Newsletter

Creating PDF with Java and iText, Generating PDF Using Java Example

Core Java » on Oct 13, 2012 { 38 Comments } By Sivateja

Its very important in real time to convert the records or any statements into PDF,EXCEL,Word,TXT and some other formats too 🙂 now i will tell you how to generate PDF using iTextPdf API (simple API to generate PDFs in java), am going to cover…

  • Inserting Image in PDF
  • Inserting Table in PDF
  • Inserting List in PDF
  • Text formatting in PDF
  • Adding new Pages in PDF
  • Little Chunk

But before you start this application you must download iTextpdf related jar(s).

PdfGen.java

package pdf;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class PdfGen {

    public static void main(String[] args) {

        try {

              OutputStream file = new FileOutputStream(new File("C:\\PDF_Java4s.pdf"));
	          Document document = new Document();
	          PdfWriter.getInstance(document, file);

			//Inserting Image in PDF
			     Image image = Image.getInstance ("src/pdf/java4s.png");
			     image.scaleAbsolute(120f, 60f);//image width,height	

			//Inserting Table in PDF
			     PdfPTable table=new PdfPTable(3);

	                     PdfPCell cell = new PdfPCell (new Paragraph ("Java4s.com"));

				      cell.setColspan (3);
				      cell.setHorizontalAlignment (Element.ALIGN_CENTER);
				      cell.setPadding (10.0f);
				      cell.setBackgroundColor (new BaseColor (140, 221, 8));					               

				      table.addCell(cell);						               

				      table.addCell("Name");
				      table.addCell("Address");
				      table.addCell("Country");
                      table.addCell("Java4s");
				      table.addCell("NC");
				      table.addCell("United States");
				      table.setSpacingBefore(30.0f);       // Space Before table starts, like margin-top in CSS
				      table.setSpacingAfter(30.0f);        // Space After table starts, like margin-Bottom in CSS								          

			 //Inserting List in PDF
				      List list=new List(true,30);
			          list.add(new ListItem("Java4s"));
				      list.add(new ListItem("Php4s"));
				      list.add(new ListItem("Some Thing..."));		

			 //Text formating in PDF
	                Chunk chunk=new Chunk("Welecome To Java4s Programming Blog...");
					chunk.setUnderline(+1f,-2f);//1st co-ordinate is for line width,2nd is space between
					Chunk chunk1=new Chunk("Php4s.com");
					chunk1.setUnderline(+4f,-8f);
					chunk1.setBackground(new BaseColor (17, 46, 193));      

			 //Now Insert Every Thing Into PDF Document
		         document.open();//PDF document opened........			       

					document.add(image);

					document.add(Chunk.NEWLINE);   //Something like in HTML :-)

                    document.add(new Paragraph("Dear Java4s.com"));
	                document.add(new Paragraph("Document Generated On - "+new Date().toString()));	

					document.add(table);

					document.add(chunk);
					document.add(chunk1);

					document.add(Chunk.NEWLINE);   //Something like in HTML :-)							    

       				document.newPage();            //Opened new page
					document.add(list);            //In the new page we are going to add list

		         document.close();

			             file.close();

            System.out.println("Pdf created successfully..");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Explanation

  • Point number 1, just forget every thing 🙂 its very simple program, i will show you the road map
  • First open OutputStream and give our output PDF file name [ line number 26 ]
  • Create Document class object [ line number 27 ]
  • Call getInstance() static method from PdfWriter class
  • In getInstance() we have 2 parameters, 1 is document object and 2nd one is our OutputStream object
  • Now jump to line number 70, we are calling open() method from Document object, means think PDF is opened now
  • Come to line number 30, here am going to write some code to insert an image into the PDF document
  • Create Image class object and loaded the image and adjusted the dimensions
  • Come to line number 72, add your image object here 🙂
  • line number 85 we have created new PDF page
  • Similarly allllllllllllllll

Download iText Jars

Click here to check output PDF

Output PDF

PDF Generated Related to Above code

​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

38 Responses to “Creating PDF with Java and iText, Generating PDF Using Java Example”
  1. raja says:

    Hi java4s,
    If possible please give me the core java inner class concept fully with example.
    Thanks u.

  2. Baba says:

    Hi,
    This is Baba… I got a small issue.. in my requriment i want to download a PDF, but with itext API or any other API am able to get a pdf file with static location.,ie.,”C://temp/mypdf.pdf”. But in my requriment i want to download a pdf with asking location also ie., “sava as and open with” option in a small popup. any code is there to fullfill this requriment. Please send mail babavaliahmadi@gmail.com

  3. venubabu.g says:

    hai

    i am venu please see this code to download pdf with popup

    response.setContentType(“application/pdf”);
    response.setHeader(“Content-Disposition”,
    ” attachment; filename=\”venu.pdf\””); paste this two lines in your code and then continue

  4. Hi
    I want to generate PDf file in JAPAN and Korean language . How can I achieve this using itext API .

  5. Pawan says:

    Hi,
    I am Pawan. After generate the PDF file auto print dialog is not coming.
    How to do for that?

    Please help me out with an example.

    Thanks in advance…

  6. suresh says:

    Hello boss this is suresh [ +91-8500123410 ], thanks for giving good code , it is very helpful for me……

  7. Aswini says:

    Thank you.
    It is working fine

  8. Preethi says:

    How to convert a pdf to excel using java?

  9. Tomy says:

    How to add multiple image to get 1 pdf file?

  10. ramesh says:

    how to create border for the pdf file and creating table inside that

  11. mayank says:

    hello sir can u give me a example of generating pdf in jsp in dynamic web project page and also a option for save that generating pdf in memory where ever we want, means before generation of pdf system will give you a option to save that pdf in memory

  12. Priyanka says:

    hi Sivateja,

    i am trying to create a pdf through iText in java.Could you please tell me how to reduce space between iText objects like paragraph and table. After paragraph, there is too much space wasted to start a new table on a page. I want to reduce that space. Thanks in advance.

  13. Zaser says:

    There is another java library for creating PDF file and offers many other options including converting pdf documents, It is known as Aspose.PDF for Java.

    @ramesh,

    You can do all that you have mentioned in your reply by using this API:

    http://www.aspose.com/java/pdf-component.aspx

  14. shoaib says:

    hello sir plz tell me how i save Dynamic data convert into pdf plzz its urgent i really neeed it

  15. HARSH says:

    Dear Sir, Please help me i m small application developer in java. i face one problem with itext pdf file. i want to add same image in all page as a header please send me code at if u know “toomuchharsh@gmail.com”
    Thanks in Advance…..

  16. GAURAV GUPTA says:

    How to convert PDF file to excel sheet in java……….

  17. Jaipal Reddy says:

    I want to fill acrobat fields dynamically and generate plat the pdf?
    Is there any way with iTextPdf?

  18. Kamal says:

    Hi Team,

    Iam in the process of converting the .doc file of microsoft word document to acrobat .pdf file.

    I just wanted to know how could we determine the order of data elements in word document so that we can write it to pdf in same order.

    I’m using POI 3.9 and iText 4.2. Please help.

    Thanks in Advance
    Kamal

  19. kav says:

    Thank you for sharing this tutorial.
    I wanted to create pdf images with java, and lucky to find your article on google, the code works correctly.
    Looking forward to learn more from you.
    Best regards.

  20. mathew says:

    I’M HAVING THE FOLLOWING ERRORS WHILE TRYING TO RUN U’R CODE PLS TELL ME WHY
    java.io.FileNotFoundException: D:\juli\pdf\PDF-Java4s.pdf (Access is denied)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.(FileOutputStream.java:212)
    at java.io.FileOutputStream.(FileOutputStream.java:165)
    at pdfgen.main(pdfgen.java:33)

  21. hari says:

    HI SivaTeja,

    I am trying to add an image to pdf as header..but i couldn’t. Can you please send me some sample code..so i can modify that. Thanks in advance.

  22. Santhosh K S says:

    Hi Java4s,
    Thank u for give such useful code.

  23. Balaji V says:

    java.io.FileNotFoundException: D:\raj\pdf\PDF-Java4s.pdf (Access is denied)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.(FileOutputStream.java:212)
    at java.io.FileOutputStream.(FileOutputStream.java:165)
    at pdfgen.main(pdfgen.java:33)

  24. Dhruvil says:

    Hi Team,
    How to create a new file and save all the data user writes in a jsp page provided to him in that file(file can be .txt or .doc or .pdf)?? Looking forward for some help.

  25. bajrang says:

    I want to write 50,000 record in pdf. can you suggest which library i want to use???

  26. Murugan says:

    this font will support for korea, vietnam english,cjk.
    pls try this font
    1. dowload Malgun-Gothic-Bold_29380.ttf font.
    2. store it in asset->fonts->Malgun-Gothic-Bold_29380.ttf font
    3. this code will work for cjk and English and vitenames
    4. if it not support for other language. please change the font(or download)

    Font fontbold=FontFactory.getFont(“assets/fonts/Malgun-Gothic-Bold_29380.ttf”, BaseFont.IDENTITY_H,BaseFont.EMBEDDED, 12);

  27. shankar says:

    Hi Bro., i copied this code and using into my problem but my problem is unable to open pdf file so please give me a solution.

  28. Datta says:

    How to generate PDF in Japanese?

  29. user says:

    How to give the path to store in mobile internal memory???Actually I want execute this code in Android

  30. sanoop singh says:

    Hi Bro.,
    when i haveinserting this itext.jar should be connected that should not be work give me quick reply
    Only a type can be imported. com.itextpdf.text.pdf.PdfWriter resolves to a package
    how to solve this one issue .

  31. ram says:

    how to convert uploaded any type of file to pdf

  32. ram says:

    How to convert selected file to pdf using jsp and servlets

  33. hacker says:

    good example

  34. sukanya says:

    Hi how to convert pdf data into json format in console. using core java concepts only

  35. Rasmi says:

    hi..
    i want to generate a pdf file which will contain both html table and a chart (may be HighChart) using java or javascript / both .

  36. uma says:

    Nice i have done this program successfully……………

  37. syamkumar says:

    Dear Sir,
    Please help me i am small application developer in java. i face one problem with itext pdf file. i want to add same image in all page as a header
    And Data also need to be appear on top of image
    please send me code at if u know “dskkumardsk3@gmail.com”

    Thanks in Advance…..

  38. Sindhu Reddy says:

    How to convert input text data file into PDF format, Please give an example.

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.