Java HTML-> PDF解决方案?

我目前正在使用Java构建基于PDF的报告。 我已经看过iText和BIRT,但似乎需要付出很多努力来学习他们正在寻找的API,这个解决方案可以让我在HTMl中生成报告(我已经知道了)并将其输出到PDF。 谁能提供一些可能的解决方案? – 谢谢! – 邓肯克雷布斯

Flying Saucer将XHTML转换为PDF。 太棒了。 它并不快。 如果您的XHTML语法中存在轻微错误,则会失败。 (例如应该是
时候)

这是让我开始的链接。 它似乎使用iText,但是一旦你有了工作,只需更改HTML并更新。

http://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html

可能有更好的方法,这就是我做的方式。

如果您的源HTML使用CSS设置样式并且不一定格式正确,请尝试使用PD4ML库(免费用于非营利性用途)。

我可以推荐jodconverter它在无头模式下使用openoffice

1安装openoffice(用于linux“zypper install libreoffice”)

2 WIN把它放在路径变量上所以“soffice”可以从任何地方运行,对我来说它是“C:\ Program Files(x86)\ LibreOffice 4 \ program”

3 LINUX确保运行java进程的用户拥有自己的主目录,因为openoffice需要在那里存储配置,对于我tomcat运行进程,但它的主目录由root拥有

4将jodconverter-lib添加到您的java项目中

  com.artofsolving jodconverter 2.2.1  

兑换

 // ensure open office is running String[] commands = new String[] {"soffice","--headless","--accept=socket,host=localhost,port=8100;urp;"}; Runtime.getRuntime().exec(commands); // convert String html = "
hey there
"; ByteArrayOutputStream pdfOutputStream = new ByteArrayOutputStream(); DefaultDocumentFormatRegistry defaultDocumentFormatRegistry = new DefaultDocumentFormatRegistry(); OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100); connection.connect(); DocumentConverter converter = new OpenOfficeDocumentConverter(connection); converter.convert(IOUtils.toInputStream(html, Charset.forName("UTF-8")), defaultDocumentFormatRegistry.getFormatByFileExtension("html"), pdfOutputStream, defaultDocumentFormatRegistry.getFormatByFileExtension("pdf")); connection.disconnect(); byte[] pdfBytes = pdfOutputStream.toByteArray();

使用phantomjs ,您可以非常轻松地将HTML转换为PDF:

 import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.phantomjs.PhantomJSDriverService; import org.openqa.selenium.remote.DesiredCapabilities; public class Screenshot { public static final String SCRIPT = "var page = require('webpage').create();\n" + "page.open('@@URL@@', function() {\n" + " page.render('@@FILE@@');\n" + "});\n"; public static void main(String[] args) { final String url = args[0]; final String file = args[1]; final String script = SCRIPT.replace("@@URL@@", url).replace("@@FILE@@", file); final DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "/path/to/phantomjs/bin/phantomjs"); try { PhantomJSDriver phantomJSDriver = new PhantomJSDriver(capabilities); phantomJSDriver.executePhantomJS(script); } finally { phantomJSDriver.close(); } } } 

如果file名以.pdf结尾,则网页将保存为PDF。 Phantomjs还支持PNG,JPG和GIF输出。

这是一个非常简单的例子,更一般地说截图过程是非常可定制的(设置视口大小,启用/禁用javascript等)。 查看PhantomJS的屏幕截图页面以获取更多信息。

JavaFx WebKit浏览器可用于html到pdf的转换。 对于Windows安装pdf24打印机驱动程序和Linux使用cups-pdf 。 安装后使用WebEngine的print方法。

如果您可以使用外部库,则可以轻松使用ui4j将网页打印为pdf。