DEV Community

E-iceblue Product Family
E-iceblue Product Family

Posted on

Programmatically Create PDF in Java

Overview

Spire.PDF for Java is a class library that allows you to create PDF documents directly from your Java programs without having to install any additional software. PDF files can be easily created using this library. Simply create a PdfDocument object, create as many PdfPageBase objects as necessary, draw strings, images, tables, lists and any other elements to the pages and then save the document.

In this post, I’ll give you an example of how to create a PDF containing Title, Paragraph, Image, Numbered List and Table, and how to arrange them in an appropriate position on the PDF page.

Before Start

Download Spire.PDF for Java from the webpage https://www.e-iceblue.com/Download/pdf-for-java.html. The download contains two jars which should be referenced in your Java project.

Coordinate System

A page generated by Spire.PDF consists of margins and content area. The coodinate system follows the following rules.

  • The origin of the coordinate system (0, 0) represents the top-left corner of the content area.
  • The x-axis extends to the right and the y-axis extends downward.

Format text content

Creating Custom Functions

Spire.PDF itself provides useful classes and methods, such as PdfPageBase class, drawString method and drawImage method, which work with the page settings, writing text and adding images according to the specific coordinates. In order to make the code easier to read, I pre-defined five custom functions below to perform different tasks.

  • drawTitle

When drawing a title on PDF, you may probably need to align text. The drawTitle function created based on drawString is such a function that allows to horizontally align text, for instance, to center.

public static void drawTitle(PdfPageBase page, String text, PdfFont font, PdfBrush brush, float x, float y, PdfTextAlignment alignment) {
    //set the text alignment via PdfStringFormat class
    PdfStringFormat format = new PdfStringFormat();
    format.setAlignment(alignment);
    //draw title on the page
    page.getCanvas().drawString(text, font, brush, x, y, format);
}
  • drawParagraph

The drawParagraph function is different from drawTitle, though they’re taking similar parameters. This function is created based on PdfTextWidget.draw method and returns an object of PdfLayoutResult class which contains the bounds information of the element being drawing. By doing so, you’ll be able to know where the current paragraph ends and where to start drawing the next piece of content.

public static PdfLayoutResult drawParagraph(PdfPageBase page, String text, PdfFont font, PdfBrush brush, float x, float y) {
    //create a PdfTextWidget object
    PdfTextWidget widget = new PdfTextWidget(text, font, brush);
    //set the PdfLayoutType to Paginate to make the content paginated automatically
    PdfTextLayout layout = new PdfTextLayout();
    layout.setLayout(PdfLayoutType.Paginate);
    //create a rectangle where the paragraph will be placed
    Rectangle2D.Float rect = new Rectangle2D.Float(0, y, (float) page.getClientSize().getWidth(), (float) page.getClientSize().getHeight());
    //draw paragraph on the page
    PdfLayoutResult layoutResult = widget.draw(page, rect, layout);
    return layoutResult;
}
  • drawImage

The drawImage function is a simply overloading of the original method. This function won’t returns a PdfLayoutResult object. In order to know where the content below begins, you'll need to get the image height through PdfImage object and then calculate the Y coordinate.

public static void drawImage(PdfPageBase page, PdfImage image, float x, float y) {
    //draw image on the page
    page.getCanvas().drawImage(image, x, y);
}
  • drawTable

When using the drawTable function to draw tables on a PDF page, you need to specify the table data in String[][] array. This function also returns a PdfLayoutResult object that helps us get the position and size of the table.

public static PdfLayoutResult drawTable(PdfPageBase page, String[][] dataSource, PdfFont font, float x, float y) {
    //create a PdfTable object
    PdfTable table = new PdfTable();
    //specify cell padding
    table.getStyle().setCellPadding(2);
    //set font
    table.getStyle().getDefaultStyle().setFont(font);
    //fill the table with sample data
    table.setDataSource(dataSource);
    //draw table on the page
    PdfLayoutResult layoutResult = table.draw(page, new Point2D.Float(x, y));
    return layoutResult;
}
  • drawSortedList

