--添加依赖

<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
<dependency>
   <groupId>org.apache.pdfbox</groupId>
   <artifactId>pdfbox</artifactId>
   <version>2.0.12</version>
</dependency>

--最佳实践

package com.dhht.wechat.util;

import org.apache.commons.io.FileUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.rendering.PDFRenderer;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @Author: sh
 * @Description: PDFUtil
 * @Date: 11:35 2019/7/1
 */
public class PDFUtil {

/**
     * 将base64字符串转换为PDF在显示到页面中
     * @param base64String
     * @param httpServletResponse
     */
    public static void base64StringToPDFToPage(String base64String, HttpServletResponse httpServletResponse){
        BASE64Decoder decoder = new BASE64Decoder();
        ByteArrayOutputStream baos = null;
        ServletOutputStream sos = null;
        try {
            byte[] bytes = decoder.decodeBuffer(base64String);
            baos = new ByteArrayOutputStream();
            baos.write(bytes); //把byte写进输出流里
            if (baos != null) {
                httpServletResponse.setContentType("application/pdf");
                httpServletResponse.setContentLength(baos.size());
                httpServletResponse.setHeader("Expires", "0");
                httpServletResponse.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
                httpServletResponse.setHeader("Pragma", "public");
                // 设置打印PDF的文件名
                String fileName = "社保证明文件.pdf";
                fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
                httpServletResponse.setHeader("Content-Disposition", "filename=" + fileName);
                sos = httpServletResponse.getOutputStream();
                baos.writeTo(sos); //byte输出流写入servlet输出流
                sos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                sos.close();
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

/**
     *  将base64编码转换成PDF
     *  @param base64String
     *  1.使用BASE64Decoder对编码的字符串解码成字节数组
     *  2.使用底层输入流ByteArrayInputStream对象从字节数组中获取数据;
     *  3.建立从底层输入流中读取数据的BufferedInputStream缓冲输出流对象;
     *  4.使用BufferedOutputStream和FileOutputSteam输出数据到指定的文件中
     */
    public static void base64StringToPDF(String base64String, String pdfPath/*File file*/){
        File file = new File(pdfPath);// 将原来参数修改为字符串
        BASE64Decoder decoder = new BASE64Decoder();
        BufferedInputStream bin = null;
        FileOutputStream fout = null;
        BufferedOutputStream bout = null;
        try {
            //将base64编码的字符串解码成字节数组
            byte[] bytes = decoder.decodeBuffer(base64String);
            //创建一个将bytes作为其缓冲区的ByteArrayInputStream对象
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            //创建从底层输入流中读取数据的缓冲输入流对象
            bin = new BufferedInputStream(bais);
            //创建到指定文件的输出流
            fout  = new FileOutputStream(file);
            //为文件输出流对接缓冲输出流对象
            bout = new BufferedOutputStream(fout);

byte[] buffers = new byte[1024];
            int len = bin.read(buffers);
            while(len != -1){
                bout.write(buffers, 0, len);
                len = bin.read(buffers);
            }
            //刷新此输出流并强制写出所有缓冲的输出字节,必须这行代码,否则有可能有问题
            bout.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bout.close();
                fout.close();
                bin.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

/**
     * PDF转换为Base64编码
     * @param file
     * @return
     */
    public static String pdfToBase64(File file) {
        BASE64Encoder encoder = new BASE64Encoder();
        FileInputStream fin =null;
        BufferedInputStream bin =null;
        ByteArrayOutputStream baos = null;
        BufferedOutputStream bout =null;
        try {
            fin = new FileInputStream(file);
            bin = new BufferedInputStream(fin);
            baos = new ByteArrayOutputStream();
            bout = new BufferedOutputStream(baos);
            byte[] buffer = new byte[1024];
            int len = bin.read(buffer);
            while(len != -1){
                bout.write(buffer, 0, len);
                len = bin.read(buffer);
            }
            //刷新此输出流并强制写出所有缓冲的输出字节
            bout.flush();
            byte[] bytes = baos.toByteArray();
            return encoder.encodeBuffer(bytes).trim();

} catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fin.close();
                bin.close();
                baos.close();
                bout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

/**
     * pdf转jpg
     * @param pdfPath
     * @param jpgPath
     */
    public static void pdfToJpg(String pdfPath,String jpgPath){
        long start = System.currentTimeMillis();
        //pdf路径
        InputStream stream = null;
        try {
            stream = new FileInputStream(new File(pdfPath));//URLUtil.getStream(url);
            // 加载解析PDF文件
            PDDocument doc = PDDocument.load(stream);
            PDFRenderer pdfRenderer = new PDFRenderer(doc);
            PDPageTree pages = doc.getPages();
            int pageCount = pages.getCount();
            for (int i = 0; i < pageCount; i++) {
                BufferedImage bim = pdfRenderer.renderImageWithDPI(i, 200);
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                ImageIO.write(bim, "jpg", os);
                byte[] datas = os.toByteArray();
                FileUtils.writeByteArrayToFile(new File(jpgPath),datas);
            }
            long end = System.currentTimeMillis();
            long time = (end - start) / 1000;
            System.out.println("pdf转jpg耗时: {}s"+time);
        }catch (Exception e){

}

}

/**
     * base64转jpg
     * @param val
     * @param pdfFile
     * @param jpgFile
     */
    public static void base64ToJPG(String val,String pdfFile,String jpgFile){
        base64StringToPDF(val,pdfFile);
        pdfToJpg(pdfFile,jpgFile);
    }

}

Base64转PDF、PDF转IMG(使用pdfbox插件)的更多相关文章

  1. word,excel,ppt转Pdf,Pdf转Swf,通过flexpaper+swftools实现在线预览

    其实这是我好几年前的项目,现在再用这种方式我也不建议了,毕竟未来flash慢慢会淘汰,此方式也是因为目测大部分人都装了flash,才这么做的,但是页面展示效果也不好.其实还是考虑收费的控件,毕竟收费的 ...

  2. word转PDF,PDF转Image,使用oppenOffice注意事项等

    最近在电子合同等项目中需要把word或者pdf转换成image,用到了openOffice把word转换pdf,以及把pdf转换成图片 感谢小伙伴张国清花费了三天时间来实现了此功能.下面我将把具体的步 ...

  3. Working with PDF files in C# using PdfBox and IKVM

    I have found two primary libraries for programmatically manipulating PDF files;  PdfBox and iText. T ...

  4. java将pdf转成base64字符串及将base64字符串反转pdf

    package cn.wonders.utils; import java.io.BufferedInputStream;import java.io.BufferedOutputStream;imp ...

  5. php base64互转pdf

    /* * base64转pdf */ function base642pdf($formTxt,$toPdf) { $file = file_get_contents($formTxt);//读 $d ...

  6. Python|网页转PDF,PDF转图片爬取校园课表~

    import pdfkit import requests from bs4 import BeautifulSoup from PIL import Image from pdf2image imp ...

  7. ABAP FORM打印转PDF/pdf 预览

    function ZSTXBC_SSFCOMP_PDF_PREVIEW. *"-------------------------------------------------------- ...

  8. openOffice word转pdf,pdf转图片优化版

    之前写了一个版本的,不过代码繁琐而且不好用,效率有些问题.尤其pdf转图片速度太慢.下面是优化版本的代码. spriing_boot 版本信息:2.0.1.RELEASE 1.配置信息: packag ...

  9. 趣学算法 PDF pdf 下载 陈小玉版

    趣学算法pdf高清无水印版下载 最近在网上找趣学算法pdf,最后还是买了完整版,今天将本书分享出来,分享给那些和我一样在网上苦苦寻找的小可爱们,有条件的话请支持正版! 链接:https://pan.b ...

随机推荐

  1. Ansible常见错误解析

    背景 由于工作中经常用到ansible,所以整理了常用的ansible错误及原因分析,方便自己也方便别人参考. 1.shell 模块常见错误 1.1 使用shell遇到"msg": ...

  2. Codeforces 1296C - Yet Another Walking Robot

    题目大意: 给定一个机器人的行走方式 你需要取走一段区间 但要保证取走这段区间后机器人最终到达的终点位置是不变的 问这段区间最短时是哪一段 解题思路: 易得,如果重复走到了某些已经走过的点,那么肯定就 ...

  3. JZOJPJ-C 8/21题解

    原题大战D1 吐槽: T1 \(O(N^2)\; N \leq 26\) N大时还要写高精, 可以增加难度 T2 不给范围 T3 居然没有完全卡掉 不对应该赞美出题人 T4 PJ考个四边形不等式?? ...

  4. OGG实验:喂奶间隔数据表通过OGG配置同步

    我之前在<使用SQL计算宝宝每次吃奶的时间间隔(数据保障篇)>中提到数据实时同步的方案,其中有一种是数据表通过OGG进行同步,当时没有详细展开测试,只给了之前学习OGG时的配置示例.由于之 ...

  5. 通过Android的API对Sqlite数据库进行操作

    一.增删改查 增 改 查 删 这是删除之前 删除三条 Dao.java package com.example.databasedemo; import android.content.Content ...

  6. ABP JTable如何显示序列号

    显示序列号 recordsLoaded: function (event, data) { var SrNo = 0; if (data.records) { $.each(data.records, ...

  7. PAT B1038 统计同成绩学生超时问题

    输入格式: 输入在第 1 行给出不超过 10​5​​ 的正整数 N,即学生总人数.随后一行给出 N 名学生的百分制整数成绩,中间以空格分隔.最后一行给出要查询的分数个数 K(不超过 N 的正整数),随 ...

  8. 明明办理的是100M光纤,为何经过路由器输出只有20M?

    就在今年7月26日,宽带发展联盟发布了第20期<中国宽带速率状况报告>(2018年第二季度).报告显示,2018年第二季度我国固定宽带网络平均下载速率达到21.31Mbps,比去年第二季度 ...

  9. Python D9 学习

    Python 设置环境 当安装好Python 后 在计算机的属性里面   高级语言设置  环境变量. 环境变量里面的path  更改为Python的 树目录  可以从计算机直接下达命令 打开Pytho ...

  10. Linux(CENTOS7) Redis安装

    1.下载redis         在disk目录下,输入以下命令进行下载: wget http://download.redis.io/releases/redis-2.8.3.tar.gz 2.解 ...