Using kuujinbo's suggestions for improving the code, it now looks like this:
public static byte[] ConvertHtmlToPdf(string html) { html = HtmlPostProcessor.Process(html); byte[] fileData = null; int num = FontFactory.RegisterDirectory(@"C:\Windows\Fonts"); using (MemoryStream ms = new MemoryStream(html.Length)) { using (Document document = new Document(PageSize.LETTER, 50, 50, 50, 50)) { PdfWriter.GetInstance(document, ms); using (StringReader stringReader = new StringReader(html)) { List<IElement> parsedList = HTMLWorker.ParseToList(stringReader, null); document.Open(); foreach (IElement item in parsedList) { document.Add(item); } } } fileData = ms.ToArray(); } return fileData; }
The problem was that inside:
using (Document document = new Document(PageSize.LETTER, 50, 50, 50, 50))
another exception was thrown, in my case it was:
WebException: Unable to connect to the remote server
which happened because the image I used was linked inside an HTML document that was converted to PDF, pointing to another website hosted on the same server. The server had internal and external IP addresses, but I forgot to edit the hosts file on the server, so redirecting to itself using these DNS names will use internal addresses instead of external ones.
The reason for the exception message is: βThe document is not openβ because (FYI: I assume here), since I was in the block, which basically acts as the βfinalβ statement, at any time there is an exception in the iText library the document is closed, and when an attempt tries to call Dispose (which was detected in the stack trace), iText throws an error because the Document object should already be closed.
source share