3

I am trying to use iTextSharp to convert some HTML mail from Outlook into PDF. Some mail gives problem to the HTMLWorker, generating exceptions.

In case this happens, I want to catch the exception and abandon the PDF creation. But I can not. What do I have to do to check and properly close the opened Document?

Bobrovsky
  • 13,789
  • 19
  • 80
  • 130
Jake
  • 11,273
  • 21
  • 90
  • 147

2 Answers2

3

Directly before calling Close() you can check the PageNumber property of your Document to see if there are any pages.

if (doc.PageNumber == 0) {
    //Do something here
}
doc.Close();

Also, the HTMLWorker class isn't being actively developed anymore. Instead, almost all new HTML parsing code is being done in a separate library called XMLWorker. See @kuujinbo's sample code here.

Community
  • 1
  • 1
Chris Haas
  • 53,986
  • 12
  • 141
  • 274
  • I just tried XMLWorkerHelper.ParseXHtml() and it is too strict! Throws exceptions on missing closing tags etc. =( I am converting HTML that I have no control over... – Jake Mar 24 '12 at 03:18
  • doc.PageNumber returns 0 for a document with one page as well.. Doesn't seem to be a good way to decide whether something was added at all. – PepiX Apr 13 '22 at 10:12
-1

Start with a new page and add your paragraphs:

Document document = new Document();

document.Open();

foreach (var item in List)
{
   document.NewPage();
   AddParagraph(item, document);
}

document.Close();
Gerard
  • 2,649
  • 1
  • 28
  • 46
  • What if List is empty? The code will break on Close() >>> System.IO.IOException: 'The document has no pages.' – PepiX Apr 13 '22 at 10:12