Skip to content Skip to sidebar Skip to footer

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 XMLWorkerHe

Solution 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 = newByteArrayOutputStream();

Documentdocument = newDocument();
PdfWriter writer = PdfWriter.getInstance(document, baos);
document.open();
XMLWorkerHelper.getInstance().parseXHtml(writer, document, newFileInputStream("/html/loremipsum.html"));
document.close();

ByteArrayInputStream pdfInputStream = newByteArrayInputStream(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.

Post a Comment for "How To Convert An Html String To A Pdf Inputstream?"