iTextSharp creates PDF with blank pages

我的梦境 提交于 2019-12-21 04:29:11

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/35438782/itextsharp-creates-pdf-with-blank-pages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!