HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Java Libraries / Read and generate pdf in Java- iText Tutorial

Read and generate pdf in Java- iText Tutorial

In this iText tutorial, I am writing various code examples read a pdf file and generate PDF file. iText library helps to generate pdf files from java applications dynamically.

These code examples are categorized into multiple sections based on the work they do OR functionality they achieve. With each java pdf example, I have attached a snapshot of PDF file so that you can visualize what exactly code is writing in PDF file. You may extend these examples to get text from database or some API response in json and write to pdf.

I have tried to put as many examples as I found useful to put here to help you all while you work on pdf files in Java. Through given examples use simple java programs, you can reuse this code in web applications.

Table of Contents

1. Overview of iText library
2. Commonly used iText classes
3. iText hello world example
4. Setting file attributes to PDF
5. Adding images to PDF
6. Creating tables in PDF
7. Creating lists in PDFs
8. Styling and formatting PDF output
9. Create password protected PDF files
10. Create PDF with limited permissions
11. Read and modify an existing PDF
12. Write PDF as Output Stream in HTTP response
Download Sourcecode of iText Examples

Let’s start the tutorial with an introduction to iText library.

1. Overview of iText library

On brighter side, iText is an open source API. Note that though iText is open source, you still need to purchase a commercial license if you want to use it for commercial purposes. iText is a freely available Java library from http://itextpdf.com. The iText library is powerful and supports the generation of HTML, RTF, and XML documents, in addition to generating PDFs. You can choose from a variety of fonts to be used in the document. Also, the structure of iText allows you to generate any of the above-mentioned types of documents with the same code. Isn’t it great feature, right?

The iText library contains classes to generate PDF text in various fonts, generate tables in PDF document, add watermarks to pages, and so on. There are many more features available with iText which I will leave on you to explore.

To add iText into your application, include following maven repository into your pom.xml file.

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13</version>
</dependency>

Or you can download the latest jar files from maven repository.

2. Commonly used iText classes

Let’s list down and get familiar with important classes which we are going to use in this application.

  • com.itextpdf.text.Document : This is the most important class in iText library and represent PDF document instance. If you need to generate a PDF document from scratch, you will use the Document class. First you must create a Document instance. Then you must open it. After that you add content to the document. Finally you close the Document instance.
  • com.itextpdf.text.Paragraph : This class represents a indented “paragraph” of text. In a paragraph you can set the paragraph alignment, indentation and spacing before and after the paragraph.
  • com.itextpdf.text.Chapter : This class represents a chapter in the PDF document. It is created using a Paragraph as title and an int as chapter number.
  • com.itextpdf.text.Font : This class contains all specifications of a font, such as family of font, size, style, and color. Various fonts are declared as static constants in this class.
  • com.itextpdf.text.List : This class represents a list, which, in turn, contains a number of ListItems.
  • com.itextpdf.text.pdf.PDFPTable : This is a table that can be put at an absolute position but can also be added to the document as the class Table.
  • com.itextpdf.text.Anchor : An Anchor can be a reference or a destination of a reference. A link like we have in HTML pages.
  • com.itextpdf.text.pdf.PdfWriter : When this PdfWriter is added to a certain PdfDocument, the PDF representation of every Element added to this Document will be written to the outputstream attached to writer (file or network).
  • com.itextpdf.text.pdf.PdfReader : Used to read a PDF document. Simple and clear.

2. iText hello world example

Let’s start writing our example codes with customary Hello World application. In this application, I will create a PDF file with a single statement in content.

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class JavaPdfHelloWorld
{
   public static void main(String[] args)
   {
      Document document = new Document();
      try
      {
         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));
         document.open();
         document.add(new Paragraph("A Hello World PDF document."));
         document.close();
         writer.close();
      } catch (DocumentException e)
      {
         e.printStackTrace();
      } catch (FileNotFoundException e)
      {
         e.printStackTrace();
      }
   }
}
Hello World Program Output as Pdf
Hello World Program Output as Pdf

4. Set file attributes to PDF file

This example shows how to set various attributes like author name, created date, creator name or simply title of the pdf file.

