Java 如何使用 PDFBox 从 HTML 创建 PDF 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19713479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:37:52  来源:igfitidea点击:

How to create a PDF file from HTML using PDFBox?

javapdfpdfbox

提问by vsingh

I am trying to create a PDF from HTML content.

我正在尝试从 HTML 内容创建 PDF。

public byte[] generatePdf(final XhtmlPDFGenerationRequest request) {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PDDocument document = new PDDocument();
    InputStream stream = new ByteArrayInputStream(request.getContent()
            .getBytes());

    PDStream pdstream = new PDStream(document, stream);
    document.save(baos);
    document.close();
    return this.toByteArray(baos);

}

When I take this byte[]and save to a file, the file is blank. I am using PDStreamto embed the input stream into the document

当我把它byte[]保存到文件中时,文件是空白的。我正在使用PDStream将输入流嵌入到文档中

From the http://pdfbox.apache.org/apidocs/

来自http://pdfbox.apache.org/apidocs/

public PDStream(PDDocument doc,
                InputStream str)
         throws IOException

Reads all data from the input stream and embeds it into the document, this will close the InputStream.

从输入流中读取所有数据并将其嵌入到文档中,这将关闭InputStream.

采纳答案by vsingh

I was looking for an HTML to PDF renderer. We were using iText. I was looking to do same with Apache PDFBox. But, it looks like it cannot be done.

我正在寻找一个 HTML 到 PDF 渲染器。我们正在使用 iText。我希望对 Apache PDFBox 做同样的事情。但是,好像做不到。

I can either use Apache FOPor continue using iText.

我可以使用Apache FOP或继续使用 iText。

Here is the iText solution if anyone is interested: Java Render XML Document as PDF

如果有人感兴趣,这里是 iText 解决方案: Java Render XML Document as PDF

If you are looking for a solution for merging using PDF box, here it is Merge pdf files using Apache pdf box

如果您正在寻找使用 PDF 框合并的解决方案,这里是 Merge pdf files using Apache pdf box