java实现将pdf变成一张图片在页面显示

1.需求:

由于pdf传输到前台显示不了,因此要在后台将pdf转成图片,然后输出到页面上

使用的是pdfbox

2.在pom.xml中添加如下依赖:

<dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>fontbox</artifactId>
            <version>2.0.9</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.9</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>

2.接口

// 设定输出的类型
  private static final String JPG = "image/jpeg;charset=GB2312";

public static final float DEFAULT_DPI = 105;

/**
   * 查看合同附件
   * 
   * @param fileName
   * @param request
   * @param response
   * @throws Exception
   */
  @RequestMapping(value = { "/viewPdf/{fileName:.+}" }, method = RequestMethod.GET)
  public void viewPdf(@PathVariable String fileName, final HttpServletResponse request,
      final HttpServletResponse response) throws Exception {
    // String ext = StringUtils.substringAfterLast(fileName, ".");
    String path = saveUploadContractAttachPath + fileName;
    logger.debug(path);
    File file = new File(path);
    if (!file.exists()) {
      return;
    }
    response.reset(); // 非常重要
    response.setContentType(JPG);
    // if ("pdf".equalsIgnoreCase(ext)) {
    // response.setContentType(PDF);
    // }
    OutputStream out = response.getOutputStream();
    // IOUtils.write(FileUtils.readFileToByteArray(file), out);
    // 图像合并使用参数
    int width = 0; // 总宽度
    int[] singleImgRGB; // 保存一张图片中的RGB数据
    int shiftHeight = 0;
    BufferedImage imageResult = null;// 保存每张图片的像素值
    PDDocument doc = PDDocument.load(file);
    PDFRenderer renderer = new PDFRenderer(doc);
    int pageCount = doc.getNumberOfPages();
    // BufferedImage image = null;
    for (int i = 0, len = pageCount; i < pageCount; i++) {
      // image = renderer.renderImageWithDPI(i, 144);
      // ImageIO.write(image, "jpg", file);
      BufferedImage image = renderer.renderImageWithDPI(i, DEFAULT_DPI, ImageType.RGB);
      int imageHeight = image.getHeight();
      int imageWidth = image.getWidth();
      if (i == 0) {// 计算高度和偏移量
        width = imageWidth;// 使用第一张图片宽度;
        // 保存每页图片的像素值
        imageResult = new BufferedImage(width, imageHeight * len, BufferedImage.TYPE_INT_RGB);
      } else {
        shiftHeight += imageHeight; // 计算偏移高度
      }
      singleImgRGB = image.getRGB(0, 0, width, imageHeight, null, 0, width);
      imageResult.setRGB(0, shiftHeight, width, imageHeight, singleImgRGB, 0, width); // 写入流中
    }
    doc.close();
    ImageIO.write(imageResult, "jpg", out);// 写图片

  }

posted @   小草1234  阅读(1139)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示