Tuesday, May 14, 2013

How To- Convert Multipage Tiff file into PDF in ASP.Net using C#

Multipage Tiff to PDF
Here, I am explaining how to convert a multipage tiff file into PDF file in C#. Sometimes we have a requirement to convert the multipage tiff file into PDF.I am using the iTextSharp (third party dll) for conversion of multipage tiff file into PDF file.

In my previous posts, I explained Send mail in ASP.Net, Convert DataTable into List, Constructor Chainning in C#, Convert a Generic List to a Datatable, Get Property Names using Reflection in C#Hard drive information using C#Create Directory/Folder using C#Check Internet Connection using C#SQL Server Database BackUp using C# and some other articles related to C#ASP.Net jQuery, Java Script and SQL Server.

Before starting the sample code, First of all download the iTextSharp and add the reference of following dll into your application.
1
itextsharp.dll

Now add the following namespaces in your code page.
1
2
3
4
using System.Drawing;
using System.Drawing.Imaging;
using iTextSharp.text;
using iTextSharp.text.pdf;
After adding above namespaces, write the following function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public void ConvertMultipageTifftoPdf()
{
  // Create the document with a certain size and certain margins 
  Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);
  // creation of output pdf file
  PdfWriter writer = PdfWriter.GetInstance(document, new System.IO.FileStream(Server.MapPath("~/PDF/Output.pdf"), System.IO.FileMode.Create));
  // load the tiff image and count the total number of pages
   Bitmap bm = new System.Drawing.Bitmap(Server.MapPath("~/Image/multipage_tiff_example.tif"));
  int total = bm.GetFrameCount(FrameDimension.Page);
  document.Open();
  PdfContentByte cb = writer.DirectContent;
  for (int k = 0; k < total; ++k)
  {
    bm.SelectActiveFrame(FrameDimension.Page, k);
    iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, 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();          
}
Output
Pdf File

I hope this will be helpful for you. I would like to have any feedback from you. Your valuable feedback, question, or comments about this article are always welcome.

No comments:

Post a Comment