Monday 7 March 2016

Apache PDFBox: Cretae blank PDF document

Following step-by-step procedure explain, how to create a blank PDF document.

Step 1: Get new PDDocument instance.
PDDocument document = new PDDocument()

Step 2: Create new PDPage.
PDPage blankPage = new PDPage();

Step 3: Add pdf page to document. We must add at least one page for the document to be valid.
document.addPage(blankPage);

Step 4: Save the document to a file.
document.save(fileName);


Following is the complete working application.
import java.io.IOException;
import java.util.Objects;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

public class BlankPDF {

 /**
  * 
  * @param fileName
  * 
  * @return true on successful creation of blank document, else false.
  * 
  * @throws NullPointerException
  *             if fileName is null.
  */
 public static boolean createBlankPDF(final String fileName) {

  if (Objects.isNull(fileName)) {
   throw new NullPointerException("fileName shoudn't be null");
  }

  try (PDDocument document = new PDDocument()) {
   /*
    * Create a new blank page and add it to the document, we must add
    * at least one page for the document to be valid.
    */
   final PDPage blankPage = new PDPage();
   document.addPage(blankPage);

   /* Save the document to a file. */
   document.save(fileName);

   return true;
  } catch (IOException e) {
   System.out.println(e.getMessage());
   return false;
  }

 }

 public static void main(String args[]) {
  final String fileName = "/Users/harikrishna_gurram/tutorials/blank.pdf";
  boolean isFileCreated = createBlankPDF(fileName);

  if (isFileCreated) {
   System.out.println("blank.pdf is created at location " + fileName);
  } else {
   System.out.println("File creation failed");
  }
 }

 @Override
 public String toString() {
  final StringBuilder builder = new StringBuilder(50);
  builder.append("Simple Class to create Blank PDF Document");
  return builder.toString();
 }

}

Output
blank.pdf is created at location /Users/harikrishna_gurram/tutorials/blank.pdf




Previous                                                 Next                                                 Home

No comments:

Post a Comment