The Complete Responsive CMS Blog created by Francesco Malagrino

Create in Java a PDF with OpenPDF

Category: Java & Written by Francesco Malagrino On April-21-2021 02:38:23

This Post will be dedicate to Java and the manipulation of the PDF.


We will see how we can create a basic PDF using OpenPDF a free library.


It is a great alternatives to Itext, that is another famous Java library that manipulate the PDF


We will see a basic example. First of all we need to import the Depedency so we need add to the POM the following lines :



<dependency>
<groupId>com.github.librepdf</groupId>
<artifactId>openpdf</artifactId>
<version>1.3.25</version>
</dependency>


and then this is the class that will create a PDF :

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {

public static void main(String[] args) {
try {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("C:/PDF/test.pdf"));
document.open();
document.add(new Paragraph("TEST!"));
document.close();
}catch (DocumentException | IOException e){
System.out.println(e.getMessage());
}
}
}


If you have done everything correctly you will have a pdf called test with inside TEST!!


Happy Coding


Share


Comments

Share your thoughts about this post