用 PDFBox 生成的 PDF 是空白的

PDF generated with PDFBox is blank

我正在尝试将内容写入 PDF 文件。我写了代码

public ByteArrayOutputStream createPDF(String text) throws IOException, COSVisitorException {

  PDDocument document;
  PDPage page;
  PDFont font1;
  PDPageContentStream contentStream;
  ByteArrayOutputStream output = new ByteArrayOutputStream();
  document = new PDDocument();


  try {
    page = new PDPage();      
    document.addPage(page);
    contentStream = new PDPageContentStream(document, page);

    contentStream.beginText();
    contentStream.moveTextPositionByAmount( 100, 700 );
    contentStream.drawString("Hello World Hello World Hello World Hello World Hello World");
    contentStream.endText();
    System.out.println("output " + output);
    document.save(output);
    document.close();
    contentStream.close();    

  } catch (Exception e) {
    e.printStackTrace();

  } finally
  {
    logInfo("output completed");
  }
  return output;
}

生成的PDF文件为空。文件内容为:

%▒▒▒▒
1 0 obj
<<
/Type /Catalog
/Version /1.4
/Pages 2 0 R
>>
endobj
2 0 obj
<<
/Type /Pages
/Kids [3 0 R]
/Count 1
>>
endobj
3 0 obj
<<
/Type /Page
/MediaBox [0.0 0.0 612.0 792.0]
/Parent 2 0 R
/Contents 4 0 R
/Resources 5 0 R
>>
endobj
4 0 obj
<<
/Filter [/FlateDecode]
/Length 6 0 R
>>
stream
x▒
endstream
endobj
5 0 obj
<<
>>
endobj
6 0 obj
8
endobj
xref
0 7
0000000000 65535 f
0000000015 00000 n
0000000078 00000 n
0000000135 00000 n
0000000247 00000 n
0000000333 00000 n
0000000354 00000 n
trailer
<<
/Root 1 0 R
/ID [<C68578F989B81BF7DD279AE1745F6E8F> <D41D8CD98F00B204E9800998ECF8427E>]
/Size 7
>>
startxref
371
%%EOF

你犯了两个错误:

  1. 您在保存文档之后而不是之前关闭了 contentStream

  2. 您还没有设置字体。

适合我的代码(删除了异常处理):

PDDocument document;
PDPage page;
PDPageContentStream contentStream;
document = new PDDocument();

page = new PDPage();
document.addPage(page);
contentStream = new PDPageContentStream(document, page);

contentStream.setFont(PDType1Font.COURIER, 10);

contentStream.beginText();
contentStream.moveTextPositionByAmount(100, 700);
contentStream.drawString("Hello World Hello World Hello World Hello World Hello World");
contentStream.endText();
contentStream.close();
document.save(....);
document.close();