Skip to content

Instantly share code, notes, and snippets.

@szahn
Last active September 18, 2017 15:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save szahn/6454209 to your computer and use it in GitHub Desktop.
Save szahn/6454209 to your computer and use it in GitHub Desktop.
Converting a tiff to pdf using iText.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.io.FileChannelRandomAccessSource;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.RandomAccessFileOrArray;
import com.itextpdf.text.pdf.codec.TiffImage;
public class TiffToPDFConverter {
public boolean Convert(List<String> files, String pdfFilename)
{
boolean converted = false;
try {
Document pdf = new Document();
PdfWriter.getInstance(pdf, new FileOutputStream(pdfFilename));
pdf.open();
int filesAdded = 0;
for(String tiffFilename : files)
{
try
{
FileChannelRandomAccessSource source = new FileChannelRandomAccessSource(
new FileInputStream(tiffFilename).getChannel());
RandomAccessFileOrArray file = new RandomAccessFileOrArray(source);
int pages = TiffImage.getNumberOfPages(file);
for (int page = 1; page <= pages; page++){
Image img = TiffImage.getTiffImage(file, page);
if (pdf.add(img)) filesAdded++;
}
} catch (IOException ex) {
throw ex;
}
}
pdf.close();
converted = IOHelper.DoesFileExist(pdfFilename)
&& filesAdded == files.size();
} catch (FileNotFoundException | DocumentException e1) {
throw e1;
}
return converted;
}
}
@husmx
Copy link

husmx commented Sep 18, 2017

Great dude! I have some days trying to make a conversion from tiff to PDF (just for fun and learn) using a java 3rd party with mulesoft and I'm getting error in the method converted = IOHelper.DoesFileExist(pdfFilename), is undefined for the type IOHelper... and I DON'T HAVE ANY IDEA how solve it (I'm not a really programer, but that's why I'm learning). Any recommendation?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment