简体   繁体   English

如何将html字符串转换为PDF InputStream?

[英]How to convert an html String to a PDF InputStream?

If we have string with a content of a html page, how can we convert it to a InputStream made after transform this string to a pdf document? 如果我们有一个包含html页面内容的字符串,那么在将该字符串转换为pdf文档之后,如何将其转换为InputStream

I'm trying to use iText with XMLWorkerHelper , and this following code works, but the problem is I don't want the output on a file. 我正在尝试将iText与XMLWorkerHelper一起使用,并且以下代码可以工作,但是问题是我不希望将输出输出到文件中。 I have tried several variations in order to get the result on a InputStream that I could convert to a Primefaces StreamedContent but no success. 我尝试了几种变体,以便在InputStream上获得结果,可以将其转换为Primefaces StreamedContent,但没有成功。 How we can do it? 我们该怎么做?

Is there another technique that we can use to solve this problem? 还有另一种技术可以用来解决这个问题吗? The motivation to this is use xhtml files wich is already rendered and output it as a pdf to be downloaded by the user. 这样做的动机是使用已经渲染的xhtml文件,并将其输出为pdf,以供用户下载。

Document document = new Document();

PdfWriter writer = PdfWriter.getInstance(document,

    new FileOutputStream("results/loremipsum.pdf"));

document.open();

XMLWorkerHelper.getInstance().parseXHtml(writer, document,

    new FileInputStream("/html/loremipsum.html"));

document.close();

If you need an InputStream from which some other code can read the PDF your code produces, you can simply create the PDF using a byte array output stream and thereafter wrap the byte array from that stream in a byte array input stream: 如果您需要一个InputStream ,其他代码可以从中读取该代码生成的PDF,则可以简单地使用字节数组输出流创建PDF,然后将该字节流中的字节数组包装到字节数组输入流中:

ByteArrayOutputStream baos = new ByteArrayOutputStream();

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, baos);
document.open();
XMLWorkerHelper.getInstance().parseXHtml(writer, document, new FileInputStream("/html/loremipsum.html"));
document.close();

ByteArrayInputStream pdfInputStream = new ByteArrayInputStream(baos.toByteArray());

You can optimize this a bit by creating and processing the PDF in different threads and using a PipedOutputStream and a PipedInputStream instead. 您可以通过在不同线程中创建和处理PDF并使用PipedOutputStreamPipedInputStream来稍微优化一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM