How to export PDFBox (pdf file) by response? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to export PDFBox (pdf file) by response? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I need to export PDF file by controller to an user. My REST is look like that however it returns empty file.

@RequestMapping(value="/pdfReport", method=RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
public void downloadPDFReport(HttpServletResponse response, @RequestBody PDFReport pdfReport) throws IOException{

    StringBuilder sB = storageManager.getPDF(pdfReport);
    System.out.println(sB.toString());

    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.setFont(PDType1Font.TIMES_ROMAN, 12);
    contentStream.beginText();
    contentStream.showText(sB.toString());
    contentStream.endText();
    contentStream.close();

    document.save("pdfBoxHelloWorld.pdf");

    PDStream pdfStream = new PDStream(document);
    InputStream inputStream = pdfStream.createInputStream();
    FileCopyUtils.copy(inputStream, response.getOutputStream());
}

I print out StringBuilder so I am 100% sure that the content of StringBuilder is correct.

Answer

Your code

PDStream pdfStream = new PDStream(document);
InputStream inputStream = pdfStream.createInputStream();
FileCopyUtils.copy(inputStream, response.getOutputStream());

does not make any sense, according to the JavaDocs of that PDStream constructor

/**
 * Creates a new empty PDStream object.
 * 
 * @param document The document that the stream will be part of.
 */
public PDStream(PDDocument document)

pdfStream is a new empty PDStream object which is part of document. Thus, it does not surprise at all that it returns empty file.

Consider using simply

document.save(response.getOutputStream());

instead.

Alternatively, if in your streaming context a content length property needs to be set before actually streaming the content, do something like this:

try (   ByteArrayOutputStream baos = new ByteArrayOutputStream()   )
{
    [...]
    doc.save(baos);
    byte[] bytes = baos.toByteArray();

    [... set response content length property to bytes.length ...]

    response.getOutputStream().write(bytes);
}
We are here to answer your question about How to export PDFBox (pdf file) by response? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji