Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert HTML to Pdf with OpenPdf

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.

like image 943
Marco Sulla Avatar asked Dec 02 '22 11:12

Marco Sulla


1 Answers

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);
}
like image 199
Marco Sulla Avatar answered Dec 19 '22 03:12

Marco Sulla