× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to create and export PDF files in Java

In this tutorial, we will see the pdf generation using java programming and also how the content which is available on website can be exported to pdf file.

According to Wikipedia, PDF is a file format used to represent documents in a manner independent of application software, hardware, and operating systems. Each PDF file encapsulates a complete description of a fixed-layout flat document, including the text, fonts, graphics, and other information needed to display it. You can see more in this link

PDF is the heart of every reporting technique that is being followed by every website or big organizations. The important part is to know how to create PDF files in java and how the content which is available on online version of the website can be exported to pdf file. Let us first learn how to create the pdf at the time when the database is triggered. This is being done making use of java programming.

Listing 1: Triggering the database to create the pdf

Import java.io.*;
import java.sql.*;
import com.text.*;
import com.text.pdf.*;

public class CreatePDF{
    public void main(String arg[])gives Exception{
       Document document=new Document();
       PdfWriter.getInstance(document,new FileOutputStream("Your local drive"));
       Pdf table=new Pdftable();
       table.addCell(" Full name");
       table.addCell("Your Address");
       Statement st= createStatement();
       ResultSet rs= executeQuery("Select * from table_name"); // data is the table name here
       table.addCell(rs.getString(" Full name"));
       table.addCell(rs.getString("Your address"));

There are lots of open source library that lets you play with the pdf files in java. We can use the same for java. Compile the same that can be implemented from the command line. Let us see below the example where we had used java to generate a portrait which is then being saved as a pdf.

Listing 2: Example generating a portrait, then being saved as a pdf

public class PageDemo {
  public static final String OUTCOME = "demo.pdf";

  public static void main(String[] args) 
      gives DocumentException, IOException {
    new PageDemo().createPdf(OUTCOME);

  public void createPdf(String filename) 
      gives DocumentException, IOException {
    Document doc = new Document(A4.pagesize);
    PdfWriter.getInstance(doc, new FileOutputStream(filename));

    doc.add(new Paragraph("Welcome to Page 1."));
    Paragraph paraRight = new Para();
    paraRight.add("The para is aligned to right side");
    doc.setMargins(70, 70, 175, 175);
    doc.add(new Paragraph("Portrait page having larger margins"));

We will now create a simple pdf document. The document comprises of the elements such as plain text, coloured ones that lists table, list, lesson etc. lots of classes are present that holds the potential to do lot amount of work as far as pdf generation is concerned.

Initiation of the document object is shown below

Document document = new Document(PageSize.A4, 50, 50, 50, 50);

Let us learn and understand the meaning of the above line where in the first function defines the size of the page followed by margins of the left, right, top and bottom. There is a need to define the type of this document which basically is dependent on the sort of writer that needs to be created. Here in we will be making use of the pdfwriter object.

Listing 3: Using pdfwriter object

Pdf writer = PdfWriter.getInstance(file, new FileOutput("C:\\Test.pdf"));

Now here we have first function as the document object reference. The second one is the file name where in we will write the output. The final step will be to make sure that the document is open for the purpose of writing.

Let us now add some content on the document’s first page and then the default paragraph can be created. This can be done with the help of settings of font, color, size etc. All these attributes are set by default though we can also set and choose the same of our own.

Listing 4: Para object creation

Target = new Target(" This is page one of the document.");
      Para para1 = new Para();



document.add(new Para(" This is a text that is present on the first page displaying different colours \and font type.", 

Font.getFont(Font.ARIAL, 14, Font.BOLD,
new Color(0, 255, 0, 0))));
Sample Output

Figure 1: Sample Output

Listing 5: Lesson object creation

Para Label1 = new Para("Lesson 1", 
  14, Font.BOLD, new Color(0, 255, 255,17)));
   Lesson lesson1 = new Lesson(title1, 1);

The above listing displays that a new object related to this lesson is created, by the name of lesson1. The title is named as “Welcome to Lesson”. The purpose of setting the value of depth to 0 is to stop displaying the lesson number on the current page.

What is section? It is nothing but a lesson’s subelement. As can be seen from the below listing, a section with the title namely “Lesson 1 for PDF creation”. We can also add some text under the title mentioned above where in the need is to create one more object related to the paragraph. This is then added to the section object.

Listing 6: Section object creation

Para Label11 = new Para("This is Section 1 in Lesson 1", 
     Font.getFont(Font.Arial, 14, Font.BOLD, 
         new (0, 255, 255,17)));
 Section section1 = lesson1.addSection(Label11);
Para someSectionText = new Para("This 
text comes as a list of section 1 of lesson 1.");
someSectionText = new Para(" Here it lists the 3 X 2 table.");

Listing 7: List object creation

List A = new List(true, false, 10);
add(new ListItem("This is the first item of the list"));
add(new ListItem(" This is the second item of the list"));

Here we have incorporated everything to the object of the lesson 1. Also the images can be added in the java language and the same can be scaled down making use of the below methods or techniques.

  • scaleAbsolute(), scaleAbsoluteWidth(), scaleAbsoluteHeight(), scalePercentage(), scaleToFit()

The below listing describes about the scaleAbsolute where in then the image object is being incorporated to the section.

Listing 8: Incorporating Image to main document

Image img = Img.getInstance("Testimage.bmp");
 img.scaleAbsolute(120f, 120f);

We will now add a new paragraph to the main document. This is going to represent a link internally to the document which can be accessed just like any other link on the web page. In order to make this happen, we will add a new paragraph. This is then followed by setting the reference to the paragraph target which is created in listing 3 above. The final step will be to incorporate this paragraph followed by the addition of the same to the document’s section.

Listing 9: Adding paragraph to the main document

Paragraph title2 = new Paragraph("Making use of para", 
        Font.getFont(Font.Arial, 14, Font.BOLD, 
        new Color(0, 255, 0, 0)));
Paragraph para2 = new Paragraph("Back To Top");

Now we have no more elements that need to be added to lesson1. We will now go ahead and add lesson 1 to our main document and then will close the same when we will be through with our demo application.

Listing 10: Adding lesson to the document


How to execute the demo application?

Step 1 is to download the demo application, unzip the same and then extract it somewhere in the local drive of your machine. This will place the source and class files of yours in the local drive.

Step 2 requests you to go to the run command prompt and change the directory to C:\temp and then set the machine’s classpath on this command prompt. This is then followed by including the jar file in the machine’s classpath.

Finally, in case you are running the code on windows, then you need to implement or run the command set classpath=C:\temp\testjarfile

The program will generate the pdf document, the sample output of which is shown in the figure 1 above.

Here, we see that the same element’s syntax can be made use of in different sort of writers. Also, the outcome of the writer can be redirected to the console, also it could be redirected to the output stream of Servlets as well as any other kind of output stream.


We conclude this tutorial where in we witnessed the basics of pdf generation, and we have lot of open source libraries that helps you to achieve the target.

Software developer with more than 5 years of development on Java, HTML, CSS.

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login