iText

iText is a reporting tool which provide a  library tool for creating a PDF document.. iText enables developers looking to enhance web- and other applications with dynamic PDF document generation and/or manipulation.
Developers can use iText to::   
  1. Serve PDF to a browser
  2. Generate dynamic documents from XML files or databases
  3. Use PDF's many interactive features
  4. Add bookmarks, page numbers, watermarks, etc.
  5. Split, concatenate, and manipulate PDF pages
  6. Automate filling out of PDF forms
  7. Add digital signatures to a PDF file

General Use of iText

HelloWorld Program

HelloWorld

public class HelloWorld {
     public static void main(String[] args) {
        System.out.println("Hello World");
        // step 1: creation of a document-object
        Document document = new Document();
        try {
            // step 2:
            // we create a writer that listens to the document
            // and directs a PDF-stream to a file
            PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));
            // step 3: we open the document
            document.open();
            // step 4: we add a paragraph to the document
            document.add(new Paragraph("Hello World"));
        } catch (DocumentException de) {
            System.err.println(de.getMessage());
        } catch (IOException ioe) {
            System.err.println(ioe.getMessage());
        }
        // step 5: we close the document
        document.close();
    }
}

Output: A new PDF document named with HelloWorld.pdf must be found after executing the above program

DefaultPageSize

Following are some sample page templets provided by iText. Put the following lines in your code to see the output.
pagesize. represent the  page size, as A4,A3,A2,A1 pages..etc.
document.newPage();
document.add(new Paragraph("The default PageSize is DIN A4."));
document.setPageSize(PageSize.A3);
document.setPageSize(PageSize.A2);
document.setPageSize(PageSize.A1);
document.setPageSize(PageSize.A0);

LandscapePortrait

document.setPageSize(PageSize.A4.rotate());
document.add(new Paragraph("To create a document in landscape format, just make the height smaller than the width. For instance by rotating the PageSize Rectangle: PageSize.A4.rotate()"));
document.setPageSize(PageSize.A4);
document.newPage();
document.add(new Paragraph("This is portrait again"));

CustomPageSize

Following code will give the page size as per urs choice  for example 3 inch x 2.54 = 7.62 cm,10 inch x 2.54 = 25.4 cm
document.newParagraph();
document.add(new Paragraph("3 inch x 2.54 = 7.62 cm"));
document.add(new Paragraph("10 inch x 2.54 = 25.4 cm"));

HelloSystemOut

set the Margins values of form as top,right,bottom,left
document.add(new Paragraph("The left margin of this document is 36pt (0.5 inch); the right margin 72pt (1 inch); the top margin 108pt (1.5 inch); the bottom margin 180pt (2.5 inch). "));
Paragraph paragraph = new Paragraph();
paragraph.setAlignment(Element.ALIGN_JUSTIFIED);
for (int i = 0; i < 20; i++) {
    paragraph.add("Hello World, Hello Sun, Hello Moon, Hello Stars, Hello Sea, Hello Land, Hello People. ");
}
document.add(paragraph);
document.setMargins(180, 108, 72, 36);
document.add(new Paragraph("Now we change the margins. You will see the effect on the next page."));
document.add(paragraph);
document.setMarginMirroring(true);HelloEncrypted
document.add(new Paragraph("Starting on the next page, the margins will be mirrored."));
document.add(paragraph);

HelloWorldMultiple

dispaly output in txt format
PdfWriter.getInstance(document, System.out);
PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.txt"));
PdfWriter pdf = PdfWriter.getInstance(document,new FileOutputStream("HelloWorldPdf.pdf"));
RtfWriter2 rtf = RtfWriter2.getInstance(document,new FileOutputStream("HelloWorldRtf.rtf"));
HtmlWriter html = HtmlWriter.getInstance(document,new FileOutputStream("HelloWorldHtml.html"));

Again a PDF with the text 'Hello World', but this time the document is encrypted. To read it, you need to know the userpassword:'Hello'
PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream("HelloEncrypted.pdf"));
writer.setEncryption(PdfWriter.STRENGTH128BITS, "Hello", "World", PdfWriter.AllowCopy | PdfWriter.AllowPrinting);

HelloWorldMeta

PdfWriter.getInstance(document, new FileOutputStream("HelloWorldMeta.pdf"));
// step 3: we add some metadata open the document
document.addTitle("Hello World example");
document.addSubject("This example explains how to add metadata.");
document.addKeywords("iText, Hello World, step 3, metadata");
document.addCreator("My program using iText");
document.addAuthor("Bruno Lowagie");

