Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iTextSharp creates PDF with blank pages

I've just added the iTextSharp XMLWorker nuget package (and its dependencies) to my project and I'm trying to convert the HTML from a string into a PDF file, even though no exceptions are being thrown, the PDF file is being generated with two blank pages. Why?

The previous version of the code was using just iTextSharp 5.5.8.0 with HTMLWorker and ParseList method, then I switched to

Here is the code I'm using:

public void ExportToPdf() {
 string htmlString = "";

 Document document = new Document(PageSize.A4, 40, 40, 40, 40);
 var memoryStream = new MemoryStream();

 PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
 document.Open();

 htmlString = sbBodyMail.ToString();

 XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, new StringReader(htmlString));

 document.Close();
 DownloadFile(memoryStream);
}

public void DownloadFile(MemoryStream memoryStream) {
 //Clears all content output from Buffer Stream
 Response.ClearContent();
 //Clears all headers from Buffer Stream
 Response.ClearHeaders();
 //Adds an HTTP header to the output stream
 Response.AddHeader("Content-Disposition", "attachment;filename=Report_Diagnosis.pdf");
 //Gets or Sets the HTTP MIME type of the output stream
 Response.ContentType = "application/pdf";
 //Writes the content of the specified file directory to an HTTP response output stream as a file block
 Response.BinaryWrite(memoryStream.ToArray());
 //Response.Write(doc);
 //sends all currently buffered output to the client
 Response.Flush();
 //Clears all content output from Buffer Stream
 Response.Clear();
}

If I place document.Add(new Paragraph("Just a test")); right before document.Close(); the paragraph is rendered in the second page, but the rest of the document still is blank.

UPDATE

I've changed the HTML in the htmlString variable to just a DIV and a TABLE and it worked. So, now the question becomes: how do I know what part of the HTML is causing some error in the XMLWorker?

like image 800
Juliano Nunes Silva Oliveira Avatar asked Feb 16 '16 17:02

Juliano Nunes Silva Oliveira


1 Answers

I've figured out that XMLWorkerHelper was having trouble with DIV width attribute (even set on style attribute) and unfortunately it doesn't throw any exception to help you on this.

I found this answer from iTextSharp's developer that says that centering a table isn't supported yet, so I'm assuming this is not supported too.

like image 113
Juliano Nunes Silva Oliveira Avatar answered Nov 10 '22 18:11

Juliano Nunes Silva Oliveira