• jPDFProcess

    jPDFProcess

    jPDFProcess

    Manipulate PDF files from your Java applications. This library provides the functionality found in all our other libraries.

    TRY LIVE DEMO

jPDFProcess Developer Guide

jPDFProcess Developer Guide

EnglishGerman

Contents

javalogo
Introduction
Getting Started
Merging And Splitting
Drawing Onto A Document
Encryption And Permissions
Exporting To Images
Printing A Document
Printable / Pageable
Digitally Signing PDF documents
Working With Form Fields
Working Within a J2EE Server
ESB Server Integration
Distribution and JAR files
Javadoc API
Source Code Samples

Introduction

jPDFProcess is a Java library that can be used to create, modify and manipulate PDF documents. After modifying the document, the library can then save the document to the file system or to a Java OutputStream. When working within a J2EE application server the library can work within a servlet to serve the modified PDF documents directly to the browser client.

The library can work with existing or new documents and provides a variety of functions that can be performed on the documents:

  • Load documents from the file system as well as from URLs or Java InputStreams.
  • Split and merge documents, remove or add pages.
  • Draw new content onto new pages using standard Java Graphics drawing commands.
  • Password protect and encrypt documents. Set and modify permissions.
  • Export the document as a series of images.
  • Print documents.
  • Set and retrieve data from PDF form fields.
  • Get and set bookmarks in the document (table of contents)

With jPDFProcess, your application or server can customize and process PDF documents to deliver customized content to your customers or to automatically manage PDF content repositories.

Getting Started

The starting point for using jPDFProcess is the com.qoppa.pdfProcess.PDFDocument. This class is used to load documents into an application, manipulate them and then save or output the document. The class provides three constructors to load PDF files from the file system, a URL or an InputStream. All constructors take an additional parameter, an object that implements IPasswordHandler, that will be queried if the PDF file has requires a password to open. For PDF files that are not encrypted, this second parameter can be null:

PDFDocument pdfDoc = new PDFDocument (new URL ("http://www.mysite.com/content.pdf"), null);

The class also provides a constructor that takes no parameters to create a blank document. After the document has been loaded, the host application can then make calls to perform any of the functions available through jPDFProcess.

Merging and Splitting

PDFDocument defines a PDF document as a number of page objects. Some of the functions available in the library are accessible at a page level. For instance, when merging two documents, the host application would retrieve the pages from one document and add it to the other document:

PDFDocument pdfDoc1 = new PDFDocument ("doc1.pdf", null);
PDFDocument pdfDoc2 = new PDFDocument ("doc2.pdf", null);
for (int count = 0; count < pdfDoc1.getPageCount(); ++count) {
  pdfDoc2.appendPage (pdfDoc1.getPage (count));
}
pdfDoc2.saveDocument ("doc2.pdf");

Splitting works in a similar fashion:

PDFDocument pdfDoc1 = new PDFDocument ("doc1.pdf", null);
PDFDocument split1 = new PDFDocument();
PDFDocument split2 = new PDFDocument();
split1.appendPage (pdfDoc1.getPage(0));
split1.appendPage (pdfDoc1.getPage(1));
split2.appendPage (pdfDoc1.getPage(2));
split2.appendPage (pdfDoc1.getPage(3));
split1.saveDocument ("split1.pdf");
split2.saveDocument ("split2.pdf");

You can find more information regarding assembling PDF documents in the developer guide of our library jPDFAssemble which API is packaged with jPDFProcess.

Drawing Onto a Document

jPDFProcess lets the host application draw content on top of existing content as well as on brand new pages in a document. This feature can be used to watermark existing documents, to create PDF documents from scratch and more. To draw the content, the library provides an object that derives from the standard java Graphics2D object and overrides all methods to draw onto the PDF rather than onto a screen. The following sample draws some figures onto an existing page, then creates a new page and draws onto it:

PDFDocument pdfDoc = new PDFDocument ("doc.pdf", null);
PDFPage existingPage = pdfDoc.getPage(0);
Graphics2D g2d = existingPage.createGraphics();
g2d.setFont(PDFGraphics.COURIER.deriveFont(14f));
g2d.drawString ("This is a string", 72, 72);
g2d.drawImage (img, 100, 200, null);
 
PDFPage newPage = pdfDoc.appendNewPage (8.5 * 72, 11 * 72);
g2d = newPage.createGraphics();
g2d.drawRect (100, 100, 100, 100);
pdfDoc.saveDocument ("doc.pdf");

Encryption and Permissions