Document document = new Document();
try
{
	PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("SetAttributeExample.pdf"));
	document.open();
	document.add(new Paragraph("Some content here"));

	//Set attributes here
	document.addAuthor("Lokesh Gupta");
	document.addCreationDate();
	document.addCreator("HowToDoInJava.com");
	document.addTitle("Set Attribute Example");
	document.addSubject("An example to show how attributes can be added to pdf files.");

	document.close();
	writer.close();
} catch (Exception e)
{
	e.printStackTrace();
}
SetAttributeExample Pdf Output
SetAttributeExample Pdf Output

5. Add images to PDF file

An example to show how images can be added to PDF files. Example contain adding images from file system as well as URLs. Also, I have added code to position the images within document.

Document document = new Document();
try
{
	PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("AddImageExample.pdf"));
	document.open();
	document.add(new Paragraph("Image Example"));

	//Add Image
	Image image1 = Image.getInstance("temp.jpg");
	//Fixed Positioning
	image1.setAbsolutePosition(100f, 550f);
	//Scale to new height and new width of image
	image1.scaleAbsolute(200, 200);
	//Add to document
	document.add(image1);

	String imageUrl = "http://www.eclipse.org/xtend/images/java8_logo.png";
	Image image2 = Image.getInstance(new URL(imageUrl));
	document.add(image2);

	document.close();
	writer.close();
} catch (Exception e)
{
	e.printStackTrace();
}
AddImageExample Pdf Output
AddImageExample Pdf Output

6. Generate tables in PDFs

Below example shows how to add tables in a pdf document.

public static void main(String[] args)
{
	Document document = new Document();
	try
	{
		PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("AddTableExample.pdf"));
		document.open();

		PdfPTable table = new PdfPTable(3); // 3 columns.
		table.setWidthPercentage(100); //Width 100%
		table.setSpacingBefore(10f); //Space before table
		table.setSpacingAfter(10f); //Space after table

		//Set Column widths
		float[] columnWidths = {1f, 1f, 1f};
		table.setWidths(columnWidths);

		PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1"));
		cell1.setBorderColor(BaseColor.BLUE);
		cell1.setPaddingLeft(10);
		cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
		cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);

		PdfPCell cell2 = new PdfPCell(new Paragraph("Cell 2"));
		cell2.setBorderColor(BaseColor.GREEN);
		cell2.setPaddingLeft(10);
		cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
		cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);

		PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 3"));
		cell3.setBorderColor(BaseColor.RED);
		cell3.setPaddingLeft(10);
		cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
		cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);

		//To avoid having the cell border and the content overlap, if you are having thick cell borders
		//cell1.setUserBorderPadding(true);
		//cell2.setUserBorderPadding(true);
		//cell3.setUserBorderPadding(true);

		table.addCell(cell1);
		table.addCell(cell2);
		table.addCell(cell3);

		document.add(table);

		document.close();
		writer.close();
	} catch (Exception e)
	{
		e.printStackTrace();
	}
}
AddTableExample Pdf Output
AddTableExample Pdf Output

7. Create list items in PDF file

Below example will help you in understanding that how to write lists in pdf files using iText library.

Document document = new Document();
try
{
	PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("ListExample.pdf"));
	document.open();
	document.add(new Paragraph("List Example")); 

	//Add ordered list
	List orderedList = new List(List.ORDERED);
	orderedList.add(new ListItem("Item 1"));
	orderedList.add(new ListItem("Item 2"));
	orderedList.add(new ListItem("Item 3"));
	document.add(orderedList);

	//Add un-ordered list
	List unorderedList = new List(List.UNORDERED);
	unorderedList.add(new ListItem("Item 1"));
	unorderedList.add(new ListItem("Item 2"));
	unorderedList.add(new ListItem("Item 3"));
	document.add(unorderedList);

	//Add roman list
	RomanList romanList = new RomanList();
	romanList.add(new ListItem("Item 1"));
	romanList.add(new ListItem("Item 2"));
	romanList.add(new ListItem("Item 3"));
	document.add(romanList);

	//Add Greek list
	GreekList greekList = new GreekList();
	greekList.add(new ListItem("Item 1"));
	greekList.add(new ListItem("Item 2"));
	greekList.add(new ListItem("Item 3"));
	document.add(greekList);

	//ZapfDingbatsList List Example
	ZapfDingbatsList zapfDingbatsList = new ZapfDingbatsList(43, 30);
	zapfDingbatsList.add(new ListItem("Item 1"));
	zapfDingbatsList.add(new ListItem("Item 2"));
	zapfDingbatsList.add(new ListItem("Item 3"));
	document.add(zapfDingbatsList);

	//List and Sublist Examples
	List nestedList = new List(List.UNORDERED);
	nestedList.add(new ListItem("Item 1"));

	List sublist = new List(true, false, 30);
	sublist.setListSymbol(new Chunk("", FontFactory.getFont(FontFactory.HELVETICA, 6)));
	sublist.add("A");
	sublist.add("B");
	nestedList.add(sublist);

	nestedList.add(new ListItem("Item 2"));

	sublist = new List(true, false, 30);
	sublist.setListSymbol(new Chunk("", FontFactory.getFont(FontFactory.HELVETICA, 6)));
	sublist.add("C");
	sublist.add("D");
	nestedList.add(sublist);

	document.add(nestedList);

	document.close();
	writer.close();
} catch (Exception e)
{
	e.printStackTrace();
}
ListExample Pdf example
ListExample Pdf example

