PDFOne (for Java™)
Create, edit, view, print & enhance PDF documents and forms on Java™ platform
Compatibility
J2SE J2EE Windows Linux Mac (OS X)

How to Read and Write PDF Files in Java

Learn how to create, read, and write to PDF documents using PDFOne.
By Santhanam L.

The PdfDocument is the main class in PDFOne Java. It represents a PDF document and allows you to create, read, and enhance PDF documents. It offers numerous methods for you to render PDF elements such as text, images, shapes, forms, watermarks, and annotations on to documents.

Creating Your First PDF Document

Before you start writing new PDF elements, you need to first create a PDF document or load an existing document. To create a new document, you create a PdfDocument object using a PdfWriter object. When you create the PdfWriter object, you can specify the stream or the file pathname to which the PDF document needs to be saved.

// Create a PdfWriter instance
PdfWriter w = PdfWriter.fileWriter("sample_doc1.pdf");

// Create a PdfDocument instance with the PdfWriter
PdfDocument d = new PdfDocument(w);

// Write some text on page 1
d.writeText("Hello, World!");

// Write document to file
d.write();

// Close all I/O streams associated with the PDF writer
w.dispose();

After you create a new PdfDocument object, the writeText() method will allow you write text on a page, which is created by default in the document.

When you begin writing text in this manner, text will be rendered on the top-left corner of the document. Subsequent calls to the method will change this location to where the previous writeText() method had let off.

Screenshot 1: Text is rendered at default location using default font.

Reading a PDF Document

To read an existing PDF document, you need to create a PdfDocument object using a PdfReader object. When you create the PdfReader object, you can specify the stream or the file pathname from which the PDF document needs to be read.

// Create a PdfReader instance
PdfReader r = PdfReader.fileReader("sample_doc1.pdf");

// Create a PdfDocument instance with the reader
PdfDocument d = new PdfDocument(r);

// Get page count and display on console
System.out.println(
        "Number of pages in sample_doc1.pdf is " +
	d.getPageCount());
		
// Close all I/O streams associated with the PDF reader
r.dispose();

Once you create the PdfDocument object, you can use the object's methods to read from the loaded document. In the above code snippet, the number of pages in the document is retrieved.

Writing To An Existing PDF Document

If you need to make changes to an existing document, then you need to specify an output file or stream when you create the PdfReader object. Any changes that you make to the loaded PDF document is saved to this output file or stream. PDFOne Java WILL NOT overwrite the input file or stream!

// Create a PdfReader instance
PdfReader r = PdfReader.fileReader(
               "sample_doc1.pdf",   // read from (input file)
               "sample_doc2.pdf");  // write to (output file)

// Create a PdfDocument instance with the reader
PdfDocument d = new PdfDocument(r);

// Write text at position (100, 100) on page 1 
d.writeText("Hello again, World!", 
	    100,   // x-coordinate 
	    50);   // y-coordinate

// Set output file to be displayed after it is  
// written to
d.setOpenAfterSave(true);
		
// Write to output file
d.write();

// Close all I/O streams associated with the PDF reader
r.dispose();

In the above code snippet, a PDF document is loaded and another "Hello, World" text string is written at a different location (specified by x-y coordinates) on the first page using an overloaded method of PdfDocument.writeText(). This modified PDF document is then saved to the output file that was specified when creating the PdfReader object.

Screenshot 2: The "Hello, World!" text is from the original input file. The "Hello again, World!" text is rendered at a specified location.

Using Fonts and Colors

You can also render text in different fonts and colors using PdfFont objects. You can create font objects either by specifying the name of the installed font or the pathname of the font file.

// Create a PdfReader instance
PdfReader r = PdfReader.fileReader(
               "sample_doc1.pdf",   // read from (input file)
               "sample_doc3.pdf");  // write to (output file)

// Create a PdfDocument instance with the reader
PdfDocument d = new PdfDocument(r);
		
// Create font objects
PdfFont fontArialItalic = PdfFont.create(
            "Arial",    // name of installed font
	    PdfFont.ITALIC | PdfFont.STROKE_AND_FILL, 
	    18, 
	    PdfEncodings.WINANSI);		
PdfFont fontTahomaNormal = PdfFont.create(
	    "tahoma.ttf", // pathname of a font file
	    PdfFont.STROKE_AND_FILL, 
	    48, 
	    PdfEncodings.WINANSI);
		
// Write text on page 1 using the Arial font created above
d.writeText("Hello again, World!", 
            fontArialItalic,   // font
	    100, 50);

// Set font properties
fontTahomaNormal.setStrokeWidth(2);
fontTahomaNormal.setStrokeColor(Color.RED);
fontTahomaNormal.setColor(Color.ORANGE);

// Write more text on page 1 using Tahoma
d.writeText("Hello again, World!", 
	    fontTahomaNormal,      // font
	    100, 100);

// Set output file to be displayed after it is  
// written to
d.setOpenAfterSave(true);
		
// Write to output file
d.write();

// Close all I/O streams associated with the PDF reader
r.dispose();

In this revised code snippet, text has been rendered using specific fonts. This has been made possible by the use of another overloaded PdfDocument.writeText() method.

A further improvement has been made on how the text is rendered using a particular font. Colors used to fill and stroke the text have been specified by modifying the properties of the font object (Tahoma).

Screenshot 3: The first "Hello again, World!" text is rendered using Arial Italic in default black color. The second "Hello again, World!" text written using Tahoma font is filled with yellow and stroked with red. Both text strings are rendered at specified locations using specified fonts and font sizes. The "Hello, World!" text is from the existing document that was read.

We have seen the basics of using PDFOne Java. Next month, we will see how to create multiple pages, and render text, shapes, images and watermarks over them.

---o0O0o---

Downloads:

---o0O0o---

Our Free Online Document-Processing Tools
Gnostice Apps

Gnostice Apps provides several PDF document-processing services over the Web. It enables you to merge, split, convert, secure and redact PDF documents - all for FREE. All you need to access these services is a HTML5-capable browser such as the latest version of Firefox/Seamonkey or IE 11.

Our Developer Tools
eDocEngine VCL

A Delphi/C++Builder component suite for creating documents in over 20 formats and also export reports from popular Delphi reporting tools.

PDFtoolkit VCL

A Delphi/C++Builder component suite to edit, enhance, view, print, merge, split, encrypt, annotate, and bookmark PDF documents.

XtremePDFConverter VCL

A Delphi/C++Builder component to intelligently convert PDF to user-friendly Word RTF documents.

PDFOne .NET

A .NET PDF component suite to create, edit, view, print, reorganize, encrypt, annotate, and bookmark PDF documents in .NET applications.

XtremeDocumentStudio .NET

Multi-format document-processing component suite for .NET developers

PDFOne (for Java™)

A Java™ PDF component suite to create, edit, view, print, reorganize, encrypt, annotate, bookmark PDF documents in Java™ applications.

XtremeFontEngine (for Java)

Java font engine to render glyphs from Type 1, Type 2 (CFF), and TrueType fonts

Our Office Productivity Applications
Free PDF Reader

A free, fast, and portable application for viewing, printing and converting PDF documents.

Privacy | Legal | Feedback | Newsletter | Resellers © 2002-2014 Gnostice Information Technologies Private Limited. All rights reserved.

This site is best viewed on a screen with minimum resolution of 1152 x 864 pixels. Windows XP users are advised to use Microsoft ClearType Tuning for optimal experience. Also, please use the latest version of a standards-compliant browser such as Firefox, Opera, or Dragon (Chromium).