问题描述
如果我们有一个html页面内容的字符串,我们如何将它转换为在将此字符串转换为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?
我试图将iText与 但没有成功。我们如何做到这一点?
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. 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. How we can do it?
是否有另一种技术可以用来解决这个问题?
这样做的动机是使用已经呈现的xhtml文件,并将其输出为由用户下载的pdf。
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.
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();
推荐答案
如果您需要 InputStream
其他代码可以读取您的代码生成的PDF,您可以使用字节数组输出流简单地创建PDF,然后将该数据流中的字节数组包装到字节数组输入流中:
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:
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());
您可以通过在不同线程中创建和处理PDF并使用 PipedOutputStream
和一个 PipedInputStream
。
You can optimize this a bit by creating and processing the PDF in different threads and using a PipedOutputStream
and a PipedInputStream
instead.
这篇关于如何将html字符串转换为PDF InputStream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!