我试图用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();
关于java - PDFBox到字节数组的长度为0,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29256604/