如何使用OpenPdf将HTML转换为Pdf [英] How to convert HTML to Pdf with OpenPdf

查看:1774
本文介绍了如何使用OpenPdf将HTML转换为Pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 OpenPDF 将HTML转换为PDF?

How can I convert an HTML to PDF with OpenPDF?

据我所知,OpenPdf是Itext 4的一个分支.不幸的是,我找不到Itext 4文档.

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

推荐答案

好吧,看来您无法仅使用OpenPDF直接完成此操作,您必须使用 flying-saucer-pdf-openpdf ,然后使用它.一个例子:

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需要XHTML语法.如果您的HTML文件有问题,则可以使用 Jsoup :

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);
}

这篇关于如何使用OpenPdf将HTML转换为Pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