Java Mailing List Archive

http://www.junlu.com/

Home » Home (12/2007) » iText »

[iText-questions] Insert an image into a PDF template - PdfContentByte null pointer

Sloey, James

2005-05-19

Replies:

I have a PDF template containing a background image and some fields that I fill with text.
I also need to insert a gif image of the persons signature on the page.
I read an archived reply from Paulo and tried to use PdfContentByte.
If I comment out the image statement the text gets filled in correctly on the output PDF file and the signature location is printed to stdout.
When I attempt to add the image I get a null pointer error.
Any help would be appreciated
Thanks
Jim Sloey
 
// example
import java.io.*;
import java.util.*;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.*;
import com.lowagie.text.DocumentException;
 
public class stampit {
 static void fillTemplate (String path, String template, String sig, String outfile){
  //get a handle to the file location
  String templatePath = path;
   
  if(templatePath == null)
   {templatePath = "/";}
  else if(!templatePath.endsWith("/"))
   {templatePath += "/";}
 try
  {
//  Reads in the pdf Template
  PdfReader reader = new PdfReader(templatePath + template);
  PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(path+outfile));
  AcroFields form = stamp.getAcroFields();
               
  //set the field values in the pdf form
  form.setField("name","James T. Sloey");
  float image_loc[] = form.getFieldPositions("signature");
        System.out.println(image_loc[0]);
        System.out.println(image_loc[1]);
        System.out.println(image_loc[2]);
        System.out.println(image_loc[3]);
        System.out.println(image_loc[4]);
  // get the image
  Image image = Image.getInstance(path+sig);
  stamp.getWriter().getDirectContent().addImage(image,100, 0, 0, 100, image_loc[2], image_loc[4]);
  // done
  stamp.setFormFlattening(true);
  stamp.close();}
               
 catch(Exception e)
  {System.out.println("Error: " + e);}
 }
 public static void main(String[] args) {
  String template = "template.pdf";
  String path = "/export/home/jsloey/src/";
  String outfile = "cn1234567.pdf";
  String sigfile = "sig.gif";
  System.out.println("Creating "+path+outfile+" from "+path+template);
  fillTemplate(path,template, sigfile, outfile);
  System.out.println("done");
 }
}
©2008 junlu.com - Jax Systems, LLC, U.S.A.