用PDFBox生成的PDF为空白 [英] PDF generated with PDFBox is blank

查看:154
本文介绍了用PDFBox生成的PDF为空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

产生的PDF文件为空.该文件的内容为:

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. 您已在保存文档后而不是之前关闭了 contentStream .

您尚未设置字体.

对我有用的代码(删除了异常处理):

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();

这篇关于用PDFBox生成的PDF为空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