Bad performance convert tif to pdf using ITextSharp
Modify GetInstance method argument to
GetInstance(bm, ImageFormat.Tiff)
this might increase the performance
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, ImageFormat.Tiff);
I'm not sure what was available when this question was originally posted but it appears iText 5.x has more to offer when converting TIFF to PDF. There is also a basic code sample in iText in Action 2nd Edition "part3.chapter10.PagedImages" and I haven't noticed any performance problems. However, the sample doesn't handle scaling well so I changed it like this:
public static void AddTiff(Document pdfDocument, Rectangle pdfPageSize, String tiffPath)
{
RandomAccessFileOrArray ra = new RandomAccessFileOrArray(tiffPath);
int pageCount = TiffImage.GetNumberOfPages(ra);
for (int i = 1; i <= pageCount; i++)
{
Image img = TiffImage.GetTiffImage(ra, i);
if (img.ScaledWidth > pdfPageSize.Width || img.ScaledHeight > pdfPageSize.Height)
{
if (img.DpiX != 0 && img.DpiY != 0 && img.DpiX != img.DpiY)
{
img.ScalePercent(100f);
float percentX = (pdfPageSize.Width * 100) / img.ScaledWidth;
float percentY = (pdfPageSize.Height * 100) / img.ScaledHeight;
img.ScalePercent(percentX, percentY);
img.WidthPercentage = 0;
}
else
{
img.ScaleToFit(pdfPageSize.Width, pdfPageSize.Height);
}
}
Rectangle pageRect = new Rectangle(0, 0, img.ScaledWidth, img.ScaledHeight);
pdfDocument.SetPageSize(pageRect);
pdfDocument.SetMargins(0, 0, 0, 0);
pdfDocument.NewPage();
pdfDocument.Add(img);
}
}
The trouble is with the length of time it takes for iTextSharp to finishing messing around with your System.Drawing.Image object.
To speed this up to literally a 10th of a second in some tests I have run you need to save the selected frame out to a memory stream and then pass the byte array of data directly to the GetInstance method in iTextSharp, see below...
bm.SelectActiveFrame(FrameDimension.Page, k);
iTextSharp.text.Image img;
using(System.IO.MemoryStream mem = new System.IO.MemoryStream())
{
// This jumps all the inbuilt processing iTextSharp will perform
// This will create a larger pdf though
bm.Save(mem, System.Drawing.Imaging.ImageFormat.Png);
img = iTextSharp.text.Image.GetInstance(mem.ToArray());
}
img.ScalePercent(72f / 200f * 100);