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
#if DEBUG
string fileNameFaxOrderForm =
@"\Content\Images\FaxOrderForm\FaxOrderForm.pdf";
string fileNameFaxOrderFormOriginal =
@"\Content\Images\FaxOrderForm\FaxOrderFormOriginal.pdf";
#else
string fileNameFaxOrderForm = HttpContext.Current.Server.MapPath("~/Content/Images/FaxOrderForm/FaxOrderForm.pdf");
string fileNameFaxOrderFormOriginal = HttpContext.Current.Server.MapPath("~/Content/Images/FaxOrderForm/FaxOrderFormOriginal.pdf");
#endif
PdfReader pdfReader = null;
PdfStamper pdfStamper = null;
try
{
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);

overContent.BeginText();
// titles
overContent.SetFontAndSize(bf, 11);
overContent.SetTextMatrix(60, 583);
overContent.ShowText(title);
// RRP
overContent.SetFontAndSize(bf, 11);
overContent.SetTextMatrix(270, 583);
overContent.ShowText(rrp);
// prices
overContent.SetFontAndSize(bf, 11);
overContent.SetTextMatrix(345, 583);
overContent.ShowText(price);
// write it out
overContent.EndText();
}
catch (Exception ex)
{
// do what you like with the exception
Console.WriteLine(ex.Message);
}
finally
{
if (pdfStamper != null)
{
pdfStamper.Close();
}

if (pdfReader != null)
{
pdfReader.Close();
}
}
}
}
}


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

No comments:

Post a Comment