使用java itext压缩文件中的图片

使用java itext压缩文件中的图片


import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PRStream;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfNumber;
import com.itextpdf.text.pdf.PdfObject;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.parser.PdfImageObject;

/**
 * @version: V1.0
 * @author haoren
 * @ClassName: CompressPDFImage
 * @Description: 压缩pdf中图片
 * @date 2023年4月25日  上午9:13:08
 *
 */
public class CompressPDFImage {
    
   
      public static float FACTOR = 0.5f;

      /**
       * 
       * @author: haoren
       * @methodsName: manipulatePdf
       * @description: 对pdf中的图片进行压缩处理
       * @date 2023年4月25日  下午3:37:28
       * @param src 原文件路径
       * @param dest 压缩后新文件路径
       * @throws IOException
       * @throws DocumentException
       * @return: void
       * @throws:
       */
      public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
          PdfName key = new PdfName("ITXT_SpecialId");
          PdfName value = new PdfName("123456789");
          // 读取传过来的文件
          PdfReader reader = new PdfReader(src);
          int n = reader.getXrefSize();
          PdfObject object;
          PRStream stream;
          // Look for image and manipulate image stream
          for (int i = 0; i < n; i++) {
              object = reader.getPdfObject(i);
              if (object == null || !object.isStream())
                  continue;
              stream = (PRStream)object;
              // if (value.equals(stream.get(key))) {
              PdfObject pdfsubtype = stream.get(PdfName.SUBTYPE);
              if (pdfsubtype != null && pdfsubtype.toString().equals(PdfName.IMAGE.toString())) {
                  PdfImageObject image = new PdfImageObject(stream);
                  BufferedImage bi = image.getBufferedImage();
                  if (bi == null) continue;
                  int width = (int)(bi.getWidth() * FACTOR);
                  int height = (int)(bi.getHeight() * FACTOR);
                  BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                  AffineTransform at = AffineTransform.getScaleInstance(FACTOR, FACTOR);
                  Graphics2D g = img.createGraphics();
                  g.drawRenderedImage(bi, at);
                  ByteArrayOutputStream imgBytes = new ByteArrayOutputStream();
                  ImageIO.write(img, "JPG", imgBytes);
                  stream.clear();
                  stream.setData(imgBytes.toByteArray(), false, PRStream.BEST_COMPRESSION);
                  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);
              }
          }
          // Save altered PDF
          PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
          stamper.close();
          reader.close();
      }

      /**
       * 
       * @author: haoren
       * @methodsName: CompressImg
       * @description: 压缩pdf中图片
       * @date 2023年4月25日  下午3:37:07
       * @param value
       * @param value1
       * @return
       * @throws IOException
       * @throws DocumentException
       * @return: String
       * @throws:
       */
      public static String CompressImg(String value,String value1) throws IOException, DocumentException {
          String fileName = UuidUtil.get32UUID();//生成临时附件名称
          String fileDataPhysicalPath = PropertiesUtil.getGlobalValueByKey("FileDataPhysicalPath");//物理地址
          String path = "imgFile/fjyl/"+fileName+".pdf";//附件路径
          String urlpath = fileDataPhysicalPath+path;//存储的完成地址
          File file = new File(value);
          PdfReader pdfReader = new PdfReader(new FileInputStream(file));
          int pages = pdfReader.getNumberOfPages();//获取pdf总页数
          if (pages<=2) {
              int size = getFileSize2(file);//获取文件大小
              if (size>=20000000) {
                  new CompressPDFImage().manipulatePdf(value, urlpath);
                  return path;
              } else {
                  return value1;
              }
          } else {
              return value1;
          }
              
      }
      
      /**
       * 
       * @author: haoren
       * @methodsName: getFileSize2
       * @description: 根据java.io.*的流获取文件大小
       * @date 2023年4月25日  下午3:36:38
       * @param file
       * @return
       * @return: int
       * @throws:
       */
      public static int getFileSize2(File file){
          FileInputStream fis  = null;
          int size = 0;
          try {
              if(file.exists() && file.isFile()){
                  fis = new FileInputStream(file);
                  size = fis.available();
              }
          } catch (Exception e) {
              e.printStackTrace();
          }finally{
              if(null!=fis){
                  try {
                      fis.close();
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
              }
          }
        return size;
      }
      
}

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值