pdf转图片的两种方式(java)

    最近在工作中遇到业务需要把pdf转成图片供前台预览,在网上查了一些方法,有的能用,有的缺东西,时间又比较急,没时间去看。在这里我整理了两种亲测可行的方式,节省大家时间带备忘

1.pdf按页数转成多张PNG

/**
 * @description pdf文件逐页转成png图片
 **/
public class pdfToPng {

//测试方法
//    public static void main(String[] args) throws Exception{
//        pdf2Image("E:\\123.pdf", "E:\\", 300);
//    }

    /***
     * PDF文件转PNG图片,全部页数
     *
     * @param PdfFilePath pdf完整路径
     * @param dpi dpi越大转换后越清晰,相对转换速度越慢
     * @return
     */
    public static void pdf2Image(String PdfFilePath, String dstImgFolder, int dpi) throws Exception {
        File file = new File(PdfFilePath);
        PDDocument pdDocument;
        try {
            String imgPDFPath = file.getParent();
            int dot = file.getName().lastIndexOf('.');
            String imagePDFName = file.getName().substring(0, dot); // 获取图片文件名
            String imgFolderPath = null;
            if (dstImgFolder.equals("")) {
                imgFolderPath = imgPDFPath + File.separator + imagePDFName;// 获取图片存放的文件夹路径
            } else {
                imgFolderPath = dstImgFolder + File.separator + imagePDFName;
            }

            if (createDirectory(imgFolderPath)) {

                pdDocument = PDDocument.load(file);
                PDFRenderer renderer = new PDFRenderer(pdDocument);
                /* dpi越大转换后越清晰,相对转换速度越慢 */
                PdfReader reader = new PdfReader(PdfFilePath);
                int pages = reader.getNumberOfPages();
                StringBuffer imgFilePath = null;
                for (int i = 0; i < pages; i++) {
                    String imgFilePathPrefix = imgFolderPath + File.separator + imagePDFName;
                    imgFilePath = new StringBuffer();
                    imgFilePath.append(imgFilePathPrefix);
                    imgFilePath.append("_");
                    imgFilePath.append(String.valueOf(i + 1));
                    imgFilePath.append(".png");
                    File dstFile = new File(imgFilePath.toString());
                    BufferedImage image = renderer.renderImageWithDPI(i, dpi);
                    ImageIO.write(image, "png", dstFile);
                }
                System.out.println("PDF文档转PNG图片成功!");

            } else {
                System.out.println("PDF文档转PNG图片失败:" + "创建" + imgFolderPath + "失败");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static boolean createDirectory(String folder) {
        File dir = new File(folder);
        if (dir.exists()) {
            return true;
        } else {
            return dir.mkdirs();
        }
    }
}

2.pdf文件转成一张JPG

/**
 * @description pdf文件转成一张jpg图片
 **/
public class pdfTojpg {

//测试方法

//    public static void main(String[] args) throws Exception{
//        File file = new File("E:\\123.pdf");
//        InputStream input = new FileInputStream(file);
//
//        useStream(input,"E:\\123.jpg");
//    }


    public static void useStream(InputStream is, String outpath) throws Exception {
        try {
            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, 100,
                        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();
        }
    }
}
 

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用 iText 和 Java Advanced Imaging (JAI) 这两个库来实现将 PDF 换为图片后再换回 PDF 并压缩的过程。iText 库可用于读取和写入 PDF 文档,而 JAI 库可用于处理图像。首先,使用 iText 读取 PDF 文档并将其换为图像,然后使用 JAI 库对图像进行处理和压缩。最后,使用 iText 将处理后的图像写入新的 PDF 文档中。 ### 回答2: 将Java程序中的PDF文件换为图片的过程可以使用开源的Java库,如PDFBox或iText。首先,可以使用PDFBox或iText库将PDF文件换为一系列图片。然后,将这些图片文件按照需求处理,如调整尺寸、裁剪或加入水印等。最后,将处理后的图片文件使用相同的Java库将它们合并成一个新的PDF文件。 换为PDF文件后,可以使用开源库,如Apache PDFBox或iText库来进行PDF文件的压缩。可以通过设置压缩参数,如图像压缩质量、文本压缩方法和字体子集化来减小PDF文件的文件大小。这些库提供的API可以将压缩参数应用于换后的PDF文件,提供高效的压缩方法。 使用Java来进行PDF图片、再PDF并压缩的好处在于,Java是一种强大的跨平台编程语言,可以运行于多个操作系统上。此外,JavaPDF处理库很丰富,提供了许多功能且易于使用。大多数Java PDF处理库也具有良好的文档和社区支持,因此使用它们来处理PDF文件非常方便。 最后,这个Java程序可以应用于各种场景,如文件批处理、电子文档处理等。通过将PDF换为图片后再换为PDF并进行压缩,可以根据实际需求进行多种处理操作,提高文档处理的灵活性和效率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值