Adding Text To PDF Files

The Java code below uses a number of classes from PDFBox, an Apache open source project that allows for working with PDF documents.  In the code below, an existing PDF ,"C:\Template.pdf", is loaded, the first page (i.e. 0) is accessed and a ContentStream is built in APPEND mode.  The font is set to 20 point Times Roman and three lines are added to the PDF using the text in the first three passed arguments.  The fourth argument is used to make the output filename unique by appending it, and ".pdf", to "C:\Page-".  The file is saved with its new name and the document closed.

The purpose of this code is to add mailing addresses to a newsletter, but could to modified to customize any type of document, making it both personal and professional.


import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDPageContentStream.AppendMode;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

public class labels {

public static void main(String[] args) throws InvalidPasswordException, IOException {
  File file = new File("C:\Template.pdf"); 
  PDDocument document = PDDocument.load(file);
  PDPage page = document.getPage(0);
  PDPageContentStream contentStream = new PDPageContentStream(document, page, AppendMode.APPEND, true);
  contentStream.setFont(PDType1Font.TIMES_ROMAN, 20);

  contentStream.newLineAtOffset(280, 630);
  String text1 = args[0];

  contentStream.newLineAtOffset(280, 600);
  String text2 = args[1];

  contentStream.newLineAtOffset(280, 570);
  String text3 = args[2];

  String outputfile = "C:\Page-" + args[3] + ".pdf"; File(outputfile));

No comments:

Post a Comment

Process Attachments from DMARC Reporting Emails

Below is the Google App Script code I wrote to process emails and save attachments.  The purpose is stated in the comments at the top of the...