4

How can I convert an HTML to PDF with OpenPDF?

For what I know, OpenPdf is a fork of Itext 4. Unluckily I can't find Itext 4 documentation.

Marco Sulla
  • 14,337
  • 13
  • 54
  • 92
  • @AmedeeVanGasse: what about this? https://mvnrepository.com/artifact/com.lowagie/itext/4.2.0 – Marco Sulla Mar 17 '18 at 18:19
  • @AmedeeVanGasse: it was published by Itext Software. See also this: https://mvnrepository.com/artifact/com.lowagie/itext/4.2.2 – Marco Sulla Mar 17 '18 at 18:31
  • iText 4.2.2 was put there by me personally. It is a redirection POM that redirects to the iText 5 release that was current at the time. It's how iText Software regained control over the hijacked groupId, as described in the article linked above. – Amedee Van Gasse Mar 17 '18 at 18:33
  • iText 4.2.0 was published by weiyeh, who was an employee of InProTopia. – Amedee Van Gasse Mar 17 '18 at 18:35
  • @AmedeeVanGasse And this means that "Itext 4 does not exists" is not true. And anyway, definitively you're not helping me, furthermore for personal reasons. – Marco Sulla Mar 17 '18 at 18:40

1 Answers1

17

Ok,it seems you can't do it directly with only OpenPDF, you have to use Flying Saucer: get flying-saucer-pdf-openpdf and then use it. An example:

String inputFile = "my.xhtml";
String outputFile = "generated.pdf";

String url = new File(inputFile).toURI().toURL().toString();

ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(url);
renderer.layout();

try (OutputStream os = Files.newOutputStream(Paths.get(outputFile))) {
    renderer.createPDF(os);
}

Source.

PS: FlyingSaucer expects XHTML syntax. If you have some problems with yout HTML file, you could use Jsoup:

String inputFile = "my.html";
String outputFile = "generated.pdf";

String html = new String(Files.readAllBytes(Paths.get(inputFile)));
final Document document = Jsoup.parse(html);
document.outputSettings().syntax(Document.OutputSettings.Syntax.xml);

ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(document.html());
renderer.layout();

try (OutputStream os = Files.newOutputStream(Paths.get(outputFile))) {
    renderer.createPDF(os);
}
Marco Sulla
  • 14,337
  • 13
  • 54
  • 92