Showing posts with label tiff. Show all posts
Showing posts with label tiff. Show all posts

Monday, May 17, 2010

Using C# to convert Tif to Pdf

Below is code that allows you to create a PDF file from one or more Tif files (even those with multiple pages).

This code references iTextSharp:
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using System.Drawing.Imaging;


Below the code is setting up the document/pdf and adding a tif file to the pdf:

string sMergedFiles = "C:\\PDFTest\\PdfReport.PDF";

string sTiffFiles = "C:\\PDFTest\\TiffFiles\\";

Document document = new Document(PageSize.A4, 50, 50, 50, 50);

PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(sMergedFiles, FileMode.CreateNew));

document.Open();

//here you can loop thru and call AddTiff2Pdf for multiple files

string tiffFileName = Path.Combine(sTiffFiles, "asdf.tif");

AddTiff2Pdf(tiffFileName, ref writer, ref document);

string tiffFileName = Path.Combine(sTiffFiles, "1234.tif");

AddTiff2Pdf(tiffFileName, ref writer, ref document);

document.Close();


Below is the function used to add the tiff to the pdf:

private void AddTiff2Pdf(string tiffFileName, ref PdfWriter writer, ref Document document)
{

System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(tiffFileName);

int numberOfPages = bitmap.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);

PdfContentByte cb = writer.DirectContent;

for (int page = 0; page < numberOfPages; page++)
{

bitmap.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, page);

System.IO.MemoryStream stream = new System.IO.MemoryStream();

bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);

iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(stream.ToArray());

stream.Close();

img.ScalePercent(72f / bitmap.HorizontalResolution * 100);

img.SetAbsolutePosition(0, 0);

cb.AddImage(img);

document.NewPage();
}
}