zoukankan      html  css  js  c++  java
  • PDF文件的二进制流转图片文件的二进制流

    最近有个客户要求将pdf转成图片保存在桶

    首先我们来实现pdf字节流转成img字节流

    第一步:pom.xml中引入:

    <dependency>
        <groupId>org.apache.pdfbox</groupId>
        <artifactId>pdfbox</artifactId>
        <version>2.0.20</version>
    </dependency>

    第二步:代码实现:

    package com.ulic.gis.util;
    
    import java.awt.image.BufferedImage;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.imageio.ImageIO;
    
    import org.apache.pdfbox.pdmodel.PDDocument;
    import org.apache.pdfbox.rendering.PDFRenderer;
    
    public class PdfToImageUtil {
        /**
         * dpi越大转换后越清晰,相对转换速度越慢
         */
        private static final Integer DPI = 100;
    
        /**
         * 转换后的图片类型
         */
        private static final String IMG_TYPE = "jpg";
    
        /**
         * PDF转图片
         *
         * @param fileContent PDF文件的二进制流
         * @return 图片文件的二进制流
         */
        public static List<byte[]> pdfToImage(byte[] fileContent) throws IOException {
            List<byte[]> result = new ArrayList<>();
            try (PDDocument document = PDDocument.load(fileContent)) {
                PDFRenderer renderer = new PDFRenderer(document);
                for (int i = 0; i < document.getNumberOfPages(); ++i) {
                    BufferedImage bufferedImage = renderer.renderImageWithDPI(i, DPI);
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    ImageIO.write(bufferedImage, IMG_TYPE, out);
                    result.add(out.toByteArray());
                }
            }
            return result;
        }
        /**
         * PDF转图片
         *
         * @param fileContent PDF文件的二进制流
         * @return 图片文件的二进制流
         */
        public static byte[] pdfToImage2(byte[] fileContent) throws IOException {
            byte[] result = null;
            try (PDDocument document = PDDocument.load(fileContent)) {
                PDFRenderer renderer = new PDFRenderer(document);
                BufferedImage bufferedImage = renderer.renderImageWithDPI(0, DPI);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                ImageIO.write(bufferedImage, IMG_TYPE, out);
                result = out.toByteArray();
            }
            return result;
        }
    }
  • 相关阅读:
    android开发过程遇到的一些错误
    TCP/IP协议详解笔记——ARP协议和RARP协议
    TCP/IP协议详解笔记——IP协议
    C# Exchange发送邮件
    Echarts柱状图堆叠显示总数
    Git解决fatal: unable to connect to github.com问题
    IIS 413错误 解决方案
    C#启动外部Exe控制台程序并输入命令
    再看JavaScript
    Web Api(5)
  • 原文地址:https://www.cnblogs.com/yinyl/p/14197188.html
Copyright © 2011-2022 走看看