Mailing List



NerdyHearn - Blog

<< Back To All Blogs

Creating a PDF with C# and iTextSharp

Wednesday, August 26th, 2009

I recently came across a situation in which I, oddly enough, needed to simply embed a single image in a PDF file. I figured I would share my thoughts on this particular example, as there are a number of different open source options out there for creating PDF files in C#.

For my use, I decided to go with iTextSharp, which is a port of the popular Java library iText. I went with this option for 2 main reasons: I have used iText before, and it allowed for the direct manipulation of binary streams (this is the format which I had my images in natively). Many of the other options required that the images be on a file system, which does not play well with a high-demand solution (as they cannot be stored in memory), and this often leads to corrupted output if multiple users are hitting a page at the same time.

The code itself is pretty simple for my use case, but so you have an idea of what it looks like, here is my example. This example takes the binary form of
a jpeg image, scales, rotates, centers, and places it in a pdf, which is then pushed out in ASP.NET:

iTextSharp.text.Document doc = new iTextSharp.text.Document();

// context is my HttpContext from ASP.NET
iTextSharp.text.pdf.PdfWriter.GetInstance(doc, context.Response.OutputStream);


// result is a Bitmap binary image
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(result, ImageFormat.Jpeg);

img.Alignment = iTextSharp.text.Image.MIDDLE_ALIGN;
img.ScaleToFit(600, 600);
img.RotationDegrees = 270;

The resulting PDF file will be written to the OutputStream of ASP.NET as it was defined in the instantiation of PdfWriter.

A pretty simple example, but especially in the case of images, iTextSharp was by far the simplest and best way for me to natively work with an image in binary format.

PDFin' Tom Out.


Howto CSharp

Related Blogs

Creating High Quality Images with C# and GDI
Resolving ASP.NET Web.Config Inheritance
Reading a Microsoft Project file (mpp) in C#
Resolving Odd 5 Minute Timeout in HttpWebRequest.
Determining if MOSS is Standard or Enterprise


Currently no comments.

Add A Comment



Email Address: (not public, used to send notifications on further comments)


Enter the text above, except for the 1st and last character:

NerdyHearn - Latest tech news relating to C#, ASP.NET, SharePoint, PHP, general development, and more. SaveMySerials - Protect yourself from theft, fire, natural disasters and more by recording your serial numbers