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

Related posts brought to you by Yet Another Related Posts Plugin.

Comments

27 Responses to “How to use iTextSharp .NET PDF library to insert text and image in an existing PDF form template”
  1. Shree says:

    Hi MK,

    ItextSharp is a cool opensource PDF generator. It has worked well for me while creating English PDF. Somehow the Template based approach never worked for me while creating PDF with Japanese Text. If I create the document on the fly everything comes out perfectly, I then have much control generation of multiple pages.
    With whatever limitation it has I still find ItextSharp as the best tool for PDF generation from .net.

    Nice article.

    Shree

  2. Suresh Sundaram says:

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

    - HOW?

    When I go to Tools/References, click browse and select “itextsharp.dll” I get an error message “Can’t add reference to selected file.”

    Suresh

  3. MK says:

    Thanks for your comment Suresh.

    Try this -

    Copy itextsharp.dll to Bin folder of your project.

    Right-click on Bin folder, click Add Reference.

    Choose Browse tab.

    Navigate to and select itextsharp.dll

    Let me know if that worked.

  4. Chris says:

    I have a jpg image that I want to insert into my PDF. So I created a text field called “TestImage”.
    The only problem is that my pdf is multi page and the image gose on the first page and not the page that I have the field on. Can anyone help.

    Thanks Chris.

  5. Naresh says:

    I want to know wat is itextsharp, i dont know about it
    i want how to create it ,
    Please help me out people

  6. Abhay says:

    Thank you for wonderful post.

    I have a question regarding this approach. I have template and when I try to create with using template approach, everything works when only one instance access this template, however if I try to perform same operation with multiple instances, this approach throws error of file already in use. Can you suggest me how to come over this problem. Am I not considering any variable or creating instance required for multiple access for template approach ??? Please reply me!

  7. MK says:

    Are you closing and destroying the previous instance and then trying to open a new instance? OR are you trying to open new instance without destroying previous one’s? Please let me know, Thanks.

  8. CT_KLEIN says:

    I am having a problem with the template approach… does this only work with TextField controls and not Text or Image?
    Using your example if I had 3 TextField controls, 3 Text objects and an image object I am only seeing the TextField controls coming back in
    AcroFields testForm = pdfStamper.AcroFields;

  9. MK says:

    This should work with an image object. Other thing that you can do is try rendering image within the Text Filed and that should work too.

  10. Amit says:

    Hi..,

    i am working on c# window application. i want to read PDF file which have 100 of bookmarks. and also want to modify such bookmarks in pdf file.
    so how i use iText for that???

    Please help me..!!

    thx

  11. KSM says:

    Hi, Any one know how to process a Tagged PDF using Itextsharp.

    -KSM

  12. simon says:

    Hi, MK:
    How do you handle a one-page form template with some fields possible cross over multiple pages? In other words, some of the fields have REAL long contents and overfolw the field space.
    I appreciate your help.

    Simon

  13. Bharath says:

    Hi,

    i want to know is there a way to add document properties like Author,Title to a existing PDF file.

    Thanks

  14. John Miller says:

    I am also wondering how to load up multiple instances of a reader to use with a stamper.

    I am getting our company W-2’s on our intranet this year and some people will need multiple copies. Any ideas?

  15. sonj says:

    Thanks for the article. I have small requirement of edit exisiting pdf text, Could you please share how to do this task

  16. Hibernating Bear says:

    Hi,

    Made a few syntax changes to get this to work in VB .NET. I keep getting the error message “PDF header signature not found” at this line:

    pdfReader = new PdfReader(”F:\Websites\pdf_redesign\testTemplate.pdf”)

    I tried adding

    Response.Buffer = True
    Response.ContentType = “application/pdf”
    Response.AddHeader(”Content-Disposition”, “inline”)

    but it did not help at all. Could you let me know how to fix it, please. I would appreciate it!

  17. Harish says:

    Hi MK, hope you can help me. I have a issue with scanned docs, being converted by itextsharp to PDF. they are rotating more than zero degrees, and i am unable to control it. what i think is, the way the doc is scanned, itextsharp is printing in the same manner. ex: if i scan a doc as landscape, its printing as landscape in a portrait pdf, thus losing data. hope you understood my issue. i tried methods like Rotation(), but couldn’t get much help. can you help me. Let me know if you need the doc.

  18. John says:

    Thanks for your article it is very helpfull, I was wondering if you have had any problems with partial trust from your hosting when using Itext In an asp application?
    If so, how did you work around the security exception for partial trust issue?

    Many Thanks and keep up the great articles.

    John

  19. Sabrina says:

    Hi,

    Thank you so much for your codes. It has been a great help. Kudos to you.

    Best regards

  20. Khency says:

    Thank you very much.. it really helped !!!

  21. Bryan says:

    Thanks for the tutorial! With the lack of documentation and reference material this is crucial. I wrote up a similar example for how to add JavaScript code to an existing PDF. Maybe someone will find it useful.

    http://mattheyan.wordpress.com/2010/06/08/add-javascript-to-a-pdf-document-with-itextsharp/

  22. Bryan says:

    @John: AFAIK there are no partial trust issues, unless you are interacting with the file system and that causes problems. You can adapt the example code to work with in-memory streams.

  23. Arul Xavier says:

    Please tell me if is there any function in iTextSharp that dose replace(”xx”,”yy”) function in the pdf file without altering remaining parts of the file

  24. Moises says:

    Thanks MK!!!

    Excelent example… iTextSharp is EXCELENT!!!

    Your example helped me a lot …

  25. SK says:

    Hello,

    Thank you for good article.

    How can I edit or add action to existing (push) button of PDF? I have PDF template ready with push button field. I want to access the same button and set it’s URL, so each pdf has may same or different url. I fetch data for URL from database. Let me know how can I achieve this?

  26. Nishant says:

    Hi

    I have a problem while using IText

    I want to insert an Image at X,Y location in pdf

    any help will be appreciable

    Nishant

  27. Nishant says:

    Hi

    I have a problem while using IText

    I want to insert an Image at X,Y location in pdf

    any help will be appreciable

    Nishant

Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!