Answer the question
In order to leave comments, you need to log in
Question about working with FileOutputStream and ByteArrayOutputStream?
Hello! There is a task to create pdf with xml, I use apache.Fop. There is a question about getting pdf:
1) With FileOutputStream everything is OK, the file is saved in the folder
2) With ByteArrayOutputStream I get this
(Unknown location or error) java.io.IOException: Stream closed
%PDF-1.4
%����
1 0 obj
<<
/Creator (Apache FOP Version 2.1)
/Producer (Apache FOP Version 2.1)
/CreationDate (D:20201110174444+06'00')
>>
endobj
2 0 obj
<<
/N 3
/Length 3 0 R
/Filter /FlateDecode
>>
stream
x���wTT��Ͻwz��0�z�mz��0�z�m�:��_���C�(��C .....
public byte[] convertToPDF() throws IOException, FOPException, TransformerException {
Test r = testRepo.findById(1L).orElseThrow(EntityExistsException::new);
FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI());
// 1 OutputStream out = new FileOutputStream(OUTPUT_DIR + "//output.pdf");
// 2 ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);
TransformerFactory factory = TransformerFactory.newInstance();
StreamSource xslTsource = new StreamSource(new StringReader(r.getXsl()));
Transformer transformer = factory.newTransformer(xslTsource);
Result res = new SAXResult(fop.getDefaultHandler());
StreamSource xmlSource = new StreamSource(new StringReader(r.getXml()));
transformer.transform(xmlSource, res);
} finally {
out.close();
}
return out.toByteArray();
}
Answer the question
In order to leave comments, you need to log in
At you the error is reduced to that the stream is closed earlier, than you push the data into it.
Try to form headers separately
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/pdf"));
headers.add("content-disposition", "inline; filename=" + pdfName +".pdf");
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question