Pages

Tuesday, April 24, 2012

iText: Create a PDF in Java

from: http://www.rgagnon.com/javadetails/java-0618.html

iText

http://www.lowagie.com/iText/ iText is a very simple to use package to create and manipulate PDF file.
For the simple need, only 1 jar is required (ex. itext-2.1.3.jar, download at http://www.lowagie.com/iText/download.html)
In this example, you pass on the command line a filename (plain text file - args[0]) to convert to a PDF file (args[1]).
import java.io.*;

import com.lowagie.text.*;
import com.lowagie.text.pdf.*;

public class TextFileToPDF {

  /*
     ex. java TextFileToPDF  c:\temp\text.txt  c:\temp\text.pdf
  */
  public static void main (String [] args){
    BufferedReader input = null;
    Document output = null;
    System.out.println("Convert text file to pdf");
    System.out.println("input  : " + args[0]);
    System.out.println("output : " + args[1]);
    try {
      // text file to convert to pdf as args[0]
      input = 
        new BufferedReader (new FileReader(args[0]));
      // letter 8.5x11
      //    see com.lowagie.text.PageSize for a complete list of page-size constants.
      output = new Document(PageSize.LETTER, 40, 40, 40, 40);
      // pdf file as args[1]
      PdfWriter.getInstance(output, new FileOutputStream (args[1]));

      output.open();
      output.addAuthor("RealHowTo");
      output.addSubject(args[0]);
      output.addTitle(args[0]);

      String line = "";
      while(null != (line = input.readLine())) {
        System.out.println(line);
        Paragraph p = new Paragraph(line);
        p.setAlignment(Element.ALIGN_JUSTIFIED);
        output.add(p);
      }
      System.out.println("Done.");
      output.close();
      input.close();
      System.exit(0);
    }
    catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
}

Add a watermark to an existing document.
import java.io.FileOutputStream;
import java.util.HashMap;

import com.lowagie.text.Element;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;

public class AddWatermarkPageNumbers {
    public static void main(String[] args) {
        System.out.println("Add watermarks and pagenumbers");
        try {
            PdfReader reader = new PdfReader("ChapterSection.pdf");
            int n = reader.getNumberOfPages();
            // create a stamper that will copy the document to a new file
            PdfStamper stamp = new PdfStamper(reader, 
               new FileOutputStream("watermark_pagenumbers.pdf"));
            // adding some metadata
            HashMap moreInfo = new HashMap();
            moreInfo.put("Author", "Bruno Lowagie");
            stamp.setMoreInfo(moreInfo);
            // adding content to each page
            int i = 0;
            PdfContentByte under;
            PdfContentByte over;
            Image img = Image.getInstance("watermark.jpg");
            BaseFont bf = 
               BaseFont.createFont
                 (BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
            img.setAbsolutePosition(200, 400);
            while (i < n) {
                i++;
                // watermark under the existing page
                under = stamp.getUnderContent(i);
                under.addImage(img);
                // text over the existing page
                over = stamp.getOverContent(i);
                over.beginText();
                over.setFontAndSize(bf, 18);
                over.setTextMatrix(30, 30);
                over.showText("page " + i);
                over.setFontAndSize(bf, 32);
                over.showTextAligned
                   (Element.ALIGN_LEFT, "DUPLICATE", 230, 430, 45);
                over.endText();
            }
            // adding an extra page
            stamp.insertPage(1, PageSize.A4);
            over = stamp.getOverContent(1);
            over.beginText();
            over.setFontAndSize(bf, 18);
            over.showTextAligned(Element.ALIGN_LEFT, 
                    "DUPLICATE OF AN EXISTING PDF DOCUMENT", 30, 600, 0);
            over.endText();
            // adding a page from another document
            PdfReader reader2 = new PdfReader("SimpleAnnotations1.pdf");
            under = stamp.getUnderContent(1);
            under.addTemplate
                (stamp.getImportedPage(reader2, 3), 1, 0, 0, 1, 0, 0);
            // closing PdfStamper will generate the new PDF file
            stamp.close();
        }
        catch (Exception de) {
            de.printStackTrace();
        }
    }
}

A good introduction to iText : http://www.informit.com/articles/printerfriendly.aspx?p=420686

1 comment: