gpt4 book ai didi

java - PDFBox 到字节数组长度为 0

转载 作者:行者123 更新时间:2023-11-30 08:54:59 24 4
gpt4 key购买 nike

我正在尝试使用 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;

使用 contents.getByteArray(); 后,byteArrays长度为 0,但这是为什么呢?

image of the debug values

最佳答案

这样做:

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

关于java - PDFBox 到字节数组长度为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29256604/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com