You are on page 1of 6

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"));
document.open();
Pdf table=new Pdftable();
table.addCell(" Full name");
table.addCell("Your Address");
Class.forName("com.mysql.jdbc.Driver");
Statement st= createStatement();
ResultSet rs= executeQuery("Select * from table_name"); // data is
the table name here
while(rs.next()){
table.addCell(rs.getString(" Full name"));
table.addCell(rs.getString("Your address"));
}
document.add(table);
document.close();

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.open();
doc.add(new Paragraph("Welcome to Page 1."));
Paragraph paraRight = new Para();
paraRight.setAlignment(ALIGN_RIGHT);
paraRight.add("The para is aligned to right side");
doc.add(paraRight);
doc.setPageSize(A4.rotate.Pagesize());
doc.setMargins(70, 70, 175, 175);
doc.newPage();
doc.add(new Paragraph("Portrait page having larger margins"));
doc.close();
}
}

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"));
document.open();
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 documents 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.");
Target.setName("BackToTop");
Para para1 = new Para();
para1.setSpacingBefore();
para1.add(Target);
document.add(para1);
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))));

Figure 1: Sample Output

Listing 5: Lesson object creation


Para Label1 = new Para("Lesson 1",
Font.getFont(Font.ARIAL,
14, Font.BOLD, new Color(0, 255, 255,17)));
Lesson lesson1 = new Lesson(title1, 1);
Lesson1.setNumberDepth(0);
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 lessons 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.");
section1.add(someSectionText);
someSectionText = new Para(" Here it lists the 3 X 2 table.");
section1.add(someSectionText);
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"));
section1.add(A);
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);
section1.add(img2);
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 documents
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)));
section1.add(label2);
label2.setSpacingBefore();
Paragraph para2 = new Paragraph("Back To Top");
Paragraph2.setReference("#BackToTop");
section1.add(para2);

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


document.add(lesson1);
document.close();

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 machines classpath on this command prompt. This is then
followed by including the jar file in the machines 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 elements 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.
Conclusion
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.

Read more:
http://mrbool.com/how-to-create-and-export-pdf-files-in-java/27343#ixzz3bLT9coo2

You might also like