Create a PDF Document in Java

This following code snippets demonstrate how to use Spire. PDF for Java to create PDF documents in Java programs, including how to create fonts, how to center text, how to draw text in a specified rectangular area, how to paginate content automatically, and so on.

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 FileNotFoundException, IOException  {

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

        //add a page
        PdfPageBase page = doc.getPages().add();

        //heading text
        String heading = "Java - Overview";

        //create solid brush objects
        PdfSolidBrush brush1 = new PdfSolidBrush(new PdfRGBColor(Color.BLUE));
        PdfSolidBrush brush2 = new PdfSolidBrush(new PdfRGBColor(Color.BLACK));

        //create true type font objects
        PdfTrueTypeFont font1= new PdfTrueTypeFont(new Font("Times New Roman",Font.PLAIN,20));
        PdfTrueTypeFont font2= new PdfTrueTypeFont(new Font("Arial Unicode MS",Font.PLAIN,12));

        //set the text alignment via PdfStringFormat class
        PdfStringFormat format1 = new PdfStringFormat();
        format1.setAlignment(PdfTextAlignment.Center);

        //draw heading on the center of the page
        page.getCanvas().drawString(heading, font1, brush1, new Point2D.Float((float)page.getActualBounds(true).getWidth()/2, 0),format1);

        //get body text from a .txt file
        String body = readFileToString("C:\\Users\\Administrator\\Desktop\\body.txt");

        //create a PdfTextWidget object
        PdfTextWidget widget = new PdfTextWidget(body, font2, brush2);

        //create a rectangle where the body text will be placed
        Rectangle2D.Float rect = new Rectangle2D.Float(0, 30, (float)page.getActualBounds(true).getWidth(),(float)page.getActualBounds(true).getHeight());

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

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

        //save to file
        doc.saveToFile("output/CreatePdf.pdf");
    }

    //customize a function to read 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;
    }
}

Create a PDF Document in Java