Active Directory Products
Calls To Calendar
SMS To CSV
SMS To Gmail
Voicemail To Gmail
How Long For Me
<< 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
// 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.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.
Fixing Virtual PC 2007 To Run On Windows 7
Awesome .NET 4: Named and Optional Parameters for Classes and Methods
Resolving Odd 5 Minute Timeout in HttpWebRequest.
Setting up a real VPN with your every day consumer router and DD-WRT
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: