Skip to content

Convert a TIFF to PDF in C#

Since 1.1View as Markdown

Put every page of a TIFF file, such as a scan or a fax, on its own PDF page.

PdfImage.GetPageCount counts the pages of the TIFF and PdfImage.Load(path, page) loads one, from 0. Add a PDF page the size of the image, which is its pixel size at the resolution the file records, and draw the image at its natural size.

recipe-tiff-to-pdf.cs
#:package PdfNetStack@1.2.0
using PdfNetStack;
using PdfNetStack.Drawing;
PdfDocument doc = PdfDocument.Create();
int pages = PdfImage.GetPageCount("scan.tif");
for (int i = 0; i < pages; i++)
{
PdfImage image = PdfImage.Load("scan.tif", i);
// A page the size of the image at its recorded resolution, in points.
PdfPage page = doc.Pages.Add(PdfRectangle.FromSize(image.Width, image.Height));
using PdfGraphics g = page.CreateGraphics();
g.DrawImage(image, 0, 0);
}
doc.Save("scan.pdf");
Console.WriteLine($"{pages} pages written");
  • A TIFF page stored as one strip of CCITT fax or JPEG data goes into the PDF as is, without decoding (CCITTFaxDecode, DCTDecode). Other pages are decoded and Flate compressed.
  • TIFF strips and tiles, chunky and planar data, PackBits, LZW, Deflate, CCITT Group 3 and 4 and JPEG compression, bilevel to 16 bit samples, alpha and BigTIFF are read. A damaged file raises a FormatException.
  • A file without a resolution is taken at 96 pixels per inch. To fit pages to A4 instead, add PdfRectangle.A4 pages and draw with PdfImageFit.Contain.