package image;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* 功能1:图片转PDF
* 功能2:删除图片
* 注意:转换pdf文件上限约20~30万
*/
public class ImgToPDF {
private static int count = 0;
private static final List<String> IMAGE_EXTENSIONS = Arrays.asList(".tif",".jpg", ".jpeg", ".png", ".gif", ".bmp"); // 支持的图片格式
public static void main(String[] args) throws Exception {
System.setProperty("itext.licensekey.disableagplwarning", "true");//个人用户引入itextpdf临时禁止不需要的提示。
标签:java,file,new,static,File,import,PDF,图片 From: https://www.cnblogs.com/lt3232696/p/18586607
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
count = 0;
System.out.println("任务开始:" + dateFormat.format(new Date()));
String directoryPath = "F:\\数据转换\\11\\two";
// 1、将子目录下所有图片转成PDF
List<File> imageFiles = findImageFiles(directoryPath);
int executors = Runtime.getRuntime().availableProcessors();
int executorSize = 2 * executors;
ExecutorService executor = Executors.newFixedThreadPool(executorSize);
threadPool(imageFiles, executor);
//2、删除子目录所有图片
//findImagesInSubdirectories(directoryPath);
System.out.println("任务结束:" + dateFormat.format(new Date()));
}
public static void threadPool(List<File> excelFilePaths, ExecutorService executor) {
List<Callable<Void>> tasks = new ArrayList<>();
// 将每个Excel文件的转换任务添加到列表中
for (File file : excelFilePaths) {
tasks.add(() -> {
// 在这里实现img到PDF的转换逻辑
boolean result = generatePdfFile(file);
if (result) {
setFileRecord("\n\t文件已转换成功:" + file.getAbsolutePath() + ",已转"+count+"个");
} else {
setFileRecord("\n\t文件已转换失败:" + file.getAbsolutePath() + ",已转"+count+"个");
}
return null;
});
}
try {
// 提交所有任务到线程池,并等待它们完成
executor.invokeAll(tasks);
} catch (InterruptedException e) {
System.out.println("Interrupted while waiting for tasks to complete");
Thread.currentThread().interrupt(); // 重新设置中断标志
} finally {
shutdownExecutor(executor);
}
}
private static void shutdownExecutor(ExecutorService executor) {
executor.shutdown();
try {
if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
executor.shutdownNow();
if (!executor.awaitTermination(60, TimeUnit.SECONDS))
System.out.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
executor.shutdownNow();
Thread.currentThread().interrupt(); // 重新设置中断标志
}
}
/**
* 将图片转换为PDF文件
*/
private static boolean generatePdfFile(File file) throws Exception {
try {
String fileName = file.getAbsolutePath();
String pdfFileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".pdf";
Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
PdfWriter.getInstance(doc, new FileOutputStream(pdfFileName));
doc.open();
doc.newPage();
Image image = Image.getInstance(file.getPath());
float height = image.getHeight();
float width = image.getWidth();
int percent = getPercent(height, width);
image.setAlignment(Image.MIDDLE);
image.scalePercent(percent);
doc.add(image);
doc.close();
File pdfFile = new File(pdfFileName);
count++;
System.out.println("File created: " + pdfFile.getAbsolutePath() + ",已转"+count+"个");
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 等比压缩,获取压缩百分比
*
* @param height 图片的高度
* @param weight 图片的宽度
* @return 压缩百分比
*/
private static int getPercent(float height, float weight) {
float percent = 0.0F;
if (height > weight) {
percent = PageSize.A4.getHeight() / height * 100;
} else {
percent = PageSize.A4.getWidth() / weight * 100;
}
return Math.round(percent);
}
public static void findImagesInSubdirectories(String rootPath) throws Exception {
File rootDirectory = new File(rootPath);
File[] subDirectories = rootDirectory.listFiles(File::isDirectory); // 只获取子目录
if (subDirectories != null) {
for (File dir : subDirectories) {
searchForImages(dir);
}
}
}
private static void searchForImages(File directory) throws Exception {
File[] files = directory.listFiles((dir, name) -> {
String lowerCaseName = name.toLowerCase();
return IMAGE_EXTENSIONS.stream()
.anyMatch(lowerCaseName::endsWith);
});
if(files != null){
processFiles(files);
}
}
public static List<File> findImageFiles(String directoryPath) {
List<File> imageFiles = new ArrayList<>();
File directory = new File(directoryPath);
if (directory.exists() && directory.isDirectory()) {
File[] files = directory.listFiles();
if (files!= null) {
for (File file : files) {
if (file.isDirectory()) {
// 递归查找子目录中的图片文件
imageFiles.addAll(findImageFiles(file.getAbsolutePath()));
} else {
String fileName = file.getName();
int start = fileName.lastIndexOf(".");
int end = fileName.length();
String fileType = fileName.substring(start, end).toLowerCase();
if (IMAGE_EXTENSIONS.contains(fileType)) {
imageFiles.add(file);
}
}
}
}
}
return imageFiles;
}
public static void setFileRecord(String content){
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
// 创建FileWriter对象,第二个参数true表示追加模式
FileWriter writer = new FileWriter("imgToPdf"+ sdf.format(new Date())+".txt", true);
//String content = "这是要追加到txt文件中的新内容";
writer.write(content);
writer.close();
//System.out.println("内容已成功追加到文件中");
} catch (IOException e) {
e.printStackTrace();
}
}
}