Render a XML file to PDF in byte [] format

时间:2018-06-04 17:41:05

标签: java pdf itext flying-saucer

I am rendering an XML file to a PDF file using flying saucer/iText. I would like to know if there is any way that I can save the rendered PDF file as ByteOutputStream or byte [] rather than having it as a file. I am using the below code. Any help is greatly appreciated.

byte[] bytes = outputStream.toByteArray();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document1 = builder.parse(new ByteArrayInputStream(bytes));
String outputFile = "generated/pdfOutput/document.pdf";
OutputStream out = new FileOutputStream(outputFile);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(document1, null);
renderer.layout();
renderer.createPDF(out);
out.close();

1 个答案:

答案 0 :(得分:1)

尝试类似的东西。

byte[] bytes = outputStream.toByteArray();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document1 = builder.parse(new ByteArrayInputStream(bytes));

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(document1, null);
renderer.layout();
renderer.createPDF(baos);
byte[] byteArray = baos.toByteArray();
baos.close();