简体   繁体   中英

write on existing form-pdf with pdfbox

I am relativly new to Java and I want to replace an existing iText based Javascript with pdfbox. (Java 2.0) I have a pdf-Formsheet (but this sheet has no Acroform entries) and I want to fill it with information (Name, Birthdate and so on). The pdf is in a rectangular special size (like a contact card).

My code so far:

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

The text does not show. What am I missing here? I thought with the correct text-positions I could simply write on the pdf?

The source is working. Maybe your content.newLineAtOffset(100, 400); is too huge - out of bounds - for your little card.

By the way, you have to setLeading(float) to use newLine() meaningfuly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM