导包:
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.io.RandomAccessSource;
import com.itextpdf.text.io.RandomAccessSourceFactory;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.RandomAccessFileOrArray;
import com.itextpdf.text.pdf.codec.TiffImage;
方法:
public static int tifToPdf(String inputFile, String outputFile){
int status = -1;
Document tifftoPDF = new Document();
Image tempImage = null;
RandomAccessSource ras = null;
try{
RandomAccessSourceFactory r = new RandomAccessSourceFactory();
ras = r.createSource(new FileInputStream(inputFile));
//Read the Tiff File
RandomAccessFileOrArray myTiffFile=new RandomAccessFileOrArray(ras);
//Find number of images in Tiff file
int numberOfPages = TiffImage.getNumberOfPages(myTiffFile);
System.out.println("Number of Images in Tiff File" + numberOfPages);
PdfWriter.getInstance(tifftoPDF, new FileOutputStream(outputFile));
tifftoPDF.open();
Rectangle rectangle = tifftoPDF.getPageSize();
System.out.println(rectangle.getHeight());
//Run a for loop to extract images from Tiff file
//into a Image object and add to PDF recursively
for(int i = 1; i <= numberOfPages; i ++){
tempImage = TiffImage.getTiffImage(myTiffFile, i);
tempImage.scaleAbsolute(rectangle.getWidth(), rectangle.getHeight());
tifftoPDF.newPage();//设置大小后,创建新的一页,否则会出现,首页尺寸格式错误
tifftoPDF.add(tempImage);
}
status = 1;
System.out.println("Tiff to PDF Conversion in Java Completed" );
}catch(Exception e){
status = -1;
}finally{
tifftoPDF.close();
if(ras != null){
try {
ras.close();
} catch (IOException e) {
status = -1;
}
}
}
return status;
}