工具类功能 : tif 转为 pdf
输入 : tif图片所在的目录
输入 : 生成pdfbao保存的目录
需要的依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
ps : 从csdn上花积分下载了两个都不好用只能自己整理
package com.zkrt.tezt.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.junit.Test;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
/**
* tif 图片转 pdf
* @author QiuYue
* 2019/8/16
*/
public class Tif2pdf {
@Test
public void mtif() {
//tif所在的目录
String tifPath = "D:\\resources\\tif";
//pdf保存到的目录
String pdfPath = "D:\\resources\\pdf\\";
Tif2pdf.traverseFolder(tifPath, pdfPath);
}
/**
* 使用递归遍历path下的所有文件夹和文件找到tif文件转为pdf
*
* @param path tif所在文件目录
* @param pdfPath pdf保存的路径
*/
public static void traverseFolder(String path, String pdfPath) {
File file = new File(path);
if (file.exists()) {
File[] files = file.listFiles();
if (null == files || files.length == 0) {
System.out.println("文件夹是空的!");
return;
} else {
for (File file2 : files) {
if (file2.isDirectory()) {
System.out.println("目录文件不进行转换:" + file2.getAbsolutePath());
traverseFolder(file2.getAbsolutePath(), pdfPath);
} else if (file2.getAbsolutePath().endsWith(".tif")) {
System.out.println("文件转换:" + file2.getAbsolutePath());
Tif2pdf.tifToPdf(file2.getAbsolutePath(), pdfPath);
} else {
System.out.println("不是tif文件不转化 :" + file2.getAbsolutePath());
}
}
}
} else {
System.out.println("文件不存在!");
}
}
/**
*
* @param tifPath tif保存的路径
* @param pdfPath pdf保存的路径
*/
public static void tifToPdf(String tifPath, String pdfPath) {
//如果文件不存在就创建
File _toFile = new File(pdfPath);
if (!_toFile.exists()) {
_toFile.mkdirs();
}
// 创建一个文档对象
Document doc = new Document(PageSize.LETTER, 0, 0, 0, 0);
try {
File file = new File(tifPath);
int random = (int) (Math.random() * 100);
// 设置文件名 : 原文件名 + random + "_" + ".pdf"
String newName = file.getName().substring(0, file.getName().lastIndexOf(".tif")) + "_" + random + ".pdf";
// 定义输出位置并把文档对象装入输出对象中
PdfWriter.getInstance(doc, new FileOutputStream(pdfPath + newName));
// 打开文档对象
doc.open();
Image img = Image.getInstance(tifPath);
doc.add(img);
doc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}