views:

250

answers:

1

I'm interested in filling out existing PDF forms programatically. All I really need to do is pull information from user input and then place the appropriate text over an existing PDF in the appropriate locations. I can already do this with reportlab by feeding the same sheet of paper into a printer, twice, but this just really rubs me the wrong way.

I'm tempted to just personally reverse engineer each existing PDF and draw every line and character myself before adding the user-inputted text, but I wanted to check to see if there was an easy way to take an existing PDF and set it as a background for some extra text. I'd really prefer to use python as it's the only language I feel comfortable with.

I also realize that I could just scan the document itself and use the resulting raster image as a background, but I would prefer the precision of vector graphics.

It seems like ReportLab has a commercial product with this functionality, and the specific function I'm looking for is in it (copyPages) - but it seems like overkill to pay for a 4 figure product for a single, simple function for a nonprofit use.

+2  A: 

If the PDF forms are real AcroForms you can use iText to fill them. I don't know if there's other port than iText (java, original) and iTextSharp (c#) but it's easy to use and free. You can take a look at this sample code or (java snippet):

String formFile = "/path/to/myform.pdf"
String newFile = "/path/to/output.pdf"
PdfReader reader = new PdfReader(formFile);
FileOutputStream outStream = new FileOutputStream(newFile);
PdfStamper stamper = new PdfStamper(reader, outStream);
AcroFields fields = stamper.getAcroFields();

// fill the form
fields.setField("name", "Shane");
fields.setField("url", "http://stackoverflow.com");

// PDF infos
HashMap<String, String> infoDoc = new HashMap<String, String>();
infoDoc.put("Title", "your title here");
infoDoc.put("Author", "JRE ;)");
stamper.setMoreInfo(infoDoc);

// Flatten the PDF & cleanup
stamper.setFormFlattening(true);
stamper.close();
reader.close();
outStream.close();
RC