Monday, January 19, 2009

iText: A PDF library for Java/.NET

I've been trying the iText library lately. It makes generating PDFs quite simple. Check out this C# code snippet of inserting an image (JPEG, in this case) into a PDF:

Document doc = new Document();
PdfWriter pdf = PdfWriter.GetInstance(doc, new System.IO.FileStream("fileout.pdf", System.IO.FileMode.Create));

#region Getting my byte array
//You don't have to do this if you are using a database - read the image as a byte array from the database instead
FileStream fstream = new FileStream(@"C:\rosewhite.jpg", System.IO.FileMode.Open);
byte[] byteBuf = new byte[100000];
int actualSize = fstream.Read(byteBuf, 0, 100000);
byte[] byteBufNew = new Byte[byteBuf.Length];
for (int i = 0; i < byteBuf.Length; i++)
byteBufNew[i] = byteBuf[i];

//provide the byte array you got from the database in place of byteBufNew
doc.Add(new Jpeg(byteBufNew));

You can do lots of other stuff with iText too, such as inserting tables, add digital signatures, bookmarks etc. iText is a free library and can read more about it here.

1 comment:

srikant said...

Nice article..quite helpful as lot of times ppl fail to convert picture to PDF. Btw, this is Ravi Gopidi's office colleague.