package myApplication;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.RandomAccessFileOrArray;
import com.itextpdf.text.pdf.codec.TiffImage;
public class TifsToPdf {
// 将多个tif文件合并成一个pdf文件
public void tifToPdf(String arr[], String sFilePdf) {
//获取TIF文件路径
String sNewfile = sFilePdf.substring(0, sFilePdf.lastIndexOf("\\"));
System.out.println(sNewfile);
File _toFile = new File(sNewfile);
if (!_toFile.exists()) {// 如果pdf目录不存在新建目录
_toFile.mkdirs();
}
// 创建一个文档对象
Document doc = new Document(PageSize.LETTER, 0, 0, 0, 0);
int pages = 0;
int comps = 0;
String sFileTif = "";
try {
// 定义输出位置并把文档对象装入输出对象中
PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(
sFilePdf));
// 打开文档对象
doc.open();
for (int i = 0; i < arr.length; i++) {
sFileTif = arr[i];
PdfContentByte cb = writer.getDirectContent();
RandomAccessFileOrArray ra = null;
try {
ra = new RandomAccessFileOrArray(sFileTif);
comps = TiffImage.getNumberOfPages(ra);
} catch (Throwable e) {
System.out.println("Exception in " + sFileTif + " "
+ e.getMessage());
}
// System.out.println("Processing: " + sFileTif);
for (int c = 0; c < comps; ++c) {
try {
Image img = TiffImage.getTiffImage(ra, c + 1);
if (img != null) {
// System.out.println("page " + (c + 1));
img.scalePercent(7200f / img.getDpiX(),
7200f / img.getDpiY());
doc.setPageSize(new Rectangle(img.getScaledWidth(),
img.getScaledHeight()));
img.setAbsolutePosition(0, 0);
cb.addImage(img);
doc.newPage();
++pages;
}
} catch (Throwable e) {
System.out.println("Exception " + sFileTif + " page "
+ (c + 1) + " " + e.getMessage());
}
}
ra.close();// 关闭
}
// 关闭文档对象,释放资源
doc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
TIF 文件转换成PDF文件
最新推荐文章于 2024-07-23 14:18:34 发布