Showing posts with label PDF. Show all posts
Showing posts with label PDF. Show all posts

Monday, 13 June 2011

SSJS creation of PDF with iText

A customer needed their new XPages application to email invoices to their clients as PDF attachments. After a bit of research, I worked out a simple way to do this using Server Side Javascript with iText. This content explains what I discovered, because I couldn't find a similar post:

  1. Download the iText jar file from here.
  2. From 'Window' menu select 'Show Eclipse Views', 'Other', 'Package Explorer', to add the jar file to this folder of your database:
  3. Create a PDF file as a base template. I did this in Symphony as it saved the complication of adding lines and graphics programmatically. You then overlay text on this PDF to create each file.
  4. Call the following SSJS function to produce the PDF and attach it to a rich text field in a document:
//A. Load the java packages
importPackage(com.itextpdf);
importPackage(com.itextpdf.text);
importPackage(com.itextpdf.text.pdf);
importPackage(com.itextpdf.text.pdf.fonts);
importPackage(java.io);

//B. Initialize and get the PDF template (eg: from the Notes Data directory)
var theDirectory= session.getEnvironmentString("Directory",true);
var reader = new com.itextpdf.text.pdf.PdfReader (theDirectory + "/Template.pdf");
var fileOut = new java.io.FileOutputStream(filename);
var stamper = new com.itextpdf.text.pdf.PdfStamper(reader, fileOut);
var canvas = stamper.getOverContent(1);

//C. Embed the fonts you intend to use
var arial = new BaseFont.createFont("c:/windows/fonts/arial.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED);
var arialbd = new BaseFont.createFont("c:/windows/fonts/arialbd.ttf", BaseFont.WINANSI, BaseFont.EMBEDDED);
var NORMAL = new Font(arial,10);
var BOLD = new Font(arialbd,10);
var BOLD11 = new Font(arialbd,11);
var BOLD12 = new Font(arialbd,12);

//D. Create and place your data eg:
var client = new Phrase(doc.getItemValueString("Client"),NORMAL);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, client, 65, 670, 0);
or
var lcost = new Phrase(@Text(doc.getItemValueDouble("Cost"),"C,"), BOLD11);
ColumnText.showTextAligned(canvas, Element.ALIGN_RIGHT, lcost, 563, 533 - (i*44), 0);
Note that the coordinates are in points, starting from the bottom-left of the page. Zero rotation. 1" = 72 points = 25.4mm

//E. Close and Attach
stamper.close();
fileOut.close();

//attach the pdf
var rtitem:NotesRichTextItem= doc.createRichTextItem("Invoice");
rtitem.embedObject(NotesEmbeddedObject.EMBED_ATTACHMENT, "", filename, null);

For more detailed information this book can be purchased here: