It comes up from time to time that we need to generate a PDF from within a .NET application. There are plenty of PDF tools out there – free and paid. Our favorite is one called iTextSharp. Unfortunately, its developers recently changed its licensing model from the commercial use-friendly LGPL to the Affero GPL, which does not permit use on a public web server without releasing your own code under a similar free license. However, older versions of the library can still be used under the old license and so we am using version 4.1.6 for our example.
This toolkit provides a class called PdfStamper that allows you to set field values of a form-based PDF, then draw those fields to static text, in essence, “flattening” the form. This gives you a very quick solution for generating a PDF for your users – you can create a form-based PDF in Adobe Acrobat Professional with fields as placeholders to be filled in programmatically.
The example function below accepts a PDF form and an array of field names and values and will generate a “flattened” PDF that can be returned to users.
/// Fills in the fields of a PDF
/// <param name=”strInputFileName”></param>
/// <param name=”strOutputFileName”></param>
/// <param name=”arrInputFields”></param>
/// <param name=”arrOutputFields”></param>
private void GeneratePdf(string strInputFileName, string strOutputFileName,
string arrFieldNames, string arrFieldValues)
// Verify that we have file names
if (null == strInputFileName || null == strOutputFileName ||
“” == strInputFileName.Trim() || “” == strOutputFileName.Trim())
throw new Exception(“Please provide input and output file names.”);
if (arrFieldNames.Length != arrFieldValues.Length)
throw new Exception(“The names and values arrays must match.”);
using (FileStream fileOut = new FileStream(strOutputFileName,
PdfReader reader = new PdfReader(strInputFileName);
PdfStamper stamper = new PdfStamper(reader, fileOut);
AcroFields fields = stamper.AcroFields;
// Fields on the form will be rendered as text
stamper.FormFlattening = true;
for (int i = 0; i < arrFieldNames.Length; i++)
This, and other tips, tricks and special methods, are only a small sample of how our software application engineers can help make your applications easier to use for your staff and clients. Talk to our eBusiness Solutions team today.
|Enjoy Your 30-day Free Trial!|
|Learn how Inbound Marketing Software can help your business grow!|