The last function drawSortedList is quite similar with drawTable, except that it takes some unique parameters like list content, order marker and list indent.

public static PdfLayoutResult drawSortedList(PdfPageBase page, String listContent, PdfOrderedMarker marker, PdfFont font, PdfBrush brush, float x, float y, float indent) {
    //create a sorted list based on the list content
    PdfSortedList sortedList = new PdfSortedList(listContent);
    //set the properties of the list
    sortedList.setFont(font);
    sortedList.setBrush(brush);
    sortedList.setIndent(indent);
    sortedList.setMarker(marker);
    //draw list on the page
    PdfLayoutResult layoutResult = sortedList.draw(page, x, y);
    return layoutResult;
}

Using the Code

Invoke these custom functions and you’ll be able to draw elements at the appropriate positions of a PDF page.

import com.spire.pdf.graphics.*;
import com.spire.pdf.lists.*;
import com.spire.pdf.tables.PdfTable;

import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

public class CreatePdf {

    public static void main(String[] args) {

        //create a PdfDocument object
        PdfDocument doc = new PdfDocument();
        //add a page
        PdfPageBase page = doc.getPages().add();
        //create two solid brushes
        PdfSolidBrush brush1 = new PdfSolidBrush(new PdfRGBColor(Color.BLUE));
        PdfSolidBrush brush2 = new PdfSolidBrush(new PdfRGBColor(Color.BLACK));
        //create two fonts
        PdfFont font1 = new PdfFont(PdfFontFamily.Helvetica, 15f, PdfFontStyle.Bold);
        PdfFont font2 = new PdfFont(PdfFontFamily.Helvetica, 12f);
        //initialize x, y coordinates
        float x = 0;
        float y = 0;
        //title
        String title = "Title";
        //align text to center via PdfTextAlignment class
        PdfTextAlignment alignment = PdfTextAlignment.Center;
        //draw title on the center of the page
        drawTitle(page, title, font1, brush1, (float) page.getClientSize().getWidth() / 2, y, alignment);
        y = y + 30;
        //paragraph text
        String paragraph = "This is a paragraph.(Here is the extra text for test. " +
                "Here is the extra text for test. Here is the extra text for test. " +
                "Here is the extra text for test. Here is the extra text for test.)";
        //draw paragraph on the page
        PdfLayoutResult layoutResult = drawParagraph(page, paragraph, font2, brush2, x, y);
        y = y + (float) layoutResult.getBounds().getHeight() + 10;
        //load an image file
        PdfImage image = PdfImage.fromImage("C:\\Users\\Administrator\\Pictures\\flag-of-Canada.png");
        //draw image on the page
        drawImage(page, image, x, y);
        y = y + (float) image.getPhysicalDimension().getHeight() + 10;
        //define sample data
        String[] data = {"col-1;col-2;col-3",
                "a1;a2;a3",
                "b1;b2;b3"};
        String[][] dataSource = new String[data.length][];
        for (int i = 0; i < data.length; i++) {
            dataSource[i] = data[i].split("[;]", -1);
        }
        //draw Table on the page
        layoutResult = drawTable(page, dataSource, font2, x, y);
        y = y + (float) layoutResult.getBounds().getHeight() + 10;
        //create an order marker
        PdfOrderedMarker marker = new PdfOrderedMarker(PdfNumberStyle.Upper_Roman, new PdfFont(PdfFontFamily.Helvetica, 12f, PdfFontStyle.Bold));
        //define list content
        String listString = "eBay\nGoogle\nPayPal\nYahoo\nMicrosoft";
        //draw list on the page
        drawSortedList(page, listString, marker, font2, brush2, x, y, 10);
        //save to file
        doc.saveToFile("CreatePdf.pdf");
    }

}

The resulting PDF file looks like the one below.
Format text content

Top comments (0)