123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- package cn.cslg.pas.common;
- import cn.cslg.pas.common.utils.StringUtils;
- import org.apache.commons.codec.binary.Base64;
- import org.apache.pdfbox.pdmodel.PDDocument;
- import org.apache.pdfbox.rendering.ImageType;
- import org.apache.pdfbox.rendering.PDFRenderer;
- import org.springframework.cache.annotation.CacheEvict;
- import org.springframework.cache.annotation.Cacheable;
- import org.springframework.stereotype.Component;
- import javax.imageio.ImageIO;
- import java.awt.image.RenderedImage;
- import java.io.*;
- /**
- * 缓存类,该类中定义一些用于缓存的方法
- *
- * @author chenyu
- * @date 2023/9/15
- */
- @Component
- public class CyCacheUtil implements Serializable {
- /**
- * 缓存指定专利号的说明书pdf首页的图片数据
- *
- * @param patentNo 专利号
- * @param pdfFile pdf文件
- * @return 返回该专利号的说明书pdf首页的图片数据
- */
- @Cacheable(cacheNames = "imgData", key = "#patentNo")
- public String getImgData(String patentNo, File pdfFile) throws IOException {
- //pdf转图片方式二(用依赖pdfbox)
- PDDocument doc = PDDocument.load(pdfFile);
- String newFilePath = StringUtils.getUUID() + ".pdf";
- File outputFile = new File(newFilePath);
- PDFRenderer pdfRenderer = new PDFRenderer(doc);
- // 提取的页码
- int pageNumber = 0;
- // 以300 dpi 读取存入 BufferedImage 对象
- int dpi = 300;
- RenderedImage buffImage = pdfRenderer.renderImageWithDPI(pageNumber, dpi, ImageType.RGB);
- // 将 BufferedImage 写入到 png
- ImageIO.write(buffImage, "png", outputFile);
- doc.close();
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- FileInputStream in = new FileInputStream(outputFile);
- int bytesRead;
- byte[] buffer = new byte[8192];
- //读取pdf首页临时文件
- while ((bytesRead = in.read(buffer)) != -1) {
- out.write(buffer, 0, bytesRead);
- }
- //关闭读取流
- in.close();
- byte[] bytes = out.toByteArray();
- String imgData = Base64.encodeBase64String(bytes);
- //关闭写出流
- out.close();
- //最后记得删除pdf首页的临时文件
- new File(newFilePath).delete();
- return imgData;
- }
- @CacheEvict(cacheNames = "imgData", key = "#patentNo")
- public void deleteImgData(String patentNo) {
- //在名称为imgData的缓存中删除key为该专利号的缓存内容(即删除该专利号的说明书pdf首页的图片数据)
- }
- }
|