Java将PDF的URL转成图片

Java将PDF的URL转成图片


Java将PDF的URL转成图片


前言

记录下通过pdfbox将pdfurl转化为图片(感谢老哥提供的思路)https://blog.csdn.net/weixin_38256991/article/details/103117417?ops_request_misc=&request_id=&biz_id=102&utm_term=Java%20%E5%B0%86url%20pdf%E9%93%BE%E6%8E%A5%E8%BD%AC%E6%8D%A2%E5%9B%BE%E7%89%87&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduweb~default-0-103117417.142v47pc_rank_34_default_3,201v3control_1&spm=1018.2226.3001.4187


一、引入maven依赖

	<dependency>
        <groupId>org.apache.pdfbox</groupId>
        <artifactId>pdfbox-app</artifactId>
        <version>2.0.16</version>
    </dependency>
    
    <dependency>
        <groupId>org.apache.pdfbox</groupId>
        <artifactId>pdfbox-tools</artifactId>
        <version>2.0.12</version>
    </dependency>

二、代码实现(只写了实现类)

@Service
public class PdfChangeToImagesServiceImpl implements PdfChangeToImagesService {
    @Autowired
    private EntityDao entityDao;

    @Override
    public MessageBean pdfToImage(String id,String urlPath) {

        String str = ""; // 返回给前台的Base64加密字符串
        InputStream inputStream = null;
        FileInputStream fis = null;
        ByteArrayOutputStream bos = null;

        try {

            //0.根据id从数据库查pdfurl
            Sql sql1 = new Sql("select XWQYHXSP_WJLJ from oa_xwqyhxsp where id=?");
            sql1.addParameter("id", id);
            String dt1 = DataManager.getFieldStringValue(sql1);
            String pdfUrl = dt1.toString();

            //System.out.println(pdfUrl);
            // 1、请求pdf的url,获取文件输入流
            String path = new String(pdfUrl.getBytes("iso8859-1"), "utf-8");
            URL url = new URL(path);
            inputStream = url.openStream();
            // 2、加载pdf输入流
            PDDocument doc = PDDocument.load(inputStream);
            PDFRenderer renderer = new PDFRenderer(doc);
            // 3、获取pdf的页数
            int pageCount = doc.getNumberOfPages();
            byte[] data = null;

            // 4、循环页数将pdf缩放,并转为图片
            for (int i = 0; i < pageCount; i++) {
                // 5、方式1-第二个参数是设置缩放比(即像素),方式2-renderer.renderImageWithDPI(i, 10)
                BufferedImage image = renderer.renderImage(i, 1.8f);

                // 6、设置文件存放地址(这边临时存放在当前文件下,以id为文件名)
                String classpath = this.getClass().getResource("/").getPath().replaceFirst("/", "").replaceAll("WEB-INF/classes/", "");
                String uuid = SuperKit.getUUID();
                File file = new File(classpath + "p2286/xwqyhxsp/" + uuid + ".png");
                String urlFile = SuperKit.getServerRemoteUrl() + "/p2286/xwqyhxsp/" + uuid + ".png";

                // 7、将图片BufferedImage转为png格式的图片并写入7步骤的文件中
                Sql sql = new Sql("update oa_xwqyhxsp set xwqyhxs_picurl = ? where id = ? ");
                sql.addParameter("xwqyhxs_picurl", urlFile);
                sql.addParameter("id", id);
                DataManager.execute(sql);
                //jo.put("url", urlPdf);

                try {
                    ImageIO.write(image, "png", file);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

                // 8、将文件流转为数组
                fis = new FileInputStream(file);
                bos = new ByteArrayOutputStream(1000);
                byte[] b = new byte[1000];
                int n;
                while ((n = fis.read(b)) != -1) {
                    bos.write(b, 0, n);
                }
                inputStream.close();
                data = bos.toByteArray();
                // 9、将文件数组用Base64加密返回字符串给前端
                str = new String(Base64.encodeBase64String(data));
                // 10、删除当前目录下的该文件
                if (!file.exists()){
                    System.out.println("png文件删除失败"+file+"不存在!");
                }else {
                    boolean b1 = file.delete();
                    System.out.println(b1+",png文件已删除!");
                }
                return SuperKit.success(APIMessageConstants.GET_SUCCESS, str);
            }
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } catch (InvalidPasswordException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (fis != null) {
                    fis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

将PDF转化图片流,并用 Base64 做加密传给前台,这里还将它存到了项目文件夹和数据库中

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值