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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With