Return as ByteArrayOutputStream instead of FileOutputStream

◇◆丶佛笑我妖孽 提交于 2019-12-23 06:37:26

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/50206414/return-as-bytearrayoutputstream-instead-of-fileoutputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!