8. Generate PDF and style / format PDF file content

Let’s see some examples of styling the content of PDF file. Example contains the usage of Fonts as well as chapter and sections as well.

Font blueFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL, new CMYKColor(255, 0, 0, 0));
Font redFont = FontFactory.getFont(FontFactory.COURIER, 12, Font.BOLD, new CMYKColor(0, 255, 0, 0));
Font yellowFont = FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new CMYKColor(0, 0, 255, 0));
Document document = new Document();
try
{
	PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("StylingExample.pdf"));
	document.open();
	//document.add(new Paragraph("Styling Example"));

	//Paragraph with color and font styles
	Paragraph paragraphOne = new Paragraph("Some colored paragraph text", redFont);
	document.add(paragraphOne);

	//Create chapter and sections
	Paragraph chapterTitle = new Paragraph("Chapter Title", yellowFont);
	Chapter chapter1 = new Chapter(chapterTitle, 1);
	chapter1.setNumberDepth(0);

	Paragraph sectionTitle = new Paragraph("Section Title", redFont);
	Section section1 = chapter1.addSection(sectionTitle);

	Paragraph sectionContent = new Paragraph("Section Text content", blueFont);
	section1.add(sectionContent);

	document.add(chapter1);

	document.close();
	writer.close();
} catch (Exception e)
{
	e.printStackTrace();
}
StylingExample Pdf Example
StylingExample Pdf Example

9. Generate password protected PDF file

Let’s see an example of creating password protected pdf file. Here writer.setEncryption() is used to set password to generated PDF.

We need to add bouncy castle jars generating for password protected PDFs. I have added these jars in sourcecode of examples for this post.
private static String USER_PASSWORD = "password";
private static String OWNER_PASSWORD = "lokesh";

public static void main(String[] args) {
	try 
	{
		OutputStream file = new FileOutputStream(new File("PasswordProtected.pdf"));
		Document document = new Document();
		PdfWriter writer = PdfWriter.getInstance(document, file);

		writer.setEncryption(USER_PASSWORD.getBytes(),
				OWNER_PASSWORD.getBytes(), PdfWriter.ALLOW_PRINTING,
				PdfWriter.ENCRYPTION_AES_128);

		document.open();
		document.add(new Paragraph("Password Protected pdf example !!"));
		document.close();
		file.close();

	} catch (Exception e) 
	{
		e.printStackTrace();
	}
}
PasswordProtected Pdf file
PasswordProtected Pdf file

10. Create PDF with limited permissions

In this example, I am setting few file permissions for a pdf file to limit access for other users. Following are several permission values:

 PdfWriter.ALLOW_PRINTING
 PdfWriter.ALLOW_ASSEMBLY
 PdfWriter.ALLOW_COPY
 PdfWriter.ALLOW_DEGRADED_PRINTING
 PdfWriter.ALLOW_FILL_IN
 PdfWriter.ALLOW_MODIFY_ANNOTATIONS
 PdfWriter.ALLOW_MODIFY_CONTENTS
 PdfWriter.ALLOW_SCREENREADERS

You can provide multiple permissions by ORing different values. For example PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_COPY.

