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 ...
随机推荐
- POJ 1080:Human Gene Functions LCS经典DP
Human Gene Functions Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 18007 Accepted: ...
- XML--XML Schema Definition(四)
参考 http://www.w3school.com.cn/schema/index.asp XSD 复合类型指示器 通过指示器,我们可以控制在文档中使用元素的方式.有七种指示器: Order 指示器 ...
- E - Apple Tree POJ - 2486
E - Apple Tree POJ - 2486 Wshxzt is a lovely girl. She likes apple very much. One day HX takes her t ...
- Git 学习 day01
Tips:最近的工作中需要用到版本控制工具git,所以准备开一个分类用来记录下自己学到的知识,以备以后温习 在安装完git之后需要设置用户名和用户邮箱: $ git config --global u ...
- Django1.11基础视图
Django视图 路由命名与reverse反解析 在项目urls中的include函数,使用namespace参数定义路由命名空间 url(r'^',incude('book.urls',namesp ...
- Activity的Launch mode详解 :standard(默认), singleTop, singleTask和 singleInstance
本文参考了此文http://hi.baidu.com/amauri3389/blog/item/a54475c2a4b2f040b219a86a.html 另附 android task与back s ...
- sp__helptable, sp__help******* help 存储过程
from: https://sqldbaknowledgeshare.wordpress.com/2014/11/27/general-help-procedures/ GENERAL HELP P ...
- Python使用+和*操作符 连接2个列表和列表的复制
+ 操作符通常连接两个列表可以使用 +进行连接得到一个新列表 *操作符择可以用于一个列表和一个整数,实现列表的复制.
- idhttp文件的上传和下载
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms ...
- 吴裕雄--天生自然 JAVA开发学习:修饰符
public class InstanceCounter { private static int numInstances = 0; protected static int getCount() ...