在 Java 中将 HTML 字符串转换为 PDF 字节数组



我需要构建一个函数,该函数以字符串的形式接收html文档,并应返回pdf文档作为byte[]

使用以下代码,我可以构建一个 pdf 文档。理想情况下,我不想先生成 pdf 文档。相反,应返回byte[],而无需先构建 pdf 文档。如何防止 pdf 生成并仅返回byte[]

到目前为止,我按照本教程获取了以下代码:https://www.baeldung.com/pdf-conversions-java

public static byte[] convertHtmlToPdfBytes( String htmlString ) throws IOException, DocumentException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("temp.pdf"));
document.open();
InputStream in = IOUtils.toInputStream(htmlString);
XMLWorkerHelper.getInstance().parseXHtml(writer, document, in);
document.close();
return null;
}

我使它成为可能,如下所示:

public static byte[] convertHtmlToPdfBytes( String htmlString ) throws IOException, DocumentException {
Document document = new Document();
ByteArrayOutputStream out = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
InputStream in = IOUtils.toInputStream(htmlString);
XMLWorkerHelper.getInstance().parseXHtml(writer, document, in);
document.close();
return out.toByteArray();
}

最新更新