Skip to main content
查利博客

Java Reporting - PDFBox

It is very common that we need to collect data and print them out, of course the most used file format for printing is the Portable Document Format or PDF. Fortunatly Java has so many PDF libraries like iText, PDFBox, JasperReport. But some (iText) are distributed under the Affero General Public License (AGPL) license, so we cannot use it for free unless the project is also free. Luckily, we can use the PDFBox for commercial use. Check PDFBox's home page for more information. They placed lots of examples under their svn repository, I suggest you checkout the branch and import it to your favourite IDE. You can do it by using the svn client and run svn checkout http://svn.apache.org/repos/asf/pdfbox/branches/2.0/ pdf-2.0 from your terminal. In this article, I will also list some basic examples for your references.

Add PDFBox dependency #

<dependency>
  <groupId>org.apache.pdfbox</groupId>
  <artifactId>pdfbox</artifactId>
  <version>2.0.22</version>
</dependency>

An simple interface for all examples #

public interface PdfExample {
  String saveFileTo = "src/main/resources/pdf/";

  static String getFullPaths(String fileName) {
    return saveFileTo + fileName;
  }
}

Create PDF example #

public class CreatePdfExample implements PdfExample {
  public static void main(String[] args) throws IOException {
    String fileName = "create_pdf_example.pdf";
    String message = "Welcome to Zhenhua Cai's Blog!";

    PDDocument doc = new PDDocument();
    PDPage page = new PDPage();
    doc.addPage(page);

    PDFont font = PDType1Font.TIMES_ROMAN;
    float fontSize = 20f;

    float xPoints = 100f; // move rightwards
    float yPoints = 700f; // move upwards

    PDPageContentStream contents = new PDPageContentStream(doc, page);
    contents.beginText();
    contents.setFont(font, fontSize);
    contents.newLineAtOffset(xPoints, yPoints);
    contents.showText(message);
    contents.endText();
    contents.close();

    doc.save(PdfExample.getFullPaths(fileName));
    doc.close();
  }
}

Output:

Add image to PDF example #

public class AddImageToPdfExample implements PdfExample {
  public static void main(String[] args) throws IOException {
    String inputFileName = "create_pdf_example.pdf";
    String outputFileName = "add_image_to_pdf_example.pdf";
    String imageFileName = "128.png";

    PDDocument doc = PDDocument.load(new File(PdfExample.getFullPaths(inputFileName)));
    PDPage page = doc.getPage(0);

    PDImageXObject pdImage = PDImageXObject.createFromFile(PdfExample.getFullPaths(imageFileName), doc);
    PDPageContentStream contents = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true);

    float scale = 0.5f;
    float xPoints = 100f;
    float yPoints = 400f;
    contents.drawImage(pdImage, xPoints, yPoints, pdImage.getWidth() * scale, pdImage.getHeight() * scale);
    contents.close();

    doc.save(PdfExample.getFullPaths(outputFileName));
    doc.close();
  }
}

Output:

PDF to image example #

public class Pdf2ImageExample implements PdfExample {
  public static void main(String[] args) throws IOException {
    String inputFileName = "add_image_to_pdf_example.pdf";
    String outputFileName = "add_image_to_pdf_example.png";
    String outputFileFullPaths = PdfExample.getFullPaths(outputFileName);

    PDDocument doc = PDDocument.load(new File(PdfExample.getFullPaths(inputFileName)));
    int dpi = 300;
    int startPage = 1;
    int endPage = doc.getNumberOfPages();

    PDFRenderer render = new PDFRenderer(doc);
    for (int i = startPage - 1; i < endPage; i++) {
      BufferedImage image = render.renderImageWithDPI(i, dpi, ImageType.RGB);
      ImageIOUtil.writeImage(image, outputFileFullPaths, dpi);
    }

    doc.close();
  }
}

Extract text from PDF example #

public class ExtractTextExample implements PdfExample {
  public static void main(String[] args) throws IOException {
    String inputFileName = "add_image_to_pdf_example.pdf";

    PDDocument doc = PDDocument.load(new File(PdfExample.getFullPaths(inputFileName)));
    PDFTextStripper stripper = new PDFTextStripper();
    String text = stripper.getText(doc);

    System.out.println(text);
    doc.close();
  }
}

Output:

Welcome to Zhenhua Cai's Blog!
public class PrintMetadataExample {
  public static void main(String[] args) throws Exception {
    String inputFileName = "add_image_to_pdf_example.pdf";

    PDDocument doc = PDDocument.load(new File(PdfExample.getFullPaths(inputFileName)));
    PDDocumentInformation info = doc.getDocumentInformation();
    System.out.println("Author: " + info.getAuthor());
    System.out.println("Creator: " + info.getCreator());
    System.out.println("Keywords: " + info.getKeywords());
    System.out.println("Producer: " + info.getProducer());
    System.out.println("Subject: " + info.getSubject());
    System.out.println("Title: " + info.getTitle());
    System.out.println("Trapped: " + info.getTrapped());
    System.out.println("Creation Date: " + info.getCreationDate());
    System.out.println("Modification Date: " + info.getModificationDate());
  }
}