PDFBox到字节数组长度为0

时间:2015-03-25 13:09:03

标签: java javamail pdfbox

我正在尝试使用PDFBox创建PDF并将其附加到eMail。

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;

使用byteArrayscontents.getByteArray();长度为0,但为什么?

image of the debug values

1 个答案:

答案 0 :(得分:1)

这样做:

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