用 pdfbox 在现有的 form-pdf 上写

write on existing form-pdf with pdfbox

我是 Java 的新手,我想用 pdfbox 替换现有的基于 iText 的 Javascript。 (Java 2.0) 我有一个 pdf-Formsheet(但是这个 sheet 没有 Acroform 条目),我想用信息(姓名、出生日期等)填充它。 pdf 为矩形特殊尺寸(如名片)。

到目前为止我的代码:

  File file = new File("ToBeFilled.pdf"); 

  PDDocument document = PDDocument.load(file); 

  System.out.println("PDF loaded"); 

 //Retrieving the page
  PDPage page = (PDPage)document.getPages().get( 0 );

  PDFont font = PDType1Font.HELVETICA_BOLD;
  PDPageContentStream content = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true);

  content.beginText();      
  //Setting the font to the Content stream  
  content.setFont(font, 30);  

  //Setting the position for the line (float x, float y), (0,0) = lower left corner
  content.newLineAtOffset(100, 400);
  String text = "This is the sample document and we are adding content to it.";
  String text1 = "This is an example of adding text to a page in the pdf document. we can add as many lines";
  String text2 = "as we want like this using the ShowText()  method of the ContentStream class";
  //Adding text in the form of string 
  content.showText(text); 
  //Adding text in the form of string
  content.newLine();
  content.showText(text1);
  content.newLine();
  content.showText(text2);

  //Ending the content stream
  content.endText();
  System.out.println("Text added"); 

  content.close();
  //Saving the document 
  document.save("newPrint.pdf");

  //Closing the document  
  document.close(); 

文字没有显示。我在这里错过了什么?我想如果文本位置正确,我可以简单地写在 pdf 上?

来源正常。 也许你的 content.newLineAtOffset(100, 400); 对于你的小卡片来说太大了 - 超出了范围。

顺便说一下,你必须 setLeading(float) 才能使用 newLine() 有意义。