public static void main(String[] args) {
	try {
		OutputStream file = new FileOutputStream(new File(
				"LimitedAccess.pdf"));
		Document document = new Document();
		PdfWriter writer = PdfWriter.getInstance(document, file);

		writer.setEncryption("".getBytes(), "".getBytes(),
				PdfWriter.ALLOW_PRINTING , //Only printing allowed; Try to copy text !!
				PdfWriter.ENCRYPTION_AES_128);

		document.open();
		document.add(new Paragraph("Limited Access File !!"));
		document.close();
		file.close();

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

11. Read and modify an existing PDF file

To complete this tutorial, let’s see an example of reading and modifying a PDF file using PDFReader class provided by iText library itself. In this example, I will read content from PDF file and add some random content to it’s all pages.

public static void main(String[] args) {
  try
  {
	//Read file using PdfReader
	PdfReader pdfReader = new PdfReader("HelloWorld.pdf");

	//Modify file using PdfReader
	PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream("HelloWorld-modified.pdf"));

	Image image = Image.getInstance("temp.jpg");
	image.scaleAbsolute(100, 50);
	image.setAbsolutePosition(100f, 700f);

	for(int i=1; i<= pdfReader.getNumberOfPages(); i++)
	{
		PdfContentByte content = pdfStamper.getUnderContent(i);
		content.addImage(image);
	}

	pdfStamper.close();

  } catch (IOException e) {
	e.printStackTrace();
  } catch (DocumentException e) {
	e.printStackTrace();
  }
}
Modified Pdf Example
Modified Pdf Example

12. Write PDF as Output Stream in HTTP response

This is the last example in list and in this example, I am writing the content of created PDF file into output stream attached to HttpServletResponse object. This will be needed when you want to stream the PDF file in a client-server environment.

Document document = new Document();
try{
	response.setContentType("application/pdf");
	PdfWriter.getInstance(document, response.getOutputStream());
	document.open();
	document.add(new Paragraph("howtodoinjava.com"));
	document.add(new Paragraph(new Date().toString()));
	//Add more content here
}catch(Exception e){
	e.printStackTrace();
}
	document.close();
}

That’s all for this big list of iText example codes. Leave a comment if something is not clear to you OR you would like to add any other example into this list.

Download Sourcecode of iText Examples

