如何通过响应导出PDFBox(pdf文件)?

How to export PDFBox (pdf file) by response?

我需要通过控制器将 PDF 文件导出给用户。我的 REST 看起来像那样,但是它 returns 是空文件。

@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());
}

我打印出 StringBuilder,所以我 100% 确定 StringBuilder 的内容是正确的。

您的代码

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

没有任何意义,根据 PDStream 构造函数

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

pdfStream 是一个 新的空 PDStream 对象 ,它是 document. 的 部分因此,它 returns 空文件一点也不奇怪。

考虑简单地使用

document.save(response.getOutputStream());

相反。

或者,如果在流式传输上下文中需要在实际流式传输内容之前设置内容长度 属性,请执行以下操作:

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

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

    response.getOutputStream().write(bytes);
}