Base64转PDF、PDF转IMG(使用pdfbox插件)
--添加依赖
<!-- 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插件)的更多相关文章
- word,excel,ppt转Pdf,Pdf转Swf,通过flexpaper+swftools实现在线预览
其实这是我好几年前的项目,现在再用这种方式我也不建议了,毕竟未来flash慢慢会淘汰,此方式也是因为目测大部分人都装了flash,才这么做的,但是页面展示效果也不好.其实还是考虑收费的控件,毕竟收费的 ...
- word转PDF,PDF转Image,使用oppenOffice注意事项等
最近在电子合同等项目中需要把word或者pdf转换成image,用到了openOffice把word转换pdf,以及把pdf转换成图片 感谢小伙伴张国清花费了三天时间来实现了此功能.下面我将把具体的步 ...
- 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 ...
- java将pdf转成base64字符串及将base64字符串反转pdf
package cn.wonders.utils; import java.io.BufferedInputStream;import java.io.BufferedOutputStream;imp ...
- php base64互转pdf
/* * base64转pdf */ function base642pdf($formTxt,$toPdf) { $file = file_get_contents($formTxt);//读 $d ...
- Python|网页转PDF,PDF转图片爬取校园课表~
import pdfkit import requests from bs4 import BeautifulSoup from PIL import Image from pdf2image imp ...
- ABAP FORM打印转PDF/pdf 预览
function ZSTXBC_SSFCOMP_PDF_PREVIEW. *"-------------------------------------------------------- ...
- openOffice word转pdf,pdf转图片优化版
之前写了一个版本的,不过代码繁琐而且不好用,效率有些问题.尤其pdf转图片速度太慢.下面是优化版本的代码. spriing_boot 版本信息:2.0.1.RELEASE 1.配置信息: packag ...
- 趣学算法 PDF pdf 下载 陈小玉版
趣学算法pdf高清无水印版下载 最近在网上找趣学算法pdf,最后还是买了完整版,今天将本书分享出来,分享给那些和我一样在网上苦苦寻找的小可爱们,有条件的话请支持正版! 链接:https://pan.b ...
随机推荐
- odoo 日志文件太大处理,logfile自动轮替
可以在conf 文件中设置配置信息: logfile = /your/logfile/path/ logrotate = True ; 设置为True 即可自动更换旧的日志文件, 参考: https: ...
- UML-异常处理
1.名词解释 缺陷(Fault):错误引起的行为.如:程序员拼写错了数据库名称 错误(Error):缺陷在运行系统中的表现.如:当使用拼写错误的名称调用数据库时,抛出数据库异常 故障(Failure) ...
- NBU For Windows 更新后无法启动Java Console
系统环境:Win Server 2016 备份软件:NBU 8.1 Case :Windows系统默认自动安装系统补丁,重启过程中自动进行了Update,打上了最新的补丁后,NBU Java Co ...
- 题解 P1317 【低洼地】
题目 这题挺简单的,没必要用数组 [分析] 需要判断的是低洼地的数量 通过对题目中图进行分析,显然可以发现低洼地的定义: 若数组中存在一个数值相同的连续区间,这个区间端点外相邻两点的数值都大于该区间的 ...
- 吴裕雄--天生自然 PHP开发学习:数组
<?php $cars=array("Volvo","BMW","Toyota"); echo "I like " ...
- python logging的输出
---恢复内容开始--- python中logging的使用 什么是日志: 日志是一种可以追踪某些软件运行时所发生事件的方法 软件开发人员可以向他们的代码中调用日志记录相关的方法来表明发生了某些事情 ...
- flask前后端数据交互
1.后端如何得到前端数据1)如果前端提交的方法为POST:后端接收时要写methods=[‘GET’,‘POST’]xx=request.form.get(xx);xx=request.form[’‘ ...
- java笔记-手写
- XML技术详解
XML 1.XML概述 XML可扩展标记语言是一种基于文本的语言用作应用程序之间的通信模式,是一个非常有用的描述结构化信息的技术.XML工具使得转化和处理数据变得十分容易,但同样也要领域相关的标准和代 ...
- 约数个数函数(d)的一个性质证明
洛谷P3327 [SDOI2015]约数个数和 洛谷P4619 [SDOI2018]旧试题 要用到这个性质,而且网上几乎没有能看的证明,所以特别提出来整理一下. \[ d(AB) = \sum_{x| ...