java将Pdf转为一张图片

jar包:

        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>fontbox</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>4.1.19</version>
        </dependency>

代码参考一:
亲测有用!虽然有警告信息,但还是能得到结果

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

public class PdfchangeOneImg {

  /**
   * @Description pdf转成一张图片
   * @author zdl       
   * @created 2017年1月4日 下午1:54:13     
   * @param pdfFile
   * @param outpath
   */
  private static void pdf2multiImage(String pdfFile, String outpath) {  
        try {  
            InputStream is = new FileInputStream(pdfFile);  
 PDDocument pdf = PDDocument.load(is);  
            int actSize = pdf.getNumberOfPages(); 
            List<BufferedImage> piclist = new ArrayList<BufferedImage>();  
            for (int i = 0; i < actSize; i++) {
            BufferedImage  image = new PDFRenderer(pdf).renderImageWithDPI(i,130,ImageType.RGB);  
                piclist.add(image); 
            }  
            yPic(piclist, outpath);  
            is.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
          
         
          
          /** 
        * 将宽度相同的图片,竖向追加在一起 ##注意:宽度必须相同 
        *  
        * @param piclist 
        *            文件流数组 
        * @param outPath 
        *            输出路径 
        */ 
          public static void yPic(List<BufferedImage> piclist, String outPath) {// 纵向处理图片  
        if (piclist == null || piclist.size() <= 0) {  
            System.out.println("图片数组为空!");  
            return;  
        }  
        try {  
            int height = 0, // 总高度  
            width = 0, // 总宽度  
            _height = 0, // 临时的高度 , 或保存偏移高度  
            __height = 0, // 临时的高度,主要保存每个高度  
            picNum = piclist.size();// 图片的数量  
            int[] heightArray = new int[picNum]; // 保存每个文件的高度  
            BufferedImage buffer = null; // 保存图片流  
            List<int[]> imgRGB = new ArrayList<int[]>(); // 保存所有的图片的RGB  
            int[] _imgRGB; // 保存一张图片中的RGB数据  
            for (int i = 0; i < picNum; i++) {  
                buffer = piclist.get(i);  
                heightArray[i] = _height = buffer.getHeight();// 图片高度  
                if (i == 0) {  
                    width = buffer.getWidth();// 图片宽度  
                }  
                height += _height; // 获取总高度  
                _imgRGB = new int[width * _height];// 从图片中读取RGB  
                _imgRGB = buffer.getRGB(0, 0, width, _height, _imgRGB, 0, width);  
                imgRGB.add(_imgRGB);  
            }  
            _height = 0; // 设置偏移高度为0  
            // 生成新图片  
            BufferedImage imageResult = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
            for (int i = 0; i < picNum; i++) {  
                __height = heightArray[i];  
                if (i != 0) _height += __height; // 计算偏移高度  
                imageResult.setRGB(0, _height, width, __height, imgRGB.get(i), 0, width); // 写入流中  
            }  
            File outFile = new File(outPath);  
            ImageIO.write(imageResult, "jpg", outFile);// 写图片  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
          
          public static void main(String[] args) {
    pdf2multiImage("D:\\Documents\\Downloads\\2016-12-29.pdf", "D:\\Documents\\Downloads\\2016-12-29.jpg"); 
  }
}

代码参考二:
这个没测过不知道

@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);// 写图片

  }

转自:

https://blog.csdn.net/xiao297328/article/details/83786778

https://blog.csdn.net/daolin1/article/details/54018514

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值