How to convert HTML to PDF and add headers/footers

5k views Asked by At

I am using HTMLWorker.ParseToList() to parse the elements from a html string. But it is deprecated. What is the replacement of that function? I found that the XMLWorker is the replacement of HTMLWorker, but it doesn't contain any ParseToList() function.

UPD: Use case: I want to make a pdf from a Html file and also want to add a header and a footer using html files.

1

There are 1 answers

1
Alexey Subach On

pdfHTML 4.0.2 allows you to make a PDF from an HTML file and add headers and footers easily in a completely declarative style (so only using HTML+CSS combination without necessity to write a lot of boilerplate code).

And you can even add page numbers to your output PDF, all with pure CSS instructions that are processed by pdfHTML.

Here is an example of an HTML file:

<!DOCTYPE html>
<html>
<body>

<style>
  #header {
    position: running(header);
  }

  #footer {
    position: running(footer);
  }

  @page {
    @top-center {
      content: element(header);
    }

    @bottom-center {
      content: element(footer);
    }
  }

  #current-page-placeholder::before {
    content: counter(page);
  }


  #total-pages-placeholder::before {
    content: counter(pages);
  }
</style>

<div id="header"><p style="color: green">This is a header</p></div>
<div id="footer"><p style="color: red">This is a footer. Page <span id="current-page-placeholder"></span>/<span id="total-pages-placeholder"></span></p></div>

<h2>An ordered HTML list</h2>

<ol>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

<ol type="1">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

<ol type="A">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

<ol type="a">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

<ol type="I">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

<ol type="i">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

</body>
</html>

Visual output result:

result

And that is achieved by a single line call:

HtmlConverter.convertToPdf(new File("in.html"), new File("out.pdf"));