Java: Create a PDF Document

Generating PDFs through code provides various advantages. It enables integration of dynamic content such as real-time data, database records, and user input. Code-based PDF creation offers greater customization and automation, reducing manual involvement in developing personalized documents. In this article, you will learn how to create a simple PDF document from scratch in Java using Spire.PDF for Java.

Install Spire.PDF for Java

First, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.


Background Knowledge

A page in Spire.PDF for Java (represented by PdfPageBase class) consists of client area and margins all around. The content area is for users to write various contents, and the margins are usually blank edges.

As shown in the figure below, the origin of the coordinate system on the page is located at the top left corner of the client area, with the x-axis extending horizontally to the right and the y-axis extending vertically down. All elements added to the client area must be based on the specified coordinates.

Java: Create a PDF Document

In addition, the following table lists the important classes and methods, which can help you easily understand the code snippet provided in the following section.

Member Description
PdfDocument class Represents a PDF document model.
PdfPageBase class Represents a page in a PDF document.
PdfSolidBrush class Represents a brush that fills any object with a solid color.
PdfTrueTypeFont class Represents a true type font.
PdfStringFormat class Represents text format information, such as alignment, characters spacing and indent.
PdfTextWidget class Represents the text area with the ability to span several pages.
PdfTextLayout class Represents the text layout information.
PdfDocument.getPages().add() method Adds a page to a PDF document.
PdfPageBase.getCanvas().drawString() method Draws string on a page at the specified location with specified font and brush objects.
PdfTextWidget.draw() method Draws the text widget on a page at the specified location. method Saves the document to a PDF file.

Create a PDF Document from Scratch in Java

Despite the fact that Spire.PDF for Java enables users to add various elements to PDF documents, this article demonstrates how to create a simple PDF document with only plain text. The following are the detailed steps.

  • Create a PdfDocument object.
  • Add a page using PdfDocument.getPages().add() method.
  • Create brush and font objects.
  • Draw string on the page at a specified coordinate using PdfPageBase.getCanvas().drawString() method.
  • Create a PdfTextWidget object to hold a chunk of text.
  • Draw the text widget on the page at a specified location using PdfTextWidget.draw() method
  • Save the document to a PDF file using method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.PdfPageSize;

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

public class CreatePdfDocument {

    public static void main(String[] args) throws IOException {

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

        //Add a page
        PdfPageBase page = doc.getPages().add(PdfPageSize.A4, new PdfMargins(35f));

        //Specify title text
        String titleText = "What is MySQL";

        //Create solid brushes
        PdfSolidBrush titleBrush = new PdfSolidBrush(new PdfRGBColor(Color.BLUE));
        PdfSolidBrush paraBrush = new PdfSolidBrush(new PdfRGBColor(Color.BLACK));

        //Create true type fonts
        PdfTrueTypeFont titleFont = new PdfTrueTypeFont(new Font("Times New Roman",Font.BOLD,18));
        PdfTrueTypeFont paraFont = new PdfTrueTypeFont(new Font("Times New Roman",Font.PLAIN,12));

        //Set the text alignment via PdfStringFormat class
        PdfStringFormat format = new PdfStringFormat();

        //Draw title on the page
        page.getCanvas().drawString(titleText, titleFont, titleBrush, new Point2D.Float((float)page.getClientSize().getWidth()/2, 20),format);

        //Get paragraph text from a .txt file
        String paraText = readFileToString("C:\\Users\\Administrator\\Desktop\\content.txt");

        //Create a PdfTextWidget object to hold the paragraph content
        PdfTextWidget widget = new PdfTextWidget(paraText, paraFont, paraBrush);

        //Create a rectangle where the paragraph content will be placed
        Rectangle2D.Float rect = new Rectangle2D.Float(0, 50, (float)page.getClientSize().getWidth(),(float)page.getClientSize().getHeight());

        //Set the PdfLayoutType to Paginate to make the content paginated automatically
        PdfTextLayout layout = new PdfTextLayout();

        //Draw paragraph text on the page
        widget.draw(page, rect, layout);

        //Save to file


    //Convert a .txt file to String
    private static String readFileToString(String filepath) throws FileNotFoundException, IOException {

        StringBuilder sb = new StringBuilder();
        String s ="";
        BufferedReader br = new BufferedReader(new FileReader(filepath));
        while( (s = br.readLine()) != null) {
            sb.append(s + "\n");
        String str = sb.toString();
        return str;

Java: Create a PDF Document

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.