How to convert an html String to a PDF InputStream?

独自空忆成欢 提交于 2019-12-11 23:26:49

问题


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?

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?

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();

回答1:


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());

You can optimize this a bit by creating and processing the PDF in different threads and using a PipedOutputStream and a PipedInputStream instead.



来源:https://stackoverflow.com/questions/35921388/how-to-convert-an-html-string-to-a-pdf-inputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!