I have a requirement to generate PDF file from JSON Objects and am able to produce PDF document using Apache FOP and Java. But i want to return the PDF file as ByteArrayOutputStream
and then i have to encode like this Base64.getEncoder().encodeToString(baos.toByteArray())
.
Please find the below code where am able to generate PDF file, instead of FileOutputStream
i want to return as ByteArrayOutputStream
.
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
Transformer xslfoTransformer;
try
{
xslfoTransformer = getTransformer(transformSource);
Fop fop;
try
{
fop = fopFactory.newFop
(MimeConstants.MIME_PDF, outStream);
Result res = new SAXResult(fop.getDefaultHandler());
ITextRenderer renderer = new ITextRenderer();
try
{
xslfoTransformer.transform(source, res);
File pdffile = new File("Result.pdf");
OutputStream out = new java.io.FileOutputStream(pdffile);
out = new java.io.BufferedOutputStream(out);
FileOutputStream str = new FileOutputStream(pdffile);
str.write(outStream.toByteArray());
str.close();
out.close();
}
catch (TransformerException e) {
throw e;
}
}
catch (FOPException e) {
throw e;
}
}
catch (TransformerConfigurationException e)
{
throw e;
}
catch (TransformerFactoryConfigurationError e)
{
throw e;
}