Last active
September 18, 2017 15:24
-
-
Save szahn/6454209 to your computer and use it in GitHub Desktop.
Converting a tiff to pdf using iText.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?