<!-- PDF操作,itext7全家桶 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>7.1.15</version>
<type>pom</type>
</dependency>
package org.example;
import com.itextpdf.kernel.pdf.*;
import com.itextpdf.kernel.pdf.xobject.PdfImageXObject;
import javax.imageio.ImageIO;
import java.awt.;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.;
public class Main {
public static void main(String[] args) throws IOException {
PdfName key = new PdfName("ITXT_SpecialId");
PdfName value = new PdfName("123456789");
// 读取pdf文件
PdfReader reader = null;
try {
reader = new PdfReader(new FileInputStream(new File("E:\\mqdemo\\paixu\\src\\main\\resources\\static\\2024作品集 .pdf")));
} catch (IOException e) {
throw new RuntimeException(e);
}
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
PdfDocument pdfDocument = new PdfDocument(reader,new PdfWriter(swapStream));
long n = reader.getLastXref();
PdfObject object;
PdfStream stream;
//查找图像并操作图像流
for (int i = 0; i < n; i++) {
object = pdfDocument.getPdfObject(i);
if (object == null || !object.isStream())
continue;
stream = (PdfStream) object;
PdfObject pdfsubtype = stream.get(PdfName.Subtype);
if (pdfsubtype != null && pdfsubtype.toString().equals(PdfName.Image.toString())) {
PdfImageXObject image = new PdfImageXObject(stream);
int i1 = image.getPdfObject().getAsNumber(PdfName.BitsPerComponent).intValue();
//小于8的都跳过,BitsPerComponent=4是提示报错The color depth BitsPerComponent的值 is not supported
//this.bpc != 8 ImagePdfBytesInfo类下decodeTiffAndPngBytes
//当位图不等于8时,直接跳过
if (i1 != 8) {
continue;
}
BufferedImage bi = image.getBufferedImage();
if (bi == null) continue;
int width = (int) (bi.getWidth() * 0.7f);
int height = (int) (bi.getHeight() * 0.7f);
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
AffineTransform at = AffineTransform.getScaleInstance(0.7f, 0.7f);
Graphics2D g = img.createGraphics();
g.drawRenderedImage(bi, at);
ByteArrayOutputStream imgBytes = new ByteArrayOutputStream();
//标记此处,后面会修改
ImageIO.write(img, "JPG", imgBytes);
stream.clear();
stream.setData(imgBytes.toByteArray(), false);
stream.put(PdfName.Type, PdfName.XObject);
stream.put(PdfName.Subtype, PdfName.Image);
stream.put(key, value);
stream.put(PdfName.Filter, PdfName.DCTDecode);
stream.put(PdfName.Width, new PdfNumber(width));
stream.put(PdfName.Height, new PdfNumber(height));
stream.put(PdfName.BitsPerComponent, new PdfNumber(8));
stream.put(PdfName.ColorSpace, PdfName.DeviceRGB);
}
}
//将数据写入到输出流中
pdfDocument.close();
reader.close();
System.out.println("pdf压缩完成, 文件大小="+ swapStream.size());
FileOutputStream fileOut = new FileOutputStream("outputFile.pdf");
fileOut.write(swapStream.toByteArray());
}
}