ITextPdf how to break a page

I am creating a pdf file from an html page using iTextPdf, for example:

iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document); TextReader reader = new StringReader(HTML); hw.Parse(reader); document.Close(); 

but my html page is big and I need to add page inhibition in certain palms.

How to add these breaks to PDF?

thanks

+7
source share
5 answers

There is HTMLWorker.ParseToList . Can't you use this?

  • Get n items from ParseToList
  • Add first x elements to PDF
  • Call NewPage to PDF
  • Add remaining items to PDF
+2
source

Since iTextSharp has limitations in understanding several HTML styles / tags.

The solution to this is a small workaround:

  • You need to create a new class that extends the HTMLWorker class and overrides the StartElement method, which gives us starting each html element.

     public class HTMLWorkerExtended : HTMLWorker { public HTMLWorkerExtended(IDocListener document): base(document) { } public override void StartElement(string tag, IDictionary<string, string> str) { if (tag.Equals("newpage")) document.Add(Chunk.NEXTPAGE); else base.StartElement(tag, str); } } 
  • In your html, add the <newpage /> wherever you want to split the page.

  • Now use the HTMLWorkerExtended class' object to parse the html.

     using (TextReader htmlViewReader = new StringReader(htmlText)) { using (var htmlWorker = new HTMLWorkerExtended(pdfDocument)) { htmlWorker.Open(); htmlWorker.Parse(htmlViewReader); } } 
+12
source

try adding the following to your HTML code:

 <div style="page-break-before:always">&nbsp;</div> 
+5
source

Use this code if you want to insert a page break:

document.NewPage ();

+1
source

Use the following:

I tried this and it works:

 <div style="page-break-after:always">&nbsp;</div> 
0
source

All Articles