Happy Learning !!

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Ishita

    July 1, 2020

    @RequestMapping(value=”/download”)
    public String download(HttpServletResponse res)throws IOException
    {
    String mimeType=null;
    File f=new File(“D:/files/merge/res.pdf”);
    mimeType=getMimeType(f.getCanonicalPath());
    res.setContentType(mimeType);
    res.setHeader(“Content-Disposition”,”attachment;filename=\””+f.getName()+”\””);
    res.setContentLength((int)f.length());
    InputStream is=new FileInputStream(f);
    ServletOutputStream out=res.getOutputStream();
    IOUtils.copy(is, out);
    is.close();
    out.flush();
    out.close();
    return “index”;
    }

    private String getMimeType(String canonicalPath)
    {
    canonicalPath=canonicalPath.toLowerCase();
    if(canonicalPath.endsWith(“.jpg”)||canonicalPath.endsWith(“.jpeg”))
    return “image/jpeg”;
    else
    return “application/pdf”;

    }

    This code is for those who are facing problem in downloading there pdf file you can use mime type , ihad used here only jpg and pdf. Hope this will be helpful for you all.

  2. Swarnendu

    June 24, 2020

    My scenario is this I am using pdf file to log my execution history [ text] with screenshot
    But the problem is that I am not able to append content after my existing current content and without creating multiple files I want to append all content in one pdf file.

    How to do that, because I am getting “Invalid header error ”

    can you please share code snippet for that

  3. TRISHA MITRA

    June 18, 2020

    How can I make a view of database table as a receipt? Working on Java with Eclipse IDE. I want the view page will fetch data from the db table when I will click to generate the payment receipt.

  4. MANIVANNAN

    February 28, 2020

    Is there anyway to have a agree alert with message in this. Eg. Having Two elements, we need to show the hidden content only when user agree some terms and conditions.

  5. agraj

    January 12, 2020

    Great tutorial. Very helpful.

  6. Tapas Ranjan Sahu

    October 17, 2019

    How to download attachment from pdf with password(to open the pdf need to put password) protected

  7. james

    September 22, 2019

    Document document = new Document();
    try{
        response.setContentType("application/pdf");
        PdfWriter.getInstance(document, response.getOutputStream());
        document.open();
        document.add(new Paragraph("howtodoinjava.com"));
        document.add(new Paragraph(new Date().toString()));
        //Add more content here
    }catch(Exception e){
        e.printStackTrace();
    }
        document.close();
    }
    

    This is only for generating one pdf file.. But how to generate multiple pdf files ???

  8. Sandeep Bhoite

    July 22, 2019

    Hi Lokesh and other Commentors,
    I wonder If anyone has tried embedding Video inside PDF, This is one of my business requirement and I am not getting to a proper conclusion.

    Thanks for your answer, If any one has tried it please let me how we can achieve that.

    • Lokesh Gupta

      July 22, 2019

      Interesting. Anybody, any thoughts?

  9. Suraj Kumar

    March 25, 2019

    Here you have showed some examples by manually entering values that we want to print. What if we want certain fields of my HTML page to convert in a PDF dynamically? There is no where mentioned about it here. So, can you tell how to do or where can I look more for it.

  10. Shaheer Ahmad Khan

    March 12, 2019

    This has truly saved a lot of work,
    Thank you so much.

    Can you please let me know how do I add rows to the table?

  11. Evan F

    February 13, 2019

    You’re a life saver. Thank you for posting these examples, they are much better than the website’s.

  12. kareena

    October 31, 2018

    Hi,
    I want to download pdf file for web application i.e on button click in page , it should download the content which has been passed.
    Can you share js and java code for the same.

    • Suraj Kumar

      March 25, 2019

      I am also having the same problem. Can you help me if you have got the solution to it.

      • neelima

        May 23, 2019

        I am also having the same problem. Can you help me if you have got the solution to it

  13. Rahulchandel

    March 26, 2018

    Hi lokesh,

    Can you please tell me how to extract table data from pdf and that data come in csv format or tabular format.

    Thanks,
    Rahul

  14. ranga

    December 18, 2017

    hi..im ranga
    i want creating multitable in pdf through mysql database…please send me any example link

  15. Murali

    November 29, 2017

    hai guys ..im able to generate the pdf files but when i click on the save button its downloading automatically …how can i stop that…when i click on save button it should ask save as option…how to do that???

  16. Jobish George

    March 10, 2017

    Hi,

    I would like to export my xml layout(Where i have some reports) into pdf. How could I do that?

  17. Ajmal sha

    January 20, 2017

    i need to read the title of a pdf file using java code..is it possible ..? if possible the how?

  18. Kartik Agarwal

    November 3, 2016

    I am trying to make Encrupted pdf i have followed all step and also included those 3 extra jar file of bouncycastle but i am getting following exception.
    Without setEncryption(); my code is generating pdf files are succesfully.
    Please Help I am in Urgent Need

    Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: org/bouncycastle/asn1/ASN1OctetString
    	at com.itextpdf.text.pdf.PdfEncryption.<init>(PdfEncryption.java:148)
    	at com.itextpdf.text.pdf.PdfWriter.setEncryption(PdfWriter.java:2060)
    	at NIIT.Admin.s_info.SaveResultActionPerformed(s_info.java:290)
    	at NIIT.Admin.s_info.access$500(s_info.java:34)
    	at NIIT.Admin.s_info$6.actionPerformed(s_info.java:108)
    	at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    	at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    	at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    	at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    	at java.awt.Component.processMouseEvent(Component.java:6535)
    	at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    	at java.awt.Component.processEvent(Component.java:6300)
    	at java.awt.Container.processEvent(Container.java:2236)
    	at java.awt.Component.dispatchEventImpl(Component.java:4891)
    	at java.awt.Container.dispatchEventImpl(Container.java:2294)
    	at java.awt.Component.dispatchEvent(Component.java:4713)
    	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    
    • Lokesh Gupta

      November 3, 2016

      It’s version mismatch issue. Please find the matching jars version in downloaded code.

      • Kartik Agarwal

        November 4, 2016

        i have downloaded those files from your link only

    • vikash

      February 20, 2017

      use only BoucyCastle-lw jar
      you can download it from

  19. aditi jain

    September 26, 2016

    hii,
    i used every thing to generate PDF ,but nothing worked..
    Your code helped me a lot but it is for static data, i am getting data from query so how to save it in pdf same as it is coming and i want pop up which usually comes when we clicked to button that is for open and Save..
    please help me with this…

    Aditi

    • Kartik Agarwal

      November 3, 2016

      Hello Aditi
      You can first save your Retrieve data from Database to some string than add that sting to Paragraph.

    • venkatesh

      March 10, 2020

      Hi aditi jain

      Now i need conversions to pdf from jpg,doc,excel ,word .
      if you have any code implementations please let me post.

  20. Dhanraj Bhoite

    August 4, 2016

    Hi Lokesh,

    I want to create pdf itext, but data to field which is from database. How i can do this?
    Thanks
    Dhanraj

  21. Rajan Bhatt

    May 31, 2016

    Hi,

    can we include these features in the itext ?

    1. pagination
    2. logo add on every page means to set header and footer in the each page
    3. can dynamically add the data and in particular column we have 4 different values like status: done, partially done, not done, to be done and for that we can assign color text like for done its green for partially done its yellow…so on

    if anyone knows please tell me…..

  22. Kartikaya

    May 23, 2016

    Hi Lokesh,

    Thanks for the post its really very helpful, I have one question that in my code I want to show the PDF when I click on the PDF Generate button and also want a download option for PDF but what is happening when I click on Register button the PDF is downloaded at the desired path.In my code I’m trying to get data from my database so How can I resolve the issue. I think u r the right person who can resolve my issue.
    I’ll share you my code.

     
    
    FileOutputStream file = null;
    //FileOutputStream image;
    try {
    	file = new FileOutputStream(new File("D:\\report\\Registration.pdf"));
    	
    	
    } catch (FileNotFoundException e1) {
    	
    	e1.printStackTrace();
    }
    
    
    Document document = new Document();
    PdfWriter.getInstance(document, file);
    
    document.open();
    Image img = Image.getInstance("MT.png");
    img.setAbsolutePosition(455f, 755f);
    //Scale to new height and new width of image
    img.scaleAbsolute(90, 90);
    
    
    document.add(img);
    
    Paragraph p = new Paragraph();
    try {
    p.add("\n");
    p.add(" Registration Form");
    p.add("\n =============================================================");
    
    p.add("\n Registration Number:      " + reg.getRegistration_Number());
    p.add("\n UHID:                              "+ reg.getUHID());
    p.add("\n Legacy UHID:                 " + reg.getLegacy_UHID());
    p.add("\n First Name :                    " + reg.getFirst_Name());
    p.add("\n Middle Name :                 " + reg.getMiddle_Name());
    p.add("\n Last Name :                    " + reg.getLast_Name());
    p.add("\n DOB:                               " + reg.getDOB());
    p.add("\n Gender:                          " + reg.getGender());
    p.add("\n Blood Group:                  "+reg.getBlood_group());
    p.add("\n Address Line1:               " + reg.getAddress1());
    p.add("\n Address Line2: 			" + reg.getAddress2());
    p.add("\n Country: 					" + reg.getCountry());
    p.add("\n State: 					" + reg.getState());
    p.add("\n City: 					" + reg.getCity());
    p.add("\n Pincode:					                         " + reg.getPIN());
    p.add("\n Location Code:		        	      " + reg.getLocation());
    p.add("\n Language: 				                    " + reg.getLanguage());
    p.add("\n Proficiency: 				                   " + reg.getProficiency());
    p.add("\n Contact No: 				                  " + reg.getContact_No());
    p.add("\n Attendant Address: 		       " + reg.getAttendant_address());
    p.add("\n Attendant Contact: 	       " + reg.getAttendant_contactno());
    p.add("\n Doctor: 					                         " + reg.getDoc_Name());
    p.add("\n Speciality: 				                    " + reg.getSpecialty());
    p.add("\n =============================================================");
    
    
    document.add(p);
    document.close();
    
    }
    
    catch (Exception e) {
    	e.printStackTrace();
    }	
    
    • Lokesh Gupta

      May 23, 2016

      There are two things. One – file should be generated and stored on some path – so that it can be downloaded later by clicking on generate PDF button. You approach is correct. Two – when PDF Generate button is clicked then file should be downloaded. Here you should create another servlet/MVC method as per your application design and write the PDF file into ServletOutputStream. An Example.

    • ashok

      April 6, 2020

      what type of return type we should expect from this ex,ple

  23. iasa

    May 13, 2016

    how to delete a paragraph/chapter or something else from pdf after adding it to the document ?

  24. chairman

    March 31, 2016

    Hi, i used your code but pdf file not created and also no ERROR shown.
    Please tell me how to view the pdf.

  25. Akki

    March 7, 2016

    Hi Lokesh
    Can you help me to convert one file format (eg:- .docx, .txt ) etc into pdf form.And to save at a particular location….
    Please help
    Thank you

  26. kalavathi

    February 9, 2016

    Hi Lokesh ,

    have a requirement from client . requirement is some thing like bit tricky .

    for example am going to create one PDF in local path , second time on wards when i open the same PDF,it will show duplicate .am trying to work on this but when open the first time only am getting second opening as duplicate ,after closing nothing is displayed .please suggest me .

    Thanks in advance.

    kalavathi.

  27. gratus antin

    February 4, 2016

    Hi can you please tell me how could I add OUTLINE to my generated pdf?

    Thanks in advance

    • Lokesh Gupta

      February 4, 2016

      Could you please try this example : https://kb.itextpdf.com/home/it5kb/examples/itext-in-action-chapter-7-making-documents-interactive#302-createoutlinetree.java

  28. Vivek Jain

    February 3, 2016

    how can i add watermark while generating the PDF?

    • Lokesh Gupta

      February 3, 2016

      Have you tried it? https://stackoverflow.com/questions/25359024/how-to-create-watermark-in-pdf

  29. G.S.Sivaram

    February 2, 2016

    Hai ..How can we add text at the end (append) of a pdf file..using itext 5.5.1 in java..

  30. Rheza

    December 31, 2015

    Hi Lokesh.
    I do as You told in this Article, And it worked.
    But when I generate another new file, the previous pdf file getting replaced/overwrited.
    Here’s my code:

     PdfWriter.getInstance(document, new FileOutputStream("D:/filefolder/LetterTest.pdf")); 

    My question is, do you know the code to generate pdf file without overwriting the existing data (the previous data) within that file ?
    ~Thanks in advance

    • Lokesh Gupta

      January 1, 2016

      “Read/Modify an existing PDF” This section discuss exactly same thing.

  31. Maran

    October 17, 2015

    How to generate PDF with image as watermark for web application in jsp, response.getOutputstream. creation of image watermark PDF when the user click the button, dynamic creation of pdf. [jsp] [pdf] [watermark] [image]

  32. Prithvi

    August 7, 2015

    Hello,
    I am creating a simple project where I am using itext to fill out an existing form but unfortunately I get this error operation cannot be completed since user mapped is not closed.

    import java.io.FileOutputStream;
    import java.io.IOException;

    import com.itextpdf.text.DocumentException;
    import com.itextpdf.text.pdf.AcroFields;
    import com.itextpdf.text.pdf.PdfReader;
    import com.itextpdf.text.pdf.PdfStamper;

    public class ReformPdf
    {
    private static final String dest = “D:/Eclipse Java/HiltonForms2014_r.pdf”;
    private static final String src= “D:/Eclipse Java/HiltonForms2014_r.pdf”;
    public static void main(String[] args) throws IOException, DocumentException
    {
    PdfReader reader = new PdfReader(src);
    PdfStamper stamper = new PdfStamper(reader,new FileOutputStream(dest));
    AcroFields form = stamper.getAcroFields();
    form.setField(“LASTNAME”, “GOWDA”);
    form.regenerateField(“LASTNAME”);
    stamper.close();
    reader.close();

    }

    }

    thanks in advance

    • Lokesh Gupta

      August 8, 2015

      Delete the file from file system and run the program again. Error says that outputstream writing to file has not been closed.
      So first create an instance of FileOutputStream(dest), hold its reference, and close it too in last. I may work.

  33. Bramesh Gupta

    January 26, 2015

    Hi Lokesh,

    Thank you so much for this helping article.

    Request you to please advise me to set the position of a paragraph. I am not having much experience in Java, please advise.

    -Bramesh

    • Lokesh Gupta

      January 27, 2015

      Use this example : https://kb.itextpdf.com/home/it5kb/examples/itext-in-action-chapter-3-adding-content-at-absolute-positions#152-foobarfilmfestival.java

  34. Bharat Shivram

    August 19, 2014

    Hi Lokesh, Thanks for the article. Can you please compare this approach of generating a PDF with the method of using Jasper Report. I have worked in Jasper Reports and they feel much more easier than the approach that is being used here.

    • Lokesh Gupta

      August 19, 2014

      Hi Bharat, Thanks for putting your question here.
      I also had some (little) experience of working on jasper reports and we were using that for generating reports using iReport. So, based on my previous experience, I can say that for creating report PDFs, Jasper reports is better than iText. But if you are planning to write some sort of document containing random information then iText is better. This comparison is totally based on my little experience with both approaches to generate PDF files.
      Please feel free to put your own thoughts if you disagree.

  35. Aparna

    July 30, 2014

    Hi Lokesh,

    I read that we need bouncy castle jars are required for password protected pdf. Can you please include that in the examples.

    • Lokesh Gupta

      July 30, 2014

      I had added these jars in sourcecode available to download already. As you suggested, I have added a note as well in that section of the post. Thanks for suggestion. I appreciate it.

      • Gopi

        August 28, 2014

        I have imported the project and tried to run the encrypt PDF program. However it was showing the below error

        java.lang.UnsupportedClassVersionError: com/howtodoinjava/examples/PasswordProtectedPdfExample : Unsupported major.minor version 51.0
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
        at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
        Exception in thread “main”

        I added JRE System Library [jdk1.6.0_32] but I see you have added jdk1.7 in your project.

        Please help me to resolve this issue. Does the JDK version mismatch makes issue?

        Thanks for your help

        Gopi

        • Lokesh Gupta

          August 28, 2014

          Yes, version mismatch create issues. Just delete all .class files in bin folder and generate them again.

          • Gopi

            August 29, 2014

            Hi Lokesh, thanks for the quick help, Actually I could able to trace the root cause of the issue to some extent.

            For encrypting the PDF generated I added the two JAR files (bcpkix-jdk15on-1.47.jar & bcprov-jdk15on-1.47), and we also need bouncycastle-java5-136-1.0.0.jar for some other purpose of the project . However, when the classes of bouncycastle-java5-136-1.0.0.jar is loaded before the classes of bcprov-jdk15on-1.47.jar, then the below security exception is thrown. If the class loading order is the other way, then the exception is not thrown.

            Exception : java.lang.SecurityException: no manifiest section for signature file entry org/bouncycastle/asn1/ocsp/ResponderID.class
            Exception in thread “main” java.lang.SecurityException: no manifiest section for signature file entry org/bouncycastle/asn1/ocsp/ResponderID.class
            at sun.security.util.SignatureFileVerifier.verifySection(SignatureFileVerifier.java:380)
            at sun.security.util.SignatureFileVerifier.processImpl(SignatureFileVerifier.java:231)
            at sun.security.util.SignatureFileVerifier.process(SignatureFileVerifier.java:176)
            at java.util.jar.JarVerifier.processEntry(JarVerifier.java:245)
            at java.util.jar.JarVerifier.update(JarVerifier.java:199)
            at java.util.jar.JarFile.initializeVerifier(JarFile.java:323)
            at java.util.jar.JarFile.getInputStream(JarFile.java:388)
            at sun.misc.URLClassPath$JarLoader$2.getInputStream(URLClassPath.java:692)
            at sun.misc.Resource.cachedInputStream(Resource.java:61)
            at sun.misc.Resource.getByteBuffer(Resource.java:144)
            at java.net.URLClassLoader.defineClass(URLClassLoader.java:256)
            at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
            at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
            at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
            at com.itextpdf.text.pdf.PdfEncryption.(PdfEncryption.java:147)
            at com.itextpdf.text.pdf.PdfWriter.setEncryption(PdfWriter.java:2045)
            at com.dbs.ecorner.util.PDFGenerator.generateOpenAccountPDF(PDFGenerator.java:31)
            at com.dbs.ecorner.util.PDFGenerator.main(PDFGenerator.java:317)

            Could you please throw some light on this?

            Thanks!

            • Lokesh Gupta

              August 29, 2014

              Below are the manifest files for both jars.

              I do not see any class file inside bouncycastle-java5-136.jar, rather it has pom.xml file which include “bcprov-jdk15” dependency. Can’t we remove bouncycastle-java5-136.jar all together.

              Please consider above analysis just a probability. You need to do more research.

  36. Adarsh S

    July 30, 2014

    Really Awesome !

Comments are closed on this article!

Search Tutorials

Open Source Libraries

  • Apache POI Tutorial
  • Apache HttpClient Tutorial
  • iText Tutorial
  • Super CSV Tutorial
  • OpenCSV Tutorial
  • Google Gson Tutorial
  • JMeter Tutorial
  • Docker Tutorial
  • JSON.simple Tutorial
  • RxJava Tutorial
  • Jsoup Parser Tutorial
  • PowerMock Tutorial

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)