Search code examples
c#asp.netitext

Converting multiple TIFF Images to PDF using iTextSharp


I’m using WebSite in ASP.NET and iTextSharp PDF library. I have a tiff document image that contains 3 pages, I would want to convert all those 3 tiff pages into 1 PDF file with 3 pages.

I try this but it doesn't work as well...

Please tell me what should I do?

using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

Document document = new Document();
using (var stream = new FileStream(@"C:\File\0.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
{
    PdfWriter.GetInstance(document, stream);
    document.Open();
    using (var imageStream = new FileStream(@"C:\File\0.tiff", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    {
        var image = iTextSharp.text.Image.GetInstance(imageStream);
        document.Add(image);
    }
    document.Close();
}

Solution

  • // creation of the document with a certain size and certain margins
    iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);
    
    // creation of the different writers
    iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(Server.MapPath("~/App_Data/result.pdf"), System.IO.FileMode.Create));
    
    // load the tiff image and count the total pages
    System.Drawing.Bitmap bm = new System.Drawing.Bitmap(Server.MapPath("~/App_Data/source.tif"));
    int total = bm.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);
    
    document.Open();
    iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;
    for (int k = 0; k < total; ++k)
    {
        bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k);
        iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, System.Drawing.Imaging.ImageFormat.Bmp);
        // scale the image to fit in the page
        img.ScalePercent(72f / img.DpiX * 100);
        img.SetAbsolutePosition(0, 0);
        cb.AddImage(img);
        document.NewPage();
    }
    document.Close();