PDFOne (for Java)
Create, edit, view, print & enhance PDF documents and forms in Java SE/EE
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.

// Create a PdfDocument instance
PdfDocument doc = new PdfDocument(); 

try {
  // Write some text on page 1
  doc.writeText("Hello, World!"); // automatically creates a blank page 

  // Save document to file
  doc.save("sample_doc1.pdf");
  doc.close();
} catch (IOException | PdfException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}   

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 and then call its "load" method with the file pathname or a memory stream containing the PDF file.

// Create a PdfDocument instance
PdfDocument doc = new PdfDocument();
try {
  // Load an existing document
  doc.load("sample_doc1.pdf");
  // Get page count and display it on console output
  System.out.println(
    "Number of pages in sample_doc1.pdf is " +
    doc.getPageCount());
  // Close document
  doc.close();      
} catch (IOException | PdfException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}

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 call the "save" method of the PdfDocument instance.

// Create a PdfDocument instance
PdfDocument doc = new PdfDocument();
try {
  // Load input document
  doc.load("sample_doc1.pdf");  
  // Write text at position (100, 100) on page 1
  doc.writeText(
    "Hello again, World!",
    100, // x-coordinate
    50); // y-coordinate
   
  // Write changes to output file
  doc.save("sample_doc2.pdf");
  doc.close();
} catch (IOException | PdfException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}

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 a different file.

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 PdfDocument instance
PdfDocument doc = new PdfDocument();
try {
  // Load an existing PDF document
  doc.load("sample_doc1.pdf");
  // 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
  doc.writeText("Hello again, World!",
                fontArialItalic, // font
                100, 50);

  // Change font properties
  fontTahomaNormal.setStrokeWidth(2);
  fontTahomaNormal.setStrokeColor(Color.RED);
  fontTahomaNormal.setColor(Color.ORANGE);
   
  // Write more text on page 1 using the Tahoma font
  doc.writeText("Hello again, World!", 
                fontTahomaNormal, // font
                100, 100);
   
  // Write modified document to output file
  doc.save("sample_doc3.pdf");
  doc.close();
} catch (IOException | PdfException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}

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 .NET Developer Tools
Gnostice Document Studio .NET

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

PDFOne .NET

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

Our Delphi/C++Builder developer tools
Gnostice Document Studio Delphi

Multi-format document-processing component suite for Delphi/C++Builder developers, covering both VCL and FireMonkey platforms.

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.

Our Java developer tools
Gnostice Document Studio Java

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

PDFOne (for Java)

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

Our Platform-Agnostic Cloud and On-Premises APIs
StarDocs

Cloud-hosted and On-Premises REST-based document-processing and document-viewing APIs

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