Here is a jRuby script sample showing how to use Qoppa’s PDF library jPDFProcess to add text to an existing PDF document and write “Hello World” on the document.

Using the flexible Java PDF library jPDProcess, any of the following functions could be performed: Add text and images to a PDF, print a PDF, convert PDF to images, add new pages to PDF, extract existing pages from a PDF, redact PDF, linearize PDF, extract text, digitally sign PDF, import & export form data, OCR document.

The sample below can also be adapted to use any of Qoppa’s other Java PDF libraries such as the Free jPDFWriter (create new PDF documents), jPDFOptimzer (optimize PDF), jOfficeConvert (convert Word to PDF, convert Excel to PDF), jPDFWeb (convert PDF to HTML5 or convert PDF to SVG), jPDFPreflight (convert PDF to PDF/A).

# Require Java
require 'java'

# Require jPDFProcess.jar
require 'C:/myFolder/jPDFProcess.jar'

# Java import statements
java_import java.awt.Color
java_import com.qoppa.pdfProcess.PDFDocument
java_import com.qoppa.pdfProcess.PDFPage
java_import com.qoppa.pdfProcess.PDFGraphics

begin

  # Load the document
  pdfDoc = PDFDocument.new "C:/myfolder/input.pdf", nil
  
  # Get the first page
  page = pdfDoc.getPage 0
  
  # Create Helvetica 12 pt font
  helveticaFont = PDFGraphics::HELVETICA.deriveFont 12
  
  # Draw text on the page 
  page.drawText "NEW TEXT", helveticaFont, Color::BLUE, 494, 14, nil
  
  # Save the document
  pdfDoc.saveDocument "C:/myfolder/output.pdf"
  
  # Handle exceptions
  rescue Exception => ex
    puts ex.message
    puts ex.backtrace

end

Here is the full code for the AddText.rb jruby script.

Follow the steps below to use this in your environment:

To run the script:

  1. Download jRuby: http://jruby.org/download
  2. Add the jruby/bin folder to your Path environment variable
  3. Open the command prompt and run: jruby AddText.rb
  4. Add jPDFProcess.jar and a test document “input.pdf” in the same folder