Reputation: 1961
I am using iTextSharp to generate a copy of the receipt of a payment and save in a location in case it is needed afterwards. Basically I added this function in a separate C# class that takes an html and saves file. This is called from a function in an ASPX page.
It works fine but the problem that I have is that somehow the PDF is actually being returned as characters to the Response and are inserted at the beginning of my page.
I also checked with Fiddler and I can see that the response has just a lot of characters before the start of the actual html. Any thoughts on why iTextSharp and even how it inserts the characters if I am not even remotely sending anything back to the response?
public string CreatePDFInvoice(string htmlText, int invoiceID)
{
Document pdfDocument = new Document(PageSize.LETTER, 70, 55, 40, 25);
string newPDFFilePath = @"C:\temp\receipt-" + invoiceID.ToString() + "-" +DateTime.Now.Ticks.ToString() + ".pdf";
try
{
PdfWriter wri = PdfWriter.GetInstance(pdfDocument, new FileStream(newPDFFilePath, FileMode.Create));
PdfWriter.GetInstance(pdfDocument, HttpContext.Current.Response.OutputStream);
pdfDocument.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(wri, pdfDocument, new StringReader(htmlText));
}
catch (Exception ex)
{
throw ex;
}
finally
{
pdfDocument.Close();
}
return newPDFFilePath;
}
Upvotes: 0
Views: 1362
Reputation: 8785
Every time you use PdfWriter.GetInstance
you are creating a new PdfWriter
and adding this Writer
to the pdfDocument
. Then the PDF representation of every Element added to this Document will be written to the outputstream.
You are actually sending the pdf to the Reponse because you are creating a pdfWriter
that writes to HttpContext.Current.Response.OutputStream
in line 10.
PdfWriter.GetInstance(pdfDocument, HttpContext.Current.Response.OutputStream);
Upvotes: 3
Reputation: 77546
Please take a look at these two lines in your source code:
PdfWriter wri = PdfWriter.GetInstance(pdfDocument, new FileStream(newPDFFilePath, FileMode.Create));
PdfWriter.GetInstance(pdfDocument, HttpContext.Current.Response.OutputStream);
In the first of these two lines, you create a PdfWriter
that writes a PDF-file to a path on your server. If I understand your question correctly, this is the desired behavior: you want to a document for later use.
Now look at the second line. This creates a PdfWriter
instance that writes PDF bytes to the output stream of the Response
object. If I understand your question correctly, this is undesired behavior. Remove this line and the undesired behavior will no longer occur.
Upvotes: 2