PDFBox Example | Create PDF File With Text in java

by Azeem Tariq

Posted 2 years ago

Last Updated 1 year ago

4546 views

 

 


In my previous article i show you how to create simple PDF with pdf example code  file but i did not show you how to add text into your PDF file and now in this  article i will show you how to add text as well as how to do formatting on it according to your needs , lets get start

PDFBox Example Java Code to Create PDF File

import java.io.IOException;
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

/**
 *
 * @author azeem
 */


public class Main {


    public static void main(String[] args) {
        
        try{
        
        System.out.println("Create Simple PDF file with Text");
        String fileName = "PdfWithtext.pdf"; // name of our file
        
        PDDocument doc = new PDDocument();
        PDPage page = new PDPage();

        doc.addPage(page);

        PDPageContentStream content = new PDPageContentStream(doc, page);
        
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 26);
        content.moveTextPositionByAmount(220, 750);
        content.drawString("Registration Form");
        content.endText();
        
        
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 16);
        content.moveTextPositionByAmount(80, 700);
        content.drawString("Name : ");
        content.endText();
        
        
        content.beginText();
        content.setFont(PDType1Font.HELVETICA, 16);
        content.moveTextPositionByAmount(80,650);
        content.drawString("Father Name : ");
        content.endText();
        
        content.beginText();
        content.moveTextPositionByAmount(80,600);
        content.drawString("DOB : ");
        content.endText();
        
        
        content.close();
        doc.save(fileName);
        doc.close();
        
        System.out.println("your file created in : "+ System.getProperty("user.dir"));

        }
        catch(IOException | COSVisitorException e){
        
        System.out.println(e.getMessage());
        
        }

    }
    
}

Output of this code

pdf file created with pdfbox example

Conclusion

In this Article we learn how to create PDF file with text ,  if you face any problem then please watch above video and in the next article i will add Images into pdf file.