SUBSCRIBE - [ Tech News ] [ Make Money Blogging Tips ] [ Online Marketing Tips ] [ Web Dev News ]
Powered by MaxBlogPress  

How to use iTextSharp .NET PDF library to insert text and image in an existing PDF form template

October 17, 2008 by MK  
Filed under ASP.NET, C# / ASP.NET

This is my second post regarding iTextSharp PDF creation and manipulation. I have recently being involved in a web application where we have created a number of PDF’s with data coming from different feeds. In addition to my earlier post Using Open Source iTextSharp .NET PDF library to generate PDF on the fly -  here is more info on using the iTextSharp library to generate PDF’s dynamically.

Recommended reading - iText in Action: Creating and Manipulating PDF introduces iText and lowers the learning curve to its advanced features. Its numerous, valuable examples unlock many of the secrets hidden in Adobe’s PDF Reference. The examples are in Java but they can be easily adapted to .NET using one of iText’s .NET ports: iTextSharp (C#) or iText.NET (J#).

Here is the code that I have used to manipulate an existing PDF template and to insert text and image in the PDF template using iTextSharp. Code is quite self explanatory with some comments. In case you have questions please leave me a comment or leave a QUESTION IN MY FORUM UNDER ITEXTSHARP and I will reply back with answers.

You will first need the PDF file template for this method. You can easily create the template and form fields with Adobe Acrobat. The next step is quite simple. Read PDF file from disk, create instance of PDFStamper class, fill out the PDF form fields. Finally flatten the generated PDF file and save it to disk (or stream to client if necessary).

For those who are not familiar with iTextSharp. iTextSharp is a C# port of a Java library written to support the creation and manipulation of PDF documents. The project is available for download through SourceForge.net. With the iTextSharp DLL, it is possible to not only populate fields in an existing PDF document, but also to dynamically create PDFs.

You can use Adobe Acrobat professional to create a PDF form template. Follow these easy steps to create one -

Open your “template” pdf file to which you want to add text.

Click on the Form toolbar and add the form text fields to your pdf and give each of the fields names according to what text will be put in the field.

Then make the appropriate tweaks to the formatting and alignment with the ‘Appearance’ and ‘Options’ tabs of the ‘Text Field Properties’ window.  

Now you should have a pdf with form text fields in it for each of the areas on the pdf in which you want text and images displayed.

Please make sure you add REFERENCE to iTextSharp DLL before you test the following code. 

/////////////////FYI: Framework used - .NET 3.5///////////////////

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Text;
 
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        CreatePDFDocument();
    }
 
    /// <summary>
    /// Creates the PDF document with a given content at a given location.
    /// </summary>
    /// <param name=”strFilePath”>The file path to write the new PDF to.</param>
    /// <param name=”strContent”>Content in HTML to write to the PDF.</param>
    public void CreatePDFDocument()
    {
        string pdfTemplate = @”F:\pdf_redesign\testFinal.pdf”;
 
        string imagePath = String.Empty;
 
        imagePath = @”F:\pdf_redesign\community.jpg”;
 
        PdfReader pdfReader = null;
       
        // Create the form filler
        FileStream pdfOutputFile = new FileStream(pdfTemplate, FileMode.Create);
 
        pdfReader = new PdfReader(@”F:\Websites\pdf_redesign\testTemplate.pdf”);
       
        PdfStamper pdfStamper = null;
 
        pdfStamper = new PdfStamper(pdfReader, pdfOutputFile);
 
        // Get the form fields
        AcroFields testForm = pdfStamper.AcroFields;
 
        // Fill the form
        testForm.SetField(”textBox1″, “This is PDF generation test from coolwebdeveloper.com using iTextSharp PDF library”);
        testForm.SetField(”textBox2″, “This is PDF generation test from coolwebdeveloper.com using iTextSharp PDF library”);
 
        iTextSharp.text.Image instanceImg = iTextSharp.text.Image.GetInstance(imagePath);
 
        PdfContentByte overContent = pdfStamper.GetOverContent(1);
 
        //Specifying the name of the field wehere this image will be placed
        float[] imageArea = testForm.GetFieldPositions(”testImage1″);
 
        iTextSharp.text.Rectangle imageRect = new Rectangle(imageArea[1], imageArea[2], imageArea[3], imageArea[4]);
 
        instanceImg.ScaleToFit(imageRect.Width, imageRect.Height);
 
        instanceImg.SetAbsolutePosition(imageArea[3] - instanceImg.ScaledWidth + (imageRect.Width - instanceImg.ScaledWidth) / 2, imageArea[2] + (imageRect.Height - instanceImg.ScaledHeight) / 2);
 
        overContent.AddImage(instanceImg);
 
        //’Flatten’ (make the text go directly onto the pdf) and close the form
        pdfStamper.FormFlattening = true;
 
        pdfStamper.Close();
 
        pdfReader.Close();
 
 
    }
}

///////////////////////////////////////////////

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • LinkedIn
  • Reddit
  • StumbleUpon
  • Technorati
  • TwitThis
  • Yahoo! Buzz