iText in a Web Application

HelloWorldServletOutSimplePdf
if ("pdf".equals(presentationtype)) {
    response.setContentType("application/pdf");
    PdfWriter.getInstance(document, response.getOutputStream());
}
else if ("html".equals(presentationtype)) {
    response.setContentType("text/html");
    HtmlWriter.getInstance(document, response.getOutputStream());
}
else if ("rtf".equals(presentationtype)) {
    response.setContentType("text/rtf");
    RtfWriter.getInstance(document, response.getOutputStream());
}
else {
    response.sendRedirect("http://itextdocs.lowagie.com/tutorial/general/webapp/index.html#HelloWorld");
}
// take the message from the URL or create default message
String msg = (String) request.getParameter("msg");
if (msg == null || msg.trim().length() <= 0)
    msg = "[ specify a message in the 'msg' argument on the URL ]";
// create simple doc and write to a ByteArrayOutputStream
Document document = new Document();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
document.open(); document.add(new Paragraph(msg));
document.add(Chunk.NEWLINE);
document.add(new Paragraph("The method used to generate this PDF was: " + methodGetPost));
document.close();
// setting some response headers
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
// setting the content typeresponse.setContentType("application/pdf");
// the contentlength is needed for MSIE!!!
response.setContentLength(baos.size());
// write ByteArrayOutputStream to the ServletOutputStream
ServletOutputStream out = response.getOutputStream();
baos.writeTo(out);
out.flush();

SilentPrintServlet
public void doWork(HttpServletRequest requ, HttpServletResponse resp)throws ServletException, IOException {
ServletOutputStream out = resp.getOutputStream();
// what did the user request?
int action = ACT_INIT;
int sub = ACT_INIT;
try {
    action = Integer.parseInt(requ.getParameter("action"));
    sub = Integer.parseInt(requ.getParameter("sub"));
} catch (Exception e) {
}
switch (action) {
    case ACT_INIT: {
        htmlHeader(out, requ, resp);
        formular(out, requ, resp, sub);
        break;
    }
    case ACT_REPORT_1: {
        Document document = new Document();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            PdfWriter writer = PdfWriter.getInstance(document, baos);
            document.open();
            if (requ.getParameter("preview") == null)
                writer.addJavaScript("this.print(false);", false);
            document.add(new Chunk("Silent Auto Print"));
            document.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        resp.setContentType("application/pdf");

        resp.setContentLength(baos.size());
        baos.writeTo(out);
        out.flush();
        break;
    }
}

Manipulating existing PDF documents

TwoOnOne AddWatermarkPageNumbers
// we create a reader for a certain document
PdfReader reader = new PdfReader("ChapterSection.pdf");
// we retrieve the total number of pages
int n = reader.getNumberOfPages();
// we retrieve the size of the first page
Rectangle psize = reader.getPageSize(1);
float width = psize.height();
float height = psize.width();
// step 1: creation of a document-object
Document document = new Document(new Rectangle(width, height));
// step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("2on1.pdf"));
// step 3: we open the document
document.open();
// step 4: we add content
PdfContentByte cb = writer.getDirectContent();
int i = 0;
int p = 0;
while (i < n) {
    document.newPage();
    p++;
    i++;
    PdfImportedPage page1 = writer.getImportedPage(reader, i);
    cb.addTemplate(page1, .5f, 0, 0, .5f, 60, 120);
    if (i < n) {
        i++;
        PdfImportedPage page2 = writer.getImportedPage(reader, i);
        cb.addTemplate(page2, .5f, 0, 0, .5f, width / 2 + 60, 120);
    }
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    cb.beginText();
    cb.setFontAndSize(bf, 14);
    cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "page " + p + " of " + ((n / 2) + (n % 2 > 0? 1 : 0)), width / 2, 40, 0);
    cb.endText();
}

