Vee*_*era 5 java pdf-generation itext html-parsing
我有一些HTML内容(包括格式标签,如strong图像等).在我的Java代码中,我想将此HTML内容转换为PDF文档而不会丢失HTML格式.
无论如何在Java中使用它(使用iText或任何其他库)?
我用ITextRenderer从飞碟项目.
这是一个简短,独立,有效的例子.在我的情况下,我想稍后将字节流式传输到电子邮件附件中.
因此,在示例中,我将其写入文件纯粹是为了演示此问题.这是Java 8.
import com.lowagie.text.DocumentException;
import org.apache.commons.io.FileUtils;
import org.xhtmlrenderer.pdf.ITextRenderer;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
public class So4712641 {
public static void main(String... args) throws DocumentException, IOException {
FileUtils.writeByteArrayToFile(new File("So4712641.pdf"), toPdf("<b>You gotta walk and don't look back</b>"));
}
/**
* Generate a PDF document
* @param html HTML as a string
* @return bytes of PDF document
*/
private static byte[] toPdf(String html) throws DocumentException, IOException {
final ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(html);
renderer.layout();
try (ByteArrayOutputStream fos = new ByteArrayOutputStream(html.length())) {
renderer.createPDF(fos);
return fos.toByteArray();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这给了我
为了完整起见,这里是我Maven的相关部分 pom.xml
<dependencies>
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf</artifactId>
<version>9.0.8</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
</dependencies>
Run Code Online (Sandbox Code Playgroud)
我会尝试DocRaptor.com。它将任何语言的 html 转换为 pdf 或 html 转换为 xls,并且由于它使用 Prince XML(无需您支付昂贵的许可费),因此质量比其他选项要好得多。它也是一个网络应用程序,因此无需下载任何内容。解决冗长、令人沮丧的编码的简单方法。
以下是一些示例: https://docraptor.com/documentation#coding_examples
| 归档时间: |
|
| 查看次数: |
17278 次 |
| 最近记录: |