jPDFProcess can add or modify the encryption and permission settings in a document. To do this, the library provides a method, setPasswordPermissions, that takes the new passwords and permission settings. One thing to note is that a PDF file can have two different passwords, a permissions or owner password and an open or user password. The permissions password is only required when changing the permissions of a PDF file and is note required to open and view a document. The open password is required to open a document.

// Load the document
PDFDocument pdfDoc = new PDFDocument ("input.pdf", null);
 
// Create permissions object to allow printing only
PasswordPermissions perms = new PasswordPermissions (false);
perms.setPrintAllowed(true);
 
// Set document security
pdfDoc.setPasswordPermissions("owner", "user", perms, null, PasswordPermissions.ENCRYPTION_AES_128);
 
// Save the document
pdfDoc.saveDocument ("output.pdf");

The parameters to the setPasswordPermissions method are:

  • newPermissionsPwd – This will become the new permissions password.
  • newOpenPwd – This will become the new open password.
  • permissions – The PasswordPermissions object.
  • currentPermissionsPwd – This is needed in case the PDF document already has a permissions password. As stated above, this password must be provided to be able to change the permissions and security settings in a document.
  • encryptType – The encryption type to use: PasswordPermissions.ENCRYPTION_RC4, PasswordPermissions.ENCRYPTION_AES_128, etc..

You can clear all security in a document by calling the PDFDocument.clearPasswordPermissions method. This method takes the current permissions password as a parameter, this parameter can be left to null if the document doesn’t have a permissions password.

You can find more information regarding securing PDF documents in the developer guide of our library jPDFSecure which API is packaged with jPDFProcess.

Exporting to Images

jPDFProcess can create images from any of the pages in a PDF document. Using this functionality, an application can export the document into a series of images. Images can be produced as follows:

PDFDocument pdfDoc = new PDFDocument ("doc.pdf", null);
for (int count = 0; count < pdfDoc.getPageCount(); ++count) {
  BufferedImage bi = pdfDoc.getPage (count).getImage();
  // Do something with the image
}

You can find more information regarding working with images in the developer guide of our library jPDFImages which API is packaged with jPDFProcess.

Printing a Document

jPDFProcess provides the ability to print PDF documents with or without showing the printer dialog or any other user intervention. The PDFDocument object provides a couple of print methods to achieve this:

PDFDocument.print (PrintSettings printSettings);
PDFDocument.print (String printerName, PrintSettings printSettings)

The first version of the method will display a printer dialog to let the user choose the printer and printer properties. The second version of the method will print the document to the named printer without showing a dialog. If the printer name is null, the library will print to the default printer.

The second parameter, PrintSettings, controls the way that jPDFProcess will print each page. The object has several properties that can be set by the calling application:

  • AutoRotate – This setting tells jPDFProcess to detect the orientation of the PDF document and to print appropriately to the printer page. i.e. If the document is in landscape mode, the library will send it to the printer in that mode. Setting this to false will always use portrait mode when sending to the printer.
  • ShrinkToMargin – Flag used to shrink the output to fit the printer margins. When this flag is set to true, and the PDF content is larger than the printable margins on the printer, the output will be scaled down to fit within the printer margins.
  • ExpandToMargin – Flag used to expand the output to the printer margins. When this flag is set to true, and the PDF content is smaller than the printable area on the printer, the output will be scaled up to fill the printable area on the printer page.
  • CenterInPage – Flag used to center the output on the printed page. When this flag is set to true, and the PDF content is smaller than the printable area, the output will be centered on the printed page. This flag has no effect if the PDF content is larger than the printable area or if the expand to margins flag is set to true.

When a PrintSettings object is created using its default constructor, the default settings are:

  • AutoRotate = true
  • ShrinkToMargin = true
  • ExpandToMargin = false
  • CenterInPage = true

Also, by default document’s annotations are sent to the printer, but it is possible to hide them:

PrintSettings prSettings = new PrintSettings();
prSettings.setPrintAnnotations(false);
PDFDocument.print (prSettings);

You can find more information regarding printing PDF documents in the developer guide of our library jPDFPrint which API is packaged with jPDFProcess.

Printable / Pageable

In addition to providing print methods, for added flexibility, PDFDocument implements both the Printable and Pageable interfaces. By using PDFDocument in this manner, the calling application can create its own PrinterJob, set any options that it needs to, and then set PDFDocument as the job’s Printable or Pageable object.

This can be useful when the application needs to use print request attributes (javax.print.attribute.PrintRequestAttribute) for finer control of printing options such as choosing the paper size or media tray, printing in color and others.

The PDFDocument object implements Printable directly, so it can be used with a PrinterJob as follows:

