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.
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);
}
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);
}
Here's a simple Kotlin HTML to PDF. Jsoup is not required.
fun pdfFromHtml(ostream: OutputStream, html: String) {
val renderer = ITextRenderer()
val sharedContext = renderer.sharedContext
sharedContext.isPrint = true
sharedContext.isInteractive = false
renderer.setDocumentFromString(html)
renderer.layout()
renderer.createPDF(ostream)
}
Here's one with Jsoup.
fun pdfFromHtml(ostream:OutputStream, html: String) {
val renderer = ITextRenderer()
val sharedContext = renderer.sharedContext
sharedContext.isPrint = true
sharedContext.isInteractive = false
val document = Jsoup.parse(html)
document.outputSettings().syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml)
renderer.setDocumentFromString(document.html())
renderer.layout()
renderer.createPDF(ostream)
}
© 2022 - 2024 — McMap. All rights reserved.