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
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(); } } }

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(); }

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(); }

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(); } }

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(); }

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(); }

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.
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(); } }

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(); } }

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.
Happy Learning !!
Ishita
@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.
Swarnendu
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
TRISHA MITRA
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.
MANIVANNAN
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.
agraj
Great tutorial. Very helpful.
Tapas Ranjan Sahu
How to download attachment from pdf with password(to open the pdf need to put password) protected
james
This is only for generating one pdf file.. But how to generate multiple pdf files ???
Sandeep Bhoite
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
Interesting. Anybody, any thoughts?
Suraj Kumar
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.
Shaheer Ahmad Khan
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?
Evan F
You’re a life saver. Thank you for posting these examples, they are much better than the website’s.
kareena
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
I am also having the same problem. Can you help me if you have got the solution to it.
neelima
I am also having the same problem. Can you help me if you have got the solution to it
Rahulchandel
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
ranga
hi..im ranga
i want creating multitable in pdf through mysql database…please send me any example link
Murali
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???
Jobish George
Hi,
I would like to export my xml layout(Where i have some reports) into pdf. How could I do that?
Ajmal sha
i need to read the title of a pdf file using java code..is it possible ..? if possible the how?
Kartik Agarwal
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
Lokesh Gupta
It’s version mismatch issue. Please find the matching jars version in downloaded code.
Kartik Agarwal
i have downloaded those files from your link only
vikash
use only BoucyCastle-lw jar
you can download it from
aditi jain
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
Hello Aditi
You can first save your Retrieve data from Database to some string than add that sting to Paragraph.
venkatesh
Hi aditi jain
Now i need conversions to pdf from jpg,doc,excel ,word .
if you have any code implementations please let me post.
Dhanraj Bhoite
Hi Lokesh,
I want to create pdf itext, but data to field which is from database. How i can do this?
Thanks
Dhanraj
Rajan Bhatt
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…..
Kartikaya
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.
Lokesh Gupta
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
what type of return type we should expect from this ex,ple
iasa
how to delete a paragraph/chapter or something else from pdf after adding it to the document ?
chairman
Hi, i used your code but pdf file not created and also no ERROR shown.
Please tell me how to view the pdf.
Akki
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
kalavathi
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.
gratus antin
Hi can you please tell me how could I add OUTLINE to my generated pdf?
Thanks in advance
Lokesh Gupta
Could you please try this example : https://kb.itextpdf.com/home/it5kb/examples/itext-in-action-chapter-7-making-documents-interactive#302-createoutlinetree.java
Vivek Jain
how can i add watermark while generating the PDF?
Lokesh Gupta
Have you tried it? https://stackoverflow.com/questions/25359024/how-to-create-watermark-in-pdf
G.S.Sivaram
Hai ..How can we add text at the end (append) of a pdf file..using itext 5.5.1 in java..
Rheza
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:
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
“Read/Modify an existing PDF” This section discuss exactly same thing.
Maran
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]
Prithvi
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
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.
Bramesh Gupta
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
Use this example : https://kb.itextpdf.com/home/it5kb/examples/itext-in-action-chapter-3-adding-content-at-absolute-positions#152-foobarfilmfestival.java
Bharat Shivram
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
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.
Aparna
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
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
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
Yes, version mismatch create issues. Just delete all .class files in bin folder and generate them again.
Gopi
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
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.
Adarsh S
Really Awesome !