PDFDocument pdfDoc = new PDFDocument ("doc.pdf", null);
PrinterJob pJob = PrinterJob.getPrinterJob();
pJob.setPrintable (pdfDoc);
 
HashPrintRequestAttributeSet printAttrSet = new HashPrintRequestAttributeSet (Chromaticity.COLOR);
pJob.print(printAttrSet);

Using PDFDocument as a Pageable in a PrinterJob is as follows:

PDFDocument pdfDoc = new PDFDocument ("doc.pdf", null);
PrinterJob pJob = PrinterJob.getPrinterJob();
pJob.setPageable (pdfDoc.getPageable (pJob));
 
HashPrintRequestAttributeSet printAttrSet = new HashPrintRequestAttributeSet (Chromaticity.COLOR);
pJob.print(printAttrSet);

You can find more information regarding printing PDF documents in the developer guide of our library jPDFPrint which API is packaged with jPDFProcess.

Digitally Signing a PDF document

There are 3 steps to add a new digital signature to a PDF document with jPDFProcess: create a new digital signature field, load digital id from a keystore to create a SignatureInformation object and apply the signature:

// Create signature field on the first page
Rectangle2D signBounds = new Rectangle2D.Double (36, 36, 144, 48);
SignatureField signField = pdfDoc.addSignatureField(0, "signature", signBounds);
 
// Load the keystore that contains the digital id to use in signing
FileInputStream pkcs12Stream = new FileInputStream ("keystore.pfx");
KeyStore store = KeyStore.getInstance("PKCS12");
store.load(pkcs12Stream, "store_pwd".toCharArray());
pkcs12Stream.close();
 
// Create signing information
SigningInformation signInfo = new SigningInformation (store, "key_alias", "key_pwd");
 
// Apply digital signature
pdfDoc.signDocument(signField, signInfo);
 
// Save the document
pdfDoc.saveDocument ("output.pdf");

To sign an existing digital signature field, you would simply replace the first step by:

// Get first signature field
SignatureField signField = pdfDoc.getAcroForm().getSignatureFields().get(0);

Working with Form Fields

Fields in a PDF file are contained in what Adobe calls an AcroForm. jPDFProcess provides access to an AcroForm object from the PDFDocument class and through this object, the host application can get the fields present in the document and get or set their data.

// Get a reference to the AcroForm:
pdfDoc.getAcroForm();

The method returns an object of type com.qoppa.pdf.form.AcroForm. The host application can then use this object to get the list of fields in the PDF document and to get individual fields by name.

// Get the list of fields in the document
Vector fieldList = pdfDoc.getAcroform().getFieldList();

The field objects in turn have methods to get or set their current value.After the application is done setting or getting values from fields, it can call the PDFDocument saveDocument method to save the updated document.

// Get a field by name and set its value
TextField companyField = (TextField) pdfDoc.getAcroForm().getField( "CompanyName");
companyField.setValue("Qoppa Software");
 
// Save the document
pdfDoc.saveDocument ("output.pdf");

You can flatten form fields in a PDF file by calling the PDFDocument.flattenFields method. This method paints the content of the fields directly into the pages and removes the fields themselves from the document. flattenFields takes a boolean as a parameter to indicate wether to paint the push buttons or not. Usually, you would want this flag to be set to false.

You can find more information regarding working with PDF forms in the developer guide of our library jPDFFields which API is packaged with jPDFProcess.

Working within J2EE

jPDFProcess can be used within a servlet in a J2EE server to load documents from a repository, customize the documents according to the state of a user connection and serve the modified document directly to a browser. The first step is to create a servlet class that responds to GET and / or POST requests. Within either of these requests, the code would look something like (assuming that res is an HttpServletResponse object):

 // Get servlet output stream
ServletOutputStream sOut = res.getOutputStream();
res.setContentType( "application/pdf" );
res.setHeader("Content-disposition", "attachment; filename=" + "report.pdf" )
 
// Load a PDF from the server file system. This PDF can come from a database or any other source
PDFDocument pdfDoc = new PDFDocument ("/pdfdocs/somedoc.pdf", null);
 
// Customize the document
Graphics2D g2d = pdfDoc.getPage (0).createGraphics();
g2d.drawString ("Custom Message", 72, 72);
 
// Save the document to the servlet output stream. When writing to this stream,
// the output goes directly to the client browser
objDocument.saveDocument(sOut);
 
// Close the server output stream
sOut.close();

Using this method, there are not temporary files necessary on the server or the client, enhancing security and performance when delivering PDF contents.

Distribution and JAR Files

Required and optional jar files for jPDFProcess can be found on the jPDFProcess Download page.

Javadoc API
Source Code Samples