简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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