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.
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();
}
}
///////////////////////////////////////////////
Related posts brought to you by Yet Another Related Posts Plugin.
















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
“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
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.
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.
I want to know wat is itextsharp, i dont know about it
i want how to create it ,
Please help me out people
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!
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.
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;
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.
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
Hi, Any one know how to process a Tagged PDF using Itextsharp.
-KSM
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
Hi,
i want to know is there a way to add document properties like Author,Title to a existing PDF file.
Thanks
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?
Thanks for the article. I have small requirement of edit exisiting pdf text, Could you please share how to do this task
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!
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.
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
Hi,
Thank you so much for your codes. It has been a great help. Kudos to you.
Best regards