Create PDF files using iText library

Foreword

Translation link: http://howtodoinjava.com/apache-commons/create-pdf-files-in-java-itext-tutorial/

I believe everyone is familiar with reading and writing excel files. You can just use apache’s POI library. In this article, I will write various code examples based on the iText library to create PDF files. These examples will be classified according to their respective functions. In order to allow everyone to more vividly see the content of the PDF file generated by the code, I will attach a screenshot of the PDF file to each example. I’ve tried to put here as many useful examples as I could find, and if you feel like I’ve missed some use cases, feel free to leave your suggestions in the comments and I’ll add them in.

iText library overview

The good thing is that iText is an open source API, but it should be noted that although iText is open source, if you use it for commercial purposes, you still need to purchase a commercial license. You can get the iText Java class library for free from http://itextpdf.com. The iText library is very powerful and supports the production of HTML, RTF, XML and PDF files. You can use a variety of fonts in documents, and , you can also use the same code to generate the different types of files mentioned above. This is really a great feature, isn’t it?

The iText library contains a series of interfaces that can generate PDF files with different fonts, create tables in PDF, add watermarks and other functions. Of course, iText has many other functions, which will be left to the reader to explore.

If your project is a maven project, add the following dependencies in the pom.xml file to add iText library support to your application.

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

Of course, you can also download the latest jar file yourself, and then add it to the project at the download address.

Common classes in iText library

Let us first list a few important classes that will be used in the following examples to get familiar with them.

com.itextpdf.text.Document: This is the most commonly used class in the iText library, which represents a pdf instance. If you need to generate a PDF file from scratch, you need to use this Document class. First create (new) the instance, then open (open) it, add (add) content, and finally close (close) the instance to generate a pdf file.

com.itextpdf.text.Paragraph: Represents an indented text paragraph. In the paragraph, you can set the alignment, indentation, spacing before and after the paragraph, etc.

com.itextpdf.text.Chapter: Represents a chapter of PDF, which is created through a Paragraph type title and an integer chapter number.

com.itextpdf.text.Font: This class contains all standardized fonts, including family of font, size, style and color. All these fonts are declared as static constants.

com.itextpdf.text.List: represents a list;

com.itextpdf.text.pdf.PDFPTable: represents a table;

com.itextpdf.text.Anchor: Represents an anchor, similar to a link to an HTML page.

com.itextpdf.text.pdf.PdfWriter: When this PdfWriter is added to a PdfDocument, all content added to the Document will be written to the output stream associated with the file or network.

com.itextpdf.text.pdf.PdfReader: used to read PDF files;

iText Hello World example

Let’s start with a simple “Hello World” program. In this program, I will create a PDF file containing a simple statement.

package cn.edu.hdu.chenpi.cpdemo.itext;

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

Set file properties for PDF files

This example will show how to set various properties to a PDF file, such as author name, creation date, creator, or title.

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

Add pictures to PDF

The following example shows how to add images to PDF files. In the example, the image source includes two methods: local image or URL.

Also, I added some code to set the position of the image in the 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("C:\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();
        }

Create table in PDF

The following code shows how to create a table in a PDF file

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

Create a list in PDF

This example will help you understand how the iText library creates lists in PDF files.

\

\

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

View Code

Set styles/formatted output in PDF

Let’s look at some examples of styling the content of PDF files, including the use of fonts, chapters, and sections.

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

Set a password for PDF files

Next, let’s take a look at how to generate a password for PDF files. As follows, use the writer.setEncryption() method to set a password for PDF files.

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

Set permissions for PDF files

In this example, I will set some permissions to restrict other users from accessing PDF files. Here are some permission settings:

 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 implement multiple permission settings by performing OR operations on 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();
        }
    }

Read/modify existing PDF files

This example will show how to use the iText library to read and modify PDF files. In this example, I will read a PDF file and add some content to each page.

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

Write PDF content into the HTTP response output stream

This is the last example of this article. I will write some PDF content to the output stream of HttpServletResponse. In CS environment, this is very useful when you need to convert PDF files into stream form.

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

The above are all the examples about the iText library. If anything is unclear or you want to add more examples, please leave your comments.

Happy studying~

Translation link: http://howtodoinjava.com/apache-commons/create-pdf-files-in-java-itext-tutorial/