Is it possible to send to an html a memorystream, like a file?
The idea is not creating a file in the hard drive.
I have created the stream and I can donwload the file no problem, the problem is passing to the variable to send to the aspx page so I can use it to show the file on a particulary div.
Is it possible? without creating a file in the disk.
Best Regards and Thanks
this is the Code i have:
public string ExportMemoryPdf(DataTable dtpdf, String Path)
{
string User = System.Web.HttpContext.Current.User.Identity.Name.ToString();
string Date = DateTime.Now.ToString();
string Year = DateTime.Now.ToString("yyyy");
string Month = DateTime.Now.ToString("MM");
string Day = DateTime.Now.ToString("dd");
string Hour = DateTime.Now.ToString("hh");
string Minutes = DateTime.Now.ToString("mm");
string Seconds = DateTime.Now.ToString("ss");
string FileName = User + Day + Month + Year + Hour + Minutes + Seconds;
//Session["WhereIsIt"].ToString()
//-----------------------Chamada de Classe de Registo de Eventos--------------------------
//string Message = "The User Asked For a PDF File From the Table" + Request.QueryString["Position"] + "With the Filename: " + FileName;
string Message = "The User Asked For a PDF File From the Table With the Filename: " + FileName;
//OneGrid.ExportSettings.IgnorePaging = true;
//OneGrid.Rebind();
//RegisterFile.AddRegistry(User, Message, "Message");
//------------------------------ Variaveis para aceder a Tabela --------------------------
int columncount = dtpdf.Columns.Count;
int rowcount = dtpdf.Rows.Count;
//-------------------------------Iniciaçao de criação do documento -----------------------
Document pdf1 = new Document(PageSize.A4_LANDSCAPE.Rotate());
using (MemoryStream output = new MemoryStream())
{
pdf1.SetMargins(0, 0, 80, 50);
iTextSharp.text.Font font20 = iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.HELVETICA, 10);
//----------------------------------Preparação da Tabela ---------------------------------
PdfPTable table = new PdfPTable(columncount);
//-----------------------------------Criação de Ficheiro ---------------------------------
string path = System.Web.HttpContext.Current.Server.MapPath(Path);
//string path = System.IO.Path.GetTempPath();
//Label1.Text = path.ToString();
//PdfWriter pdfWriter = PdfWriter.GetInstance(pdf1, new FileStream(path + "/" + FileName + ".pdf", FileMode.Create));
PdfWriter pdfWriter = PdfWriter.GetInstance(pdf1, output);
//----------------------------------- Dimensões da Tabela ---------------------------------------
table.WidthPercentage = 90;
//-------------------------------Criação do Header e Footer de cada folha-------------------------
KIOSK.Classes.Header_Footer page = new Classes.Header_Footer();
//-----------------------------------Inserção de conteudos -------------------------------
pdfWriter.PageEvent = page;
pdf1.Open();
//table.AddCell(HttpContext.Current.Request.QueryString["position"].ToString());
for (int z = 0; z < columncount; z++)
{
var sabersenao = dtpdf.Columns[z].ToString();
table.AddCell(new Phrase(sabersenao, font20));
}
for (int u = 0; u < rowcount; u++)
{
int contador = 0;
while (contador < columncount)
{
var CamposCorrigidos = dtpdf.Rows[u].ItemArray[contador].ToString();
StringBuilder ConvPassword = new StringBuilder(CamposCorrigidos);
ConvPassword.Replace("&", string.Empty);
ConvPassword.Replace(" ", string.Empty);
string CamposCorrigidos2 = ConvPassword.ToString();
table.AddCell(new Phrase(CamposCorrigidos2, font20));
contador += 1;
}
}
//----------------------Abertura/Fecho e inserção do componentes necessrios ao pdf---------
pdf1.Add(table);
pdf1.Close();
//System.Web.HttpContext.Current.Response.ClearContent();
//System.Web.HttpContext.Current.Response.ClearHeaders();
//System.Web.HttpContext.Current.Response.ContentType = "application/pdf";
//System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
//System.Web.HttpContext.Current.Response.BinaryWrite(output.ToArray());
//System.Web.HttpContext.Current.Response.End();
//System.Web.HttpContext.Current.Response.Flush();
//System.Web.HttpContext.Current.Response.Clear();
//System.Web.HttpContext.Current.Response.ContentType = "application/pdf";
//System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "PdfViewer; filename=" + FileName +".PDF");
////System.Web.HttpContext.Current.Response.AddHeader("content-length", output.Length.ToString());
//System.Web.HttpContext.Current.Response.BinaryWrite(output.ToArray());
//System.Web.HttpContext.Current.Response.End();
//output.Read(pdfByte, 0, (int)pdfByte.Length);
output.Read(pdfByte, 0, (int)pdfByte.Length);
var strBase64 = Convert.ToBase64String(pdfByte);
}
return Convert.ToBase64String(pdfByte);
}
and the error:
Cannot access a closed Stream.
thansk
If you know the content type the memorystream will return, you can read the stream to a variable which handles that type and then process that.
for an example with a String, see How do you get a string from a MemoryStream?. they write a string to a memorystream and then read it back out again.
It's possible, you will have to convert your memorystream to an array of bytes. Then you will have to convert your array of bytes to a Base64 string. And finally you will have to put that base64 string into your img src
An explanation about base64 to image in html.
Take notice that this will work for images. Any other files won't work as since those files need to be downloaded and thus need to have a physical location. Unless you plan on writing a javascript handler for the filetypes you which to show.
Update:
For pdf's you can do the following, however it might not be crossbrowser compatible.
CodeBehind
//string filepath = Server.MapPath("/Temp.pdf");
byte[] pdfByte; //= Helper.GetBytesFromFile(filepath);
using(var stream = ....) {
stream.read(pdfByte,0,(int)pdfByte.length);
var strBase64=Convert.ToBase64String(pdfByte);
HTML
<object data=",<<yourBase64StringHereWithoutthesmallerthenbiggerthenquotes==>>" type="application/pdf" width="800px"></object>
Updated your code:
public string ExportMemoryPdf(DataTable dtpdf, String Path)
{
string User = System.Web.HttpContext.Current.User.Identity.Name.ToString();
string Date = DateTime.Now.ToString();
string Year = DateTime.Now.ToString("yyyy");
string Month = DateTime.Now.ToString("MM");
string Day = DateTime.Now.ToString("dd");
string Hour = DateTime.Now.ToString("hh");
string Minutes = DateTime.Now.ToString("mm");
string Seconds = DateTime.Now.ToString("ss");
string FileName = User + Day + Month + Year + Hour + Minutes + Seconds;
Request.QueryString["Position"] + "With the Filename: " + FileName;
string Message = "The User Asked For a PDF File From the Table With the Filename: " + FileName;
int columncount = dtpdf.Columns.Count;
int rowcount = dtpdf.Rows.Count;
Document pdf1 = new Document(PageSize.A4_LANDSCAPE.Rotate());
pdf1.SetMargins(0, 0, 80, 50);
iTextSharp.text.Font font20 = iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.HELVETICA, 10);
PdfPTable table = new PdfPTable(columncount);
string path = System.Web.HttpContext.Current.Server.MapPath(Path);
table.WidthPercentage = 90;
KIOSK.Classes.Header_Footer page = new Classes.Header_Footer();
for (int z = 0; z < columncount; z++)
{
var sabersenao = dtpdf.Columns[z].ToString();
table.AddCell(new Phrase(sabersenao, font20));
}
for (int u = 0; u < rowcount; u++)
{
int contador = 0;
while (contador < columncount)
{
var CamposCorrigidos = dtpdf.Rows[u].ItemArray[contador].ToString();
StringBuilder ConvPassword = new StringBuilder(CamposCorrigidos);
ConvPassword.Replace("&", string.Empty);
ConvPassword.Replace(" ", string.Empty);
string CamposCorrigidos2 = ConvPassword.ToString();
table.AddCell(new Phrase(CamposCorrigidos2, font20));
contador += 1;
}
}
var base64String = string.Empty;
using (MemoryStream output = new MemoryStream())
{
PdfWriter pdfWriter = PdfWriter.GetInstance(pdf1, output);
pdfWriter.PageEvent = page;
pdf1.Open();
pdf1.Add(table);
pdf1.Close();
bytes = output.ToArray();
var base64String = Convert.ToBase64String(bytes);
}
return base64String;
}
Related
I am new to C# and I am trying to go through each cell within a Column. I always get the "errorCS0021 Cannot apply indexing with [] to an expression of type 'Range' AnlagenSites". What do I have to change in my code?
static void Main() {
//getting Data from Excel Files
WorkBook wb = WorkBook.Load("D:\\SoftwareSolutions\\AnlagenSites\\AnlagenSites\\AnlagenSites\\2022.08.18 - DoubleCheckFS20.xlsx");
WorkSheet sheet = wb.GetWorkSheet("2022.08.18 - DoubleCheckFS20");
var Site = sheet["A1:A2"];
Console.WriteLine(Site);
var Number = sheet["B1:B2"];
for(var i =1; i <= Site.Count(); i++)
{
Site[i];//here is the error
Number[i]; // same error here
string fileName = "Test.txt";
string sourcePath = "D:\\SoftwareSolutions\\AnlagenSites\\AnlagenSites\\AnlagenSites";
//putting string together
string Bregenz = "Bregenz";
for (int j = 1; j < Site.Count(); j++)
{
string targetPath = "";
if (Site.Count(j) == Bregenz)
{
targetPath = "\\ad001\\" + Number[j] + "\\other";
}
else
{
targetPath = #"\\ad001\\" + Site[j] + "\\" + Number[j] + "\\other";
}
Console.WriteLine("Protokoll added to Site:" + Site[j] + " number:" + Number[j]);
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
.
.
.
I have the below code that i m reading from datagrid and i export to ascii file and work fine
FileInfo info = new FileInfo(#"C:\SqlExports\");
info.Directory.Create();
string fileName = condition + " " + date + ".txt";
FileStream stream = new FileStream(#"C:\SqlExports\" + fileName, FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(stream, Encoding.Default);
for (int i = 0; i < Grid.Rows.Count; i++)
{
List<string> rowprint = new List<string>();
for (int f = 0; f < Grid.Columns.Count; f++)
{
if (Grid.Rows[i].Cells[f].Value != DBNull.Value)
{ rowprint.Add(Grid.Rows[i].Cells[f].Value.ToString()); }
else
{
rowprint.Add(" ");
}
}
sw.Write(string.Format("{0,-19}", rowprint[0]) + String.Format("{0,10}", rowprint[1]) + sw.NewLine, Encoding.Default);
}
sw.Close();
I need to make my code reusable so if the grid populated with other datas to read each time what i need.
i tried
sw.Write(string.Format("0, -(rowprint[0].length + 2)", rowprint[0]) + string.Format("{"0,rowprint[1].Length + 2"} + sw.Newlinn, Encoding.Default);
but of course not working so how can i have the length plus 2 blanks and the value?
of course i know that i need a var with the columns because its time maybe the columns is 2 or 3 or etc.
I need to get the content inside each page of a crystal report viewer and export it to a pdf file so that each page becomes a separate pdf and need to zip them.
Now i'm using DotNetZip dll for this.That's fine.
The issue is that i need to get contents of each page.Please Help..Below is few lines of code
Response.ContentType = "application/zip";
Response.AppendHeader("content-disposition", "attachment; filename=Reports.zip");
int i = 1;
int PageCount = report.FormatEngine.GetLastPageNumber(new
CrystalDecisions.Shared.ReportPageRequestContext());
if(PageCount >= 1){
using (ZipFile zip = new ZipFile())
{
for (i = 1; i <= PageCount; i++){
var re = report.ExportToStream(ExportFormatType.PortableDocFormat);
string Name = "Page" + i + ".pdf";
zip.AddEntry(Name, re);
}
zip.Save(Response.OutputStream);
}
}
Finally i found the answer!!..It may help someone in future.
Response.ContentType = "application/zip";
Response.AppendHeader("content-disposition", "attachment; filename=Reports.zip");
int PageCount = report.FormatEngine.GetLastPageNumber(new
CrystalDecisions.Shared.ReportPageRequestContext());
if (PageCount >= 1)
{
using (ZipFile zip = new ZipFile())
{
for (int i = 1; i <= PageCount; i++)
{
PdfRtfWordFormatOptions pdfRtfWordOpts = ExportOptions.CreatePdfRtfWordFormatOptions();
DiskFileDestinationOptions destinationOpts = ExportOptions.CreateDiskFileDestinationOptions();
ExportRequestContext req = new ExportRequestContext();
pdfRtfWordOpts.FirstPageNumber = i;
pdfRtfWordOpts.LastPageNumber = i;
pdfRtfWordOpts.UsePageRange = true;
ExportOptions CrExportOptions = report.ExportOptions;
{
CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
CrExportOptions.FormatOptions = pdfRtfWordOpts;
req.ExportInfo = CrExportOptions;
}
Stream s = report.FormatEngine.ExportToStream(req);
string Name = "Page" + i + ".pdf";
zip.AddEntry(Name, s);
}
zip.Save(Response.OutputStream);
}
}
I have a big problem and i hope you can help me out.
I have a PDF file which I split in more files.
Problem: There is a table content (goto page X), but in the new pdf files it doesnt work anymore.
I cant find a solution to copy this table content to the new pdf files.
For your understanding:
I have three pdf files which are equal.
PDF:
Page 1:
Text
Page 2:
Contenttable:
Content x Page 3 (Goto Page 3)
Content x Page 4 ""
content x Page 5 ""
...
...
I put all these pdf files together in one big pdf. (Content table still working)
And now, i will split these back in to single once (Content table not working)
My idea was to export the content table out of the original pdf(Where table content is still working) and to import it in the new once.
But i dont know how.
Second idea: search for keywords in the PDF and change the keyword to an goto local page action.
But i find no solution how i can do this.
However in the end i want to repair the table content in each single pdf file.
any ideas?
code so far:
PdfReader reader = null;
Document sourceDocument = null;
Document remote = null;
PdfCopy pdfCopyProvider = null;
PdfImportedPage importedPage = null;
PdfStamper stamp = null;
Chunk chunk = null;
reader = new PdfReader(path);
Seitenanzahl = reader.NumberOfPages;
sourceDocument = Document(reader.GetPageSizeWithRotation(startpage));
tmp = PdfTextExtractor.GetTextFromPage(reader, startpage);
string[] strsplit = tmp.Split(' ');
vorname = strsplit[4];
nachname = strsplit[5];
ort = strsplit[6];
perso = strsplit[7];
vorname = vorname.Replace("\n", "");
vorname = vorname.Replace(" ", "");
nachname = nachname.Replace("\n", "");
nachname = nachname.Replace(" ", "");
ort = ort.Replace("\n", "");
ort = ort.Replace(" ", "");
perso = perso.Replace("\n", "");
perso = perso.Replace(" ", "");
if (Directory.Exists("test/" + ort))
{
}
else
{
DirectoryInfo di = Directory.CreateDirectory("test/" + ort);
}
outputpdfpath = "test/" + ort + "/" + "p_" + ort + "_" + perso + "_" + vorname.ToLower() + "_" + nachname.ToLower() + "_hj1_booklet_2017" + ".pdf";
pdfCopyProvider = new PdfCopy(sourceDocument,
new FileStream(outputpdfpath, FileMode.Create, FileAccess.ReadWrite));
sourceDocument.Open();
for (int i = startpage; i <= endpage; i++)
{
importedPage = pdfCopyProvider.GetImportedPage(reader, i);
pdfCopyProvider.AddPage(importedPage);
}
sourceDocument.Close();
reader.Close();
}
I am trying to send my datatable that has been filtered using user input to a report but reports can only accept datasets. The problem I have here is that I don't want to do it through SQL Server. I want to keep the information local. Is there anyway that I can send the datatable to the report, or am I SOL?
How I filtered the datagridveiw and converted it to a useable table:
// If & Try block
string filter = " (DateTime >= #" + startDateTime.ToString("MM/dd/yyyy HH:mm:ss") + "# And DateTime <= #" + endDateTime.ToString("MM/dd/yyyy HH:mm:ss") + "# And TagIndex =" + integerProdNum + " )";
view.RowFilter = filter;
passingDataToReport = view.ToTable();
obviously there are if and try blocks around these, but this is how I am trying to convert the datagridview that has been filtered back into a datatable.
Then in the report viewer I have the following code:
DataSet Data = new DataSet("Data");
reportData = DataSheet.getPassingDataToReport();
reportData.TableName = "DateTimeValue";
Microsoft.Reporting.WinForms.ReportDataSource source = new Microsoft.Reporting.WinForms.ReportDataSource("Data_DateTimeValue", reportData);
this.reportViewer1.LocalReport.DataSources.Clear();
this.reportViewer1.LocalReport.DataSources.Add(source);
this.reportViewer1.DataBind();
reportViewer1.LocalReport.Refresh();
I've looked this up extensively and have found nothing of help.
As an Aside; what is the directive that .DataBind() is associated with?
I had to send the DataTable to a pdf writer and write that out using for and if loops. I found out that you cannot send a datatable that is created in run time to a report Viewer. Code below:
public void ExportToPdfTableFULL(DataTable dt, string path)
{
Document document = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
if (path.Equals(null) | path.Equals("")) { path = defaultFilename; }
try
{
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(path + "_FULL.pdf", FileMode.Create));
}
catch (System.NotSupportedException)
{
MessageBox.Show("Invalid File Path. The PDF was saved at " + defaultFilename);
path = defaultFilename;
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(path + "_FULL.pdf", FileMode.Create));
}
catch (Exception)
{
MessageBox.Show("Please Close Your PDF Viewer to Allow the " + "\nProgram to Overwrite or change the Filename");
}
document.Open();
try
{
iTextSharp.text.Image PNG = iTextSharp.text.Image.GetInstance("EisenmannLogo.png");
document.Add(PNG);
}
catch (Exception) { }
Paragraph companyInfo = new Paragraph("\n" + companyName.Text + "-" + textBox4.Text + "\n" + phoneNumber.Text + " | " + textBox3.Text + "\n" + address.Text + "\n" + state.Text + ", " + zipCode.Text + " " + textBox2.Text + "\n");
document.Add(companyInfo);
Paragraph TagName = new Paragraph("\n" + description.Text + "\n" + "\n");
document.Add(TagName);
try
{
iTextSharp.text.Image Chart_Image = iTextSharp.text.Image.GetInstance(graphedTags[0] + "_chart.png");
Chart_Image.ScalePercent(62f);
document.Add(Chart_Image);
}
catch(Exception) { }
Paragraph Disclaimer = new Paragraph("\n" + "*The data has been printed out at " + printOutInterval + " minute intervals to reduce PDF size.*" + "\n" + "\n");
Disclaimer.Alignment = Element.ALIGN_CENTER;
int counterToShorten = 0;
for (int namesGraphed = 0; namesGraphed < graphedTags.Count; namesGraphed++)
{
Paragraph spacing = new Paragraph("\n" + "\n");
document.Add(spacing);
PdfPTable table = new PdfPTable(dt.Columns.Count-1);
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_BOLD, BaseFont.CP1252, false);
iTextSharp.text.Font fontSize = new iTextSharp.text.Font(iTextSharp.text.Font.NORMAL, 8f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
iTextSharp.text.Font fontSize1 = new iTextSharp.text.Font(bfTimes, 14, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
iTextSharp.text.Font fontSize2 = new iTextSharp.text.Font(bfTimes, 14, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.WHITE);
PdfPCell cell = new PdfPCell(new Phrase(graphedTags[namesGraphed], fontSize2));
cell.Colspan = 3;
cell.HorizontalAlignment = 1;
cell.BackgroundColor = new iTextSharp.text.BaseColor(0, 0, 0);
table.AddCell(cell);
for (int j = 1; j < dt.Columns.Count; j++)
{
PdfPCell cell2 = new PdfPCell(new Phrase(dt.Columns[j].ToString(), fontSize1));
cell2.HorizontalAlignment = 1;
cell2.BackgroundColor = new iTextSharp.text.BaseColor(185, 185, 185);
table.AddCell(cell2);
}
table.HeaderRows = 1;
for (int p = 0; p < columnHeaders.Count; p++) { Console.WriteLine(columnHeaders[p]); }
document.Add(Disclaimer);
for (int i = 0; i < (dt.Rows.Count); i++)
{
if (columnHeaders.Contains("Tagname"))
{
if (graphedTags[namesGraphed].Equals(dt.Rows[i]["Tagname"].ToString()))
{
counterToShorten++;
if (counterToShorten >= printOutInterval)
{
for (int k = 1; k < (dt.Columns.Count); k++)
{
if (!dt.Rows[i][k].Equals(null))
{
PdfPCell cell3 = new PdfPCell(new Phrase(dt.Rows[i][k].ToString(), fontSize));
cell3.HorizontalAlignment = 1;
table.AddCell(cell3);
counterToShorten = 0;
}
}
}
}
}
if (columnHeaders.Contains("TagIndex"))
{
if (graphedTags[namesGraphed].Equals(dt.Rows[i]["TagIndex"].ToString()))
{
counterToShorten++;
if (counterToShorten >=printOutInterval)
{
for (int k = 1; k < (dt.Columns.Count); k++)
{
int mulitplier = 10 * i;
if (!dt.Rows[i][k].Equals(null))
{
PdfPCell cell3 = new PdfPCell(new Phrase(dt.Rows[i][k].ToString(), fontSize));
cell3.HorizontalAlignment = 1;
table.AddCell(cell3);
counterToShorten = 0;
}
}
}
}
}
}
document.Add(table);
}
document.Close();
Here is the writer I created.