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.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>10.3.4</version>
    </dependency>
</dependencies>
    

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.
PdfDocument.save() 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 PdfDocument.save() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.PdfPageSize;
import com.spire.pdf.graphics.*;

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

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();
        format.setAlignment(PdfTextAlignment.Center);

        //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();
        layout.setLayout(PdfLayoutType.Paginate);

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

        //Save to file
        doc.saveToFile("output/CreatePdfDocument.pdf");
        doc.dispose();

    }

    //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");
        }
        br.close();
        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.