import com.itextpdf.text.pdf.codec.Base64;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
/*
* @Author Mr伍
* @Description //TODO
* @Date 2020/1/9
* @Param
* @return
**/
@Slf4j
public class Base64AndPdf {
/**
* @Description:Base64转换成pdf
* @param:
* @return:
* @author: TateBrown
* @Date: 2018/7/23
*/
public static void Base64toPdffile(String pdfBase64Str,String filepath){
BufferedInputStream bis = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try{
byte[] bytes= Base64.decode(pdfBase64Str);
ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(bytes);
bis=new BufferedInputStream(byteArrayInputStream);
File file=new File(filepath);
File path=file.getParentFile();
if(!path.exists()){
path.mkdirs();
}
fos=new FileOutputStream(file);
bos=new BufferedOutputStream(fos);
byte[] buffer=new byte[1024];
int length=bis.read(buffer);
while(length!=-1){
bos.write(buffer,0,length);
length=bis.read(buffer);
}
bos.flush();
}catch(Exception e){
log.error("文件转pdf失败电子签章的工具类,详情:"+e.getMessage());
new RuntimeException("转pdf电子签章失败"+e.getMessage());
// e.printStackTrace();
}finally {
// System.err.println("保存成功pdf");
try{
bis.close();
bos.close();
fos.close();
}catch (IOException e){
log.error(e.getMessage());
e.printStackTrace();
}
}
}
//TODO
// 为工程添加 sun.misc.BASE64Encoder和sun.misc.BASE64Decoder包:
//右键项目》属性》Java Build Path》jre System Library 》access rules》resolution选择accessible,下面填上**点击确定即可!
/*BASE64Encoder和BASE64Decoder这两个方法是sun公司的内部方法,并没有在java api中公开过,所以使用这些方法是不安全的,
* 将来随时可能会从中去除,所以相应的应该使用替代的对象及方法,建议使用apache公司的API*/
static BASE64Encoder encoder = new BASE64Encoder();
static BASE64Decoder decoder = new BASE64Decoder();
/**
* 将PDF转换成base64编码
* 1.使用BufferedInputStream和FileInputStream从File指定的文件中读取内容;
* 2.然后建立写入到ByteArrayOutputStream底层输出流对象的缓冲输出流BufferedOutputStream
* 3.底层输出流转换成字节数组,然后由BASE64Encoder的对象对流进行编码
* */
public static String getPDFBinaryBase64(File file) {
FileInputStream fin =null;
BufferedInputStream bin =null;
ByteArrayOutputStream baos = null;
BufferedOutputStream bout =null;
try {
//建立读取文件的文件输出流
fin = new FileInputStream(file);
//在文件输出流上安装节点流(更大效率读取)
bin = new BufferedInputStream(fin);
// 创建一个新的 byte 数组输出流,它具有指定大小的缓冲区容量
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();
//sun公司的API
return encoder.encodeBuffer(bytes).trim();
//apache公司的API
//return Base64.encodeBase64String(bytes);
} catch (FileNotFoundException e) {
log.error(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
log.error(e.getMessage());
}finally{
try {
fin.close();
bin.close();
//关闭 ByteArrayOutputStream 无效。此类中的方法在关闭此流后仍可被调用,而不会产生任何 IOException
//baos.close();
bout.close();
} catch (IOException e) {
log.error("关闭异常"+e.getMessage());
e.printStackTrace();
}
}
return null;
}
/*
public static void main(String[] args) throws FileNotFoundException {
// File file = ResourceUtils.getFile("classpath:pdfPact/房屋买卖合同范本.pdf");
//获取文件的相对路径 可在控制台打印查看输出结果
*//* String x=getPDFBinaryBase64(file);
System.err.println("base64"+x.length());
Base64toPdffile(x,"D:/合同/买卖合同1.pdf");
System.err.println("保存成功");*//*
}*/
}
base64转MultipartFile的工具类
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
public class Base64StrToImage {
Logger logger = LoggerFactory.getLogger(Base64StrToImage.class);
public static MultipartFile base64MutipartFile(String imgStr){
try {
String [] baseStr = imgStr.split(",");
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] b = new byte[0];
b = base64Decoder.decodeBuffer(baseStr[1]);
for(int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
return new BASE64DecodedMultipartFile(b,baseStr[0]) ;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
public static MultipartFile base64Mutipartpdf(String imgStr){
try {
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] b = new byte[0];
b = base64Decoder.decodeBuffer(imgStr);
for(int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
return new BASE64DecodedMultipartFile(b,"data:application/pdf;base64,") ;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
}
BASE64DecodedMultipartFile类
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
public class BASE64DecodedMultipartFile implements MultipartFile {
private final byte[] imgContent;
private final String header;
public BASE64DecodedMultipartFile(byte[] imgContent, String header) {
this.imgContent = imgContent;
this.header = header.split(";")[0];
}
@Override
public String getName() {
return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1];
}
@Override
public String getOriginalFilename() {
return System.currentTimeMillis() + (int)Math.random() * 10000 + "." + header.split("/")[1];
}
@Override
public String getContentType() {
return header.split(":")[1];
}
@Override
public boolean isEmpty() {
return imgContent == null || imgContent.length ==0;
}
@Override
public long getSize() {
return imgContent.length;
}
@Override
public byte[] getBytes() throws IOException {
return imgContent;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(imgContent);
}
@Override
public void transferTo(File file) throws IOException, IllegalStateException {
new FileOutputStream(file).write(imgContent);
}
}
Mult…转String
public String test(MultipartFile file) throws Exception{
BASE64Encoder base64Encoder =new BASE64Encoder();
String base64EncoderImg = file.getOriginalFilename()+","+ base64Encoder.encode(file.getBytes());
return base64EncoderImg;
}