I have this code that creates a PDF file and then emails it. However, when I run it, it opens and will change my entire page to PDF. How can I stop the page to open the PDF?
PdfWriter.GetInstance(document, Response.OutputStream);
Response.ContentType = "application/pdf";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
HTMLWorker htmlparser = new HTMLWorker(document);
MemoryStream memoryStream = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
document.Open();
document.Add(mainTable);
Response.Write(document);
writer.CloseStream = false;
document.Close();
memoryStream.Position = 0;
EmailPresenter.SkyMail asd = new EmailPresenter.SkyMail();
asd.SendMail("test#test.com", "This is a test email...", memoryStream, "Test.pdf");
Response.End();
I do not know this PdfWriter library. But my suggestion would be to not provide the Response.OutputStream to the PdfWriter.
Simply delete the first three lines and the Response stream will remain untouched. You might also want to remove the last line with the Response.End() method call.
Related
I am having a bizarre issue trying to convert an HTML string to a PDF. I have tried several example for the internet and all are given me this same error on the htmlparser.Parse() method.
Here is the code:
Byte[] bytes;
StringReader sr = new StringReader(sbEmail.ToString());
var pdfDoc = new itxt.Document(itxt.PageSize.LETTER_LANDSCAPE, 15, 15, 0, 0);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
using (MemoryStream memoryStream = new MemoryStream())
{
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
bytes = memoryStream.ToArray();
memoryStream.Close();
}
There is no physical file path involved yet. So how can there be a problem with a file path?
Maybe this, can help you:
https://stackoverflow.com/a/12181998/9492698
It's about HTMLWorker is deprecated and you can use XMLWorker instead.
See here for more advanced usage of XMLWorker: info
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringReader html = new StringReader(sb.ToString());
byte[] byteArray = Encoding.UTF8.GetBytes(sb.ToString());
MemoryStream stream = new MemoryStream(byteArray);
Response.Clear();
using (iTextSharp.text.Document document = new iTextSharp.text.Document())
{
PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);
document.Open();
iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(
writer, document, stream, new System.Text.UTF8Encoding()
);
}
Response.End();
So, what could be the reason that pdf doesn't display unicode characted since I have
byte[] byteArray = Encoding.UTF8.GetBytes(sb.ToString());
and
.ParseXHtml(writer, document, stream, new System.Text.UTF8Encoding());
Here is the few steps to display unicode characters in converting Html to Pdf
Create a HTMLWorker
Register a unicode font and assign it
Create a style sheet and set the encoding to Identity-H
Assign the style sheet to the html parser
Check below code
TextReader reader = new StringReader(html);
Document document = new Document(PageSize.A4, 30, 30, 30, 30);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(FileName, FileMode.Create));
HTMLWorker worker = new HTMLWorker(document);
document.Open();
FontFactory.Register("C:\\Windows\\Fonts\\ARIALUNI.TTF", "arial unicode ms");
iTextSharp.text.html.simpleparser.StyleSheet ST = new iTextSharp.text.html.simpleparser.StyleSheet();
ST.LoadTagStyle("body", "encoding", "Identity-H");
worker.Style = ST;
worker.StartDocument();
Check below link for more understanding....
Display Unicode characters in converting Html to Pdf
Hindi, Turkish, and special characters are also display during converting from HTML to PDF using this method. Check below demo image.
I generate a pdf file on the fly and save it to the server side but i need to save it to the client machine. How to achieve this..
Document doc = new Document();
MemoryStream memoryStream = new MemoryStream();
string PDFName = ProjectName + ".pdf";
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(Server.MapPath("~/ProjectFiles") + "/" +
PDFName, FileMode.Create));
doc.Open();
//PDF Content
doc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=" + PDFName);
Response.Buffer = true;
Response.Clear();
Response.OutputStream.Write(memoryStream.GetBuffer(), 0, memoryStream.GetBuffer().Length);
Response.OutputStream.Flush();
Response.End();
In Response.OutputStream.Write(memoryStream.GetBuffer(), 0, memoryStream.GetBuffer().Length);
The memoryStream length is 0. I need to download the saved pdf into Cleint machine.
Please help me to fix this issue..
You are not writing anything to memoryStream.
Since you are generating PDFs on each request there is no need to save them to the file. You could generate the PDF to the MemoryStream directly.
MemoryStream memoryStream = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);
If your PDFs are not dynamic (eg. there is no need to generate them on every request) You can generate them to the file system as you do right now and then only read them from disk:
using (MemoryStream ms = new MemoryStream())
{
using (FileStream file = new FileStream(YourPdfFile, FileMode.Open, FileAccess.Read)) {
byte[] bytes = new byte[file.Length];
file.Read(bytes, 0, (int)file.Length);
ms.Write(bytes, 0, (int)file.Length);
}
}
But this makes sens only if the PDFs are generated once and then only served from disk.
EDIT: after writing into stream it was necessary to set memoryStream position to zero because it was at the end.
You have to affect memorystream like that :
PdfWriter pdfWriter = PdfWriter.GetInstance(document, memoryStream);
I am generating the PDF using iTextSharp.i have a HTMl Page and i am Reading HTML Page then generate the PDF.but the Problem is that the half of the page is in PDF while another half of the Page is running out the page in PDF.i mean half of the Page is displayed in PDF.while half of the Page is cutting in PDF.
my code is like this in Load Event..
string fileContents;
string FilePath = Server.MapPath("print-withoutlogin.html");
StreamReader mstrFileStreamReader = new StreamReader(FilePath);
try
{
fileContents = mstrFileStreamReader.ReadToEnd();
byte[] result = createPDF(fileContents.ToString()).GetBuffer();
Response.Clear();
Response.AddHeader("Content-Length", result.Length.ToString());
Response.ContentType = "application/pdf";
Response.AddHeader("Accept-Ranges", "bytes");
Response.Buffer = true;
Response.AddHeader("Expires", "0");
Response.AddHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
Response.AddHeader("Pragma", "public");
Response.AddHeader("content-Transfer-Encoding", "binary");
Response.AddHeader("Content-Disposition", "attachment; filename=kartik.pdf");
Response.BinaryWrite(result);
Response.Flush();
Response.End();
}
catch (Exception ex)
{
throw ex;
}
finally
{
mstrFileStreamReader.Close();
}
and
private MemoryStream createPDF(string html)
{
MemoryStream msOutput = new MemoryStream();
TextReader reader = new StringReader(html);
Document document = new Document(PageSize.A4, 0, 0, 50, 50);
PdfWriter writer = PdfWriter.GetInstance(document, msOutput);
HTMLWorker worker = new HTMLWorker(document);
//worker.SetStyleSheet(styles);
// step 4: we open document and start the worker on the document
document.Open();
worker.StartDocument();
// step 5: parse the html into the document
worker.Parse(reader);
// step 6: close the document and the worker
worker.EndDocument();
worker.Close();
document.Close();
return msOutput;
}
Have you Considered using Crystal Reports? I find it much easier and you can use
pdfStream = (MemoryStream)report.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
How do one create PDF in memorystream instead of physical file using itextsharp.
The code below is creating actual pdf file.
Instead how can I create a byte[] and store it in the byte[] so that I can return it through a function
using iTextSharp.text;
using iTextSharp.text.pdf;
Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("c:\\Test11.pdf", FileMode.Create));
doc.Open();//Open Document to write
Paragraph paragraph = new Paragraph("This is my first line using Paragraph.");
Phrase pharse = new Phrase("This is my second line using Pharse.");
Chunk chunk = new Chunk(" This is my third line using Chunk.");
doc.Add(paragraph);
doc.Add(pharse);
doc.Add(chunk);
doc.Close(); //Close document
Switch the filestream with a memorystream.
MemoryStream memStream = new MemoryStream();
PdfWriter wri = PdfWriter.GetInstance(doc, memStream);
...
return memStream.ToArray();
using iTextSharp.text;
using iTextSharp.text.pdf;
Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
byte[] pdfBytes;
using(var mem = new MemoryStream())
{
using(PdfWriter wri = PdfWriter.GetInstance(doc, mem))
{
doc.Open();//Open Document to write
Paragraph paragraph = new Paragraph("This is my first line using Paragraph.");
Phrase pharse = new Phrase("This is my second line using Pharse.");
Chunk chunk = new Chunk(" This is my third line using Chunk.");
doc.Add(paragraph);
doc.Add(pharse);
doc.Add(chunk);
}
pdfBytes = mem.ToArray();
}
I've never used iTextPDF before but it sounded interesting so I took upon the challenge and did some research on my own. Here's how to stream the PDF document via memory.
protected void Page_Load(object sender, EventArgs e)
{
ShowPdf(CreatePDF2());
}
private byte[] CreatePDF2()
{
Document doc = new Document(PageSize.LETTER, 50, 50, 50, 50);
using (MemoryStream output = new MemoryStream())
{
PdfWriter wri = PdfWriter.GetInstance(doc, output);
doc.Open();
Paragraph header = new Paragraph("My Document") {Alignment = Element.ALIGN_CENTER};
Paragraph paragraph = new Paragraph("Testing the iText pdf.");
Phrase phrase = new Phrase("This is a phrase but testing some formatting also. \nNew line here.");
Chunk chunk = new Chunk("This is a chunk.");
doc.Add(header);
doc.Add(paragraph);
doc.Add(phrase);
doc.Add(chunk);
doc.Close();
return output.ToArray();
}
}
private void ShowPdf(byte[] strS)
{
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=" + DateTime.Now);
Response.BinaryWrite(strS);
Response.End();
Response.Flush();
Response.Clear();
}
Where your code has new FileStream, pass in a MemoryStream you've already created. (Don't just create it inline in the call to PdfWriter.GetInstance - you'll want to be able to refer to it later.)
Then call ToArray() on the MemoryStream when you've finished writing to it to get a byte[]:
using (MemoryStream output = new MemoryStream())
{
PdfWriter wri = PdfWriter.GetInstance(doc, output);
// Write to document
// ...
return output.ToArray();
}
I haven't used iTextSharp, but I suspect some of these types implement IDisposable - in which case you should be creating them in using statements too.