PDFBox 到字节数组长度为 0

PDFBox to byte array length 0

我正在尝试使用 PDFBox 创建 PDF 并将其附加到电子邮件中。

pdf创建代码(pdf创建成功):

    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);

     // Create a new font object selecting one of the PDF base fonts
    PDFont font = PDType1Font.HELVETICA_BOLD;

    // Start a new content stream which will "hold" the to be created content
    PDPageContentStream contentStream = new PDPageContentStream(document, page);

    // Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
    contentStream.beginText();
    contentStream.setFont(font, 12);
    contentStream.moveTextPositionByAmount(100, 700);
    contentStream.drawString("Hello World");
    contentStream.endText();

    // Make sure that the content stream is closed:
    contentStream.close();

    // Save the results and ensure that the document is properly closed:
    document.save("D:\test.pdf");
    document.close();
    PDStream contents = new PDStream(document);
    byte[] byteArray = contents.getByteArray();
    return byteArray;

byteArrays长度在使用contents.getByteArray();后大小为0,但为什么?

这样做:

document.save("D:\test.pdf");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
document.save(baos);
document.close();
return baos.toByteArray();