Monday, 14 September 2009

Dynamically Alter a PDF in ASP.NET Using iTextSharp...

Here's a class/method that can be used to generate a PDF order form on the fly, on your website.

It's only really applicable in the current state if you had a site that was selling a single product at a time, but this provides a proof-of-concept which you could extend/evolve to do more-or-less whatever you want, within reason. You wouldn't want to be (re)generating the PDF each time an order was placed for example, but it could be useful if you had a fax order form for a product(s) and their price(s) needed to be changed by (e.g.) 10%:

using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace YourProject.Utils
public class PDFGeneration
public static void RegenerateFaxOrderForm(
string title,
string rrp,
string price)
// get the filename
string fileNameFaxOrderForm =
string fileNameFaxOrderFormOriginal =
string fileNameFaxOrderForm = HttpContext.Current.Server.MapPath("~/Content/Images/FaxOrderForm/FaxOrderForm.pdf");
string fileNameFaxOrderFormOriginal = HttpContext.Current.Server.MapPath("~/Content/Images/FaxOrderForm/FaxOrderFormOriginal.pdf");
PdfReader pdfReader = null;
PdfStamper pdfStamper = null;
pdfReader = new PdfReader(fileNameFaxOrderFormOriginal);
pdfStamper = new PdfStamper(pdfReader, new FileStream(fileNameFaxOrderForm, FileMode.Create));
BaseFont bf = BaseFont.CreateFont("Helvetica", BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

PdfContentByte overContent = pdfStamper.GetOverContent(1);

Rectangle pageSize = pdfReader.GetPageSize(1);
Rectangle cropBox = pdfReader.GetCropBox(1);

// titles
overContent.SetFontAndSize(bf, 11);
overContent.SetTextMatrix(60, 583);
// RRP
overContent.SetFontAndSize(bf, 11);
overContent.SetTextMatrix(270, 583);
// prices
overContent.SetFontAndSize(bf, 11);
overContent.SetTextMatrix(345, 583);
// write it out
catch (Exception ex)
// do what you like with the exception
if (pdfStamper != null)

if (pdfReader != null)

...obviously using iTextSharp here, which is IMHO a truly excellent library!

No comments:

Post a Comment

Migrating (and Open-Sourcing) an Historical Codebase: SVN-to-Git

I have a SVN repo on my local machine that I have been shoving stuff into since before I knew how to use revision control systems properly (...