Tip to convert TIF file to pdf using iText library.
I am going to explain how we can convert a TIF/TIFF file to PDF document using iText API. Before moving to the main subject of this tip I would like to give a small introduction of iText API.
What is iText ??
iText is a library that allows you to create and manipulate PDF documents. It enables developers looking to enhance web and other applications with dynamic PDF document generation and/or manipulation. You can create PDF documents from scratch with data from database, an XML file, or any other data source.
iText is available in Java as well as in C#.
What is TIF/TIFF file format ??
TIF/TIFF (Tagged Image File Format) file is high-quality graphics format often used for storing images with many colors, such as digital photos. It support for layers and multiple pages.
In one line you can say TIF/TIFF is nothing but a multipage image. Now I think atleast we have understood why iText and what is TIF/TIFF file format?
So we move to the main subject of this tip. Here we will see how we can esily convert a TIF to PDF using iText library.
I would like to explain it via an example code.
CODE::
/**
* Method to convert a TIFF to PDF directly.
*/
public void generatePDFFromTIF() throws DocumentException,IOException {
/*
* RandomAccessFileOrArray is a class from iText API which is representing our TIF file here.
* We are passing or TIF in the constructor of RandomAccessFileOrArray class. We need to pass full path of TIF file as string.
* I am assuming it in “D:\” drive of windows.
* /
RandomAccessFileOrArray myTifFile = new RandomAccessFileOrArray(“D:/tiffFileName.tif”);
/*
* Now find number of pages (images) in TIF file using static method of TiffImage class. TiffImage class is from iText API.
*/
int numberOfPages = TiffImage.getNumberOfPages(myTifFile);
Document TiffToPDF = new Document();
/*
* Now use a static method getInstance() from PdfWriter class to get an instance of PdfWriter class to write data from TIF to this PDF.
* As we can see the first parameter is Document instance that we created above and second parameter is an instance of FileOutputStream.
* We are passing full path of PDF under constructor of FileOutputStream. FileOutputStream creats an stream to pdf on that path to write data in PDF file.
*/
PdfWriter.getInstance(TiffToPDF, new FileOutputStream(“D:/tiffFileName.pdf”));
// We must open the Document before writing anything to pdf.
TiffToPDF.open();
/*
* Now itterate over pages under TIF file. Fetching images one by one from TIF creates an Image object and write that Image instance to PDF Document.
*/
for(int tiffImageCounter = 1;tiffImageCounter