Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iTextPdf how to break page

I generate pdf file from html page using iTextPdf like:

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 large and I need to add page brakes in specific palces.

How can I add these page breaks in pdf?

Thanks

like image 506
ihorko Avatar asked Dec 19 '12 20:12

ihorko


2 Answers

Since, iTextSharp do have limitations in understanding few HTML styles/tags.

The solution to this is a little workaround:

  • You need to create a new class which extends the HTMLWorker class and overrides the StartElement method which gives us event on starting of every 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 <newpage /> tag wherever you want a page break.

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

    using (TextReader htmlViewReader = new StringReader(htmlText))
     {
        using (var htmlWorker = new HTMLWorkerExtended(pdfDocument))
          {
             htmlWorker.Open();
             htmlWorker.Parse(htmlViewReader);
          }
     }
    
like image 122
T Gupta Avatar answered Sep 28 '22 04:09

T Gupta


try adding the following in your HTML:

<div style="page-break-before:always">&nbsp;</div>
like image 25
malkassem Avatar answered Sep 28 '22 04:09

malkassem