// we create a reader for a certain document
PdfReader reader = new PdfReader("ChapterSection.pdf");
int n = reader.getNumberOfPages();
// we 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);EncryptorExample
// closing PdfStamper will generate the new PDF file
stamp.close();
Register PdfReader reader = new PdfReader("SimpleRegistrationForm.pdf");
int n = reader.getNumberOfPages();
// filling in the form
PdfStamper stamp1 = new PdfStamper(reader, new FileOutputStream("registered.pdf"));
AcroFields form1 = stamp1.getAcroFields();
form1.setField("name", "Bruno Lowagie");
form1.setField("address", "Baeyensstraat 121, Sint-Amandsberg");
form1.setField("postal_code", "BE-9040");
form1.setField("email", "bruno@lowagie.com");
stamp1.close();
// filling in the form and flatten
reader = new PdfReader("SimpleRegistrationForm.pdf");
PdfStamper stamp2 = new PdfStamper(reader, new FileOutputStream("registered_flat.pdf"));
AcroFields form2 = stamp2.getAcroFields();
form2.setField("name", "Bruno Lowagie");
form2.setField("address", "Baeyensstraat 121, Sint-Amandsberg");
form2.setField("postal_code", "BE-9040");
form2.setField("email", "bruno@lowagie.com");
stamp2.setFormFlattening(true);
stamp2.close();
PdfReader reader = new PdfReader("ChapterSection.pdf");
PdfEncryptor.encrypt(reader,new FileOutputStream("encrypted.pdf"),"Hello".getBytes(),"World".getBytes(),PdfWriter.AllowPrinting | PdfWriter.AllowCopy,false);

Concatenate

int pageOffset = 0;
ArrayList master = new ArrayList();
int f = 0;
String outFile = args[args.length-1];
Document document = null;
PdfCopy writer = null;
while (f < args.length-1) {
    // we create a reader for a certain document
    PdfReader reader = new PdfReader(args[f]);
    reader.consolidateNamedDestinations();
    // we retrieve the total number of pages
    int n = reader.getNumberOfPages();
    List bookmarks = SimpleBookmark.getBookmark(reader);
    if (bookmarks != null) {
        if (pageOffset != 0)
            SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
        master.addAll(bookmarks);
    }
     pageOffset += n;

    if (f == 0) {
        // step 1: creation of a document-object
        document = new Document(reader.getPageSizeWithRotation(1));
        // step 2: we create a writer that listens to the document
        writer = new PdfCopy(document, new FileOutputStream(outFile));
        // step 3: we open the document
        document.open();
    }
    // step 4: we add content
    PdfImportedPage page;
    for (int i = 0; i < n; ) {
        ++i;
        page = writer.getImportedPage(reader, i);
        writer.addPage(page);
    }
    PRAcroForm form = reader.getAcroForm();
    if (form != null)
        writer.copyAcroForm(reader);
    f++;
}
if (master.size() > 0)
    writer.setOutlines(master);
// step 5: we close the document
document.close();

ConcatenateForms

PdfReader reader1 = new PdfReader("SimpleRegistrationForm.pdf");
PdfReader reader2 = new PdfReader("TextFields.pdf");
PdfCopyFields copy = new PdfCopyFields(new FileOutputStream("concatenatedforms.pdf"));
copy.addDocument(reader1);
copy.addDocument(reader2);
copy.close();

Measurements

document.add(new Paragraph("The size of this page is 288x720 points."));
document.add(new Paragraph("288pt / 72 points per inch = 4 inch"));
document.add(new Paragraph("720pt / 72 points per inch = 10 inch"));
document.add(new Paragraph("The size of this page is 4x10 inch."));
document.add(new Paragraph("4 inch x 2.54 = 10.16 cm"));
document.add(new Paragraph("10 inch x 2.54 = 25.4 cm"));
document.add(new Paragraph("The size of this page is 10.16x25.4 cm."));
document.add(new Paragraph("The left border is 36pt or 0.5 inch or 1.27 cm"));
document.add(new Paragraph("The right border is 18pt or 0.25 inch or 0.63 cm."));
document.add(new Paragraph("The top and bottom border are 72pt or 1 inch or 2.54 cm."));

NewPage

document.add(new Paragraph("This is the first page."));
document.newPage();
document.add(new Paragraph("This is a new page"));
document.newPage();
document.newPage();
document.add(new Paragraph("We invoked new page twice, yet there was no blank page added. Between the second page and this one. This is normal behaviour."));
document.newPage();
writer.setPageEmpty(false);
document.newPage();
document.add(new Paragraph("We told the writer the page wasn't empty."));
document.newPage();
document.add(Chunk.NEWLINE);
document.newPage();
document.add(new Paragraph("You can also add something invisible if you want a blank page."));
document.add(Chunk.NEXTPAGE);
document.add(new Paragraph("Using Chunk.NEXTPAGE also jumps to the next page"));

iTextVersion

document.add(new Paragraph("This page was made using " + Document.getVersion()));

No comments:

Post a Comment