PDF generated with PDFBox is blank

2019-02-26 02:52发布

I am trying to write content into a PDF file. I have written the code

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;
}

The produced PDF file is empty. The content of the file is:

%▒▒▒▒
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条回答
乱世女痞
2楼-- · 2019-02-26 03:29

You made two mistakes:

  1. You have closed the contentStream after saving the document instead of before.

  2. You haven't set a font.

Code that works for me (exception handling removed):

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();
查看更多
登录 后发表回答