package sample;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.kernel.pdf.xobject.PdfImageXObject;
import com.itextpdf.layout.element.Image;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Locale;
import java.util.function.Function;
/**
* @author huidongma
*/
public class PdfCompress {
/**
* @param srcDir 源 文件/文件夹
* @param targetDir 目标文件夹
* @param factor 压缩因子 取值0-1
* @throws IOException
*/
protected static void compress(String srcDir, String targetDir, float factor, Function<String, String> log) throws IOException {
log.apply("处理进度: ");
PdfCompress pdfCompress = new PdfCompress();
File file = new File(srcDir);
if (file.isFile()) {
if(file.getName().toLowerCase(Locale.ROOT).endsWith(".pdf")){
file.createNewFile();
log.apply("----------");
log.apply("源文件地址:" + file.getPath());
pdfCompress.manipulatePdf(targetDir, srcDir, factor,log);
}
else{
log.apply("仅支持pdf文件压缩");
}
} else {
file.mkdirs();
log.apply("源文件夹地址:" + file.getPath());
File[] files = file.listFiles((dir, name) -> name.toLowerCase(Locale.ROOT).endsWith(".pdf"));
int total = files.length;
for (int i = 0; i < files.length; i++) {
log.apply("----------");
log.apply(file.getPath());
pdfCompress.manipulatePdf(targetDir, files[i].getPath(), factor,log);
}
}
}
private String createSrcFileName(String target, String src) {
return target + File.separator + new File(src).getName();
}
protected void manipulatePdf(String target, String src, float factor, Function<String, String> log) throws IOException {
new Thread(() -> {
String targetUrl = this.createSrcFileName(target, src);
PdfDocument pdfDoc =null;
boolean isSuccess = false;
try {
pdfDoc =new PdfDocument(new PdfReader(src), new PdfWriter(targetUrl));
int pages = pdfDoc.getNumberOfPages();
log.apply("共计" + pages + "页");
for (int i = 0; i < pages; i++) {
PdfPage page = pdfDoc.getPage(i + 1);
PdfDictionary pageDict = page.getPdfObject();
PdfDictionary resources = pageDict.getAsDictionary(PdfName.Resources);
PdfDictionary xObjects = resources.getAsDictionary(PdfName.XObject);
PdfName imgRef = xObjects.keySet().iterator().next();
PdfStream stream = xObjects.getAsStream(imgRef);
Image img = convertToBlackAndWhite(new PdfImageXObject(stream), factor);
xObjects.put(imgRef, img.getXObject().getPdfObject());
log.apply(src + "###第" + (i + 1) + "页完成******");
}
isSuccess = true;
} catch (Exception ignored) {
} finally {
if(pdfDoc!=null) {
pdfDoc.close();
}
}
//针对非纯图片的pdf,直接拷贝过去
if (!isSuccess) {
if (Files.exists(Paths.get(targetUrl))){
log.apply("开始删除:"+targetUrl);
try{
Files.delete(Paths.get(targetUrl));
}
catch (Exception exception){
log.apply("删除失败:"+targetUrl);
}
}
try {
Files.copy(Paths.get(src), Paths.get(targetUrl), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); //如果dest文件存在就会报错
} catch (IOException e) {
e.printStackTrace();
}
log.apply("拷贝完成");
}
}).start();
}
private static Image convertToBlackAndWhite(PdfImageXObject image, float factor) throws IOException {
BufferedImage bi = image.getBufferedImage();
int width = (int) (bi.getWidth() * factor);
int height = (int) (bi.getHeight() * factor);
BufferedImage newBi = new BufferedImage(width, height, image.getBufferedImage().getType());
AffineTransform at = AffineTransform.getScaleInstance(factor, factor);
Graphics2D g = newBi.createGraphics();
g.drawRenderedImage(bi, at);
ByteArrayOutputStream imgBytes = new ByteArrayOutputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(newBi, image.identifyImageType().name(), baos);
return new Image(ImageDataFactory.create(baos.toByteArray()));
}
}
没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
Java批量压缩图片格式的PDF档(源码Demo) 适用:仅针对纯图片型的pdf(类似扫描版)进行压缩 原理:压缩图片然后再另存成新文件 实例如下: ├── META-INF │ └── MANIFEST.MF ├── pom.xml └── src ├── main │ ├── java │ │ ├── META-INF │ │ │ └── MANIFEST.MF │ │ ├── Main.java │ │ └── sample │ │ ├── Controller.java │ │ └── PdfCompress.java │ └── resources │ └── sample.fxml └── test └── java
资源推荐
资源详情
资源评论
收起资源包目录
Java批量压缩图片格式的PDF档(源码Demo).zip (23个子文件)
Java批量压缩图片格式的PDF档(源码Demo)
itextdemo
pom.xml 1KB
META-INF
MANIFEST.MF 43B
.DS_Store 6KB
src
test
java
main
resources
.DS_Store 8KB
sample.fxml 2KB
.DS_Store 6KB
java
META-INF
MANIFEST.MF 43B
sample
Controller.java 3KB
PdfCompress.java 5KB
.DS_Store 6KB
Main.java 583B
.idea
uiDesigner.xml 9KB
misc.xml 531B
jarRepositories.xml 845B
compiler.xml 530B
workspace.xml 7KB
.gitignore 176B
artifacts
itextdemo.xml 695B
inspectionProfiles
Project_Default.xml 1KB
__MACOSX
itextdemo
._.DS_Store 120B
src
main
._.DS_Store 120B
resources
._.DS_Store 120B
java
._.DS_Store 120B
共 23 条
- 1
资源评论
- m0_614225592023-12-14非常有用的资源,有一定的参考价值,受益匪浅,值得下载。
解决方案专家
- 粉丝: 27
- 资源: 56
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功