Search code examples
javaxsl-fofileoutputstreamapache-fopbytearrayoutputstream

Return as ByteArrayOutputStream instead of FileOutputStream


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;
        }

Solution

  • I am slightly confused to what you are asking. I have not used Apache Fop, but will try answer this question.

    If you want to read PDF file as byte array use input streams instead.

    But if you want to use ByteArrayOutputStream that is writing bytes you basically answered your own question, try using existing BAOS that you created initially and you are using in FileOutputStream, that's assuming the byte array output stream is reading bytes via some InputStream or some other source. Second assumption is that BAOS and FOS were able to properly write PDF file you were talking about. You can simply do:

    byte[] b = outStream.toByteArray();
    String str = Base64.getEncoder().encodeToString(b);