CyCacheUtil.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package cn.cslg.pas.common;
  2. import cn.cslg.pas.common.utils.StringUtils;
  3. import org.apache.commons.codec.binary.Base64;
  4. import org.apache.pdfbox.pdmodel.PDDocument;
  5. import org.apache.pdfbox.rendering.ImageType;
  6. import org.apache.pdfbox.rendering.PDFRenderer;
  7. import org.springframework.cache.annotation.CacheEvict;
  8. import org.springframework.cache.annotation.Cacheable;
  9. import org.springframework.stereotype.Component;
  10. import javax.imageio.ImageIO;
  11. import java.awt.image.RenderedImage;
  12. import java.io.*;
  13. /**
  14. * 缓存类,该类中定义一些用于缓存的方法
  15. *
  16. * @author chenyu
  17. * @date 2023/9/15
  18. */
  19. @Component
  20. public class CyCacheUtil implements Serializable {
  21. /**
  22. * 缓存指定专利号的说明书pdf首页的图片数据
  23. *
  24. * @param patentNo 专利号
  25. * @param pdfFile pdf文件
  26. * @return 返回该专利号的说明书pdf首页的图片数据
  27. */
  28. @Cacheable(cacheNames = "imgData", key = "#patentNo")
  29. public String getImgData(String patentNo, File pdfFile) throws IOException {
  30. //pdf转图片方式二(用依赖pdfbox)
  31. PDDocument doc = PDDocument.load(pdfFile);
  32. String newFilePath = StringUtils.getUUID() + ".pdf";
  33. File outputFile = new File(newFilePath);
  34. PDFRenderer pdfRenderer = new PDFRenderer(doc);
  35. // 提取的页码
  36. int pageNumber = 0;
  37. // 以300 dpi 读取存入 BufferedImage 对象
  38. int dpi = 300;
  39. RenderedImage buffImage = pdfRenderer.renderImageWithDPI(pageNumber, dpi, ImageType.RGB);
  40. // 将 BufferedImage 写入到 png
  41. ImageIO.write(buffImage, "png", outputFile);
  42. doc.close();
  43. ByteArrayOutputStream out = new ByteArrayOutputStream();
  44. FileInputStream in = new FileInputStream(outputFile);
  45. int bytesRead;
  46. byte[] buffer = new byte[8192];
  47. //读取pdf首页临时文件
  48. while ((bytesRead = in.read(buffer)) != -1) {
  49. out.write(buffer, 0, bytesRead);
  50. }
  51. //关闭读取流
  52. in.close();
  53. byte[] bytes = out.toByteArray();
  54. String imgData = Base64.encodeBase64String(bytes);
  55. //关闭写出流
  56. out.close();
  57. //最后记得删除pdf首页的临时文件
  58. new File(newFilePath).delete();
  59. return imgData;
  60. }
  61. @CacheEvict(cacheNames = "imgData", key = "#patentNo")
  62. public void deleteImgData(String patentNo) {
  63. //在名称为imgData的缓存中删除key为该专利号的缓存内容(即删除该专利号的说明书pdf首页的图片数据)
  64. }
  65. }