侧边栏壁纸
博主头像
suringYu

走走停停

  • 累计撰写 50 篇文章
  • 累计创建 18 个标签
  • 累计收到 3 条评论

目 录CONTENT

文章目录

图片base64转pdfbase64

suringYu
2021-02-02 / 0 评论 / 0 点赞 / 343 阅读 / 8,618 字

思路:先将图片base64转变图片,通过直接操作图片文件转变成pdf,最后将pdf读取为base64

package com.web.util;

import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.util.ResourceUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

/**
 * <b>创建人:</b>surfingCat<br>
 * <b>类描述:</b>图片base64转pdfbase64<br>
 * <b>创建时间:</b>2021/2/2 15:39<br>
 */
public class base64Util {

    static BASE64Encoder encoder = new sun.misc.BASE64Encoder();
    static BASE64Decoder decoder = new sun.misc.BASE64Decoder();
    /**
     * @title  将图片的base64转成PDF的base64编码
     * @param  bas64ImageStr  需要转换的base64编码
     * @return 转换后的base64编码
     */
    public static String imageBase64ToPdfBase64(String bas64ImageStr){
        String pdfBase64 = "";//PDF的base64编码
        String uuid = String.valueOf(UUID.randomUUID()).replace("-", "");
        try{
            //1.去除转义字符
            bas64ImageStr = bas64ImageStr.replaceAll("\r|\n", "");
            //2.获取要存储文件的路径,即获取src资源文件编译后的路径(即classes路径)
            //当前项目下路径
            String url = ResourceUtils.getURL("classpath:").getPath();;
            //对路径进行拼接添加
            String servicePdfPath = url + "/servicePdf/";//存放PDF的路径
            String serviceImagePath = url + "/serviceImage/";//存放PDF的路径
            //3.判断是否存在此文件夹,不存在则新建
            File pdfFolder =new File(servicePdfPath);
            if(!pdfFolder.exists()  && !pdfFolder.isDirectory()) {
                pdfFolder.mkdir();
            }
            File imageFolder =new File(serviceImagePath);
            if(!imageFolder.exists()  && !imageFolder.isDirectory()) {
                imageFolder.mkdir();
            }
            //4.图片的文件名字和最终保存的文件路径
            String filePdfName = uuid +"_change.pdf";//PDF图片路径名字
            String lastPdfPath = servicePdfPath+filePdfName;//最终PDF存放的路径
            String imageName = uuid +"_change.jpg";//图片路径名字
            String lastImagePath = serviceImagePath+imageName;//最终PDF存放的路径
            //5.imageBase64转成PDF文件进行储存
            base64ToImage(bas64ImageStr,lastImagePath);
            //6.图片转成PDF文件进行储存
            fileToPdf(lastImagePath,lastPdfPath);
            //7.最后将PDF转成base64
            File file3 =new File(lastPdfPath);
            pdfBase64 = getPDFBinary(file3);
            pdfBase64 = pdfBase64.replaceAll("\r|\n", "");
            base64StringToPDF(pdfBase64,lastPdfPath);
            //8.需要删除创建的临时文件
            File imageFile = new File(lastImagePath);
            if(imageFile.exists()){
                imageFile.delete();
            }
            File pdfFile = new File(lastPdfPath);
            if(pdfFile.exists()){
                pdfFile.delete();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return pdfBase64;
    }

    /**
     * base64字符串转化成图片
     * @param imageBase64 图片base64编码
     * @param filePath 存放路径
     * @return 是否成功
     */
    public static boolean base64ToImage(String imageBase64,String filePath) { // 对字节数组字符串进行Base64解码并生成图片
        if (imageBase64 == null) // 图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
// Base64解码
            byte[] b = decoder.decodeBuffer(imageBase64);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(filePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * @title 将PDF转换成base64编码
     * 1.使用BufferedInputStream和FileInputStream从File指定的文件中读取内容;
     * 2.然后建立写入到ByteArrayOutputStream底层输出流对象的缓冲输出流BufferedOutputStream
     * 3.底层输出流转换成字节数组,然后由BASE64Encoder的对象对流进行编码
     * @param file PDF文件
     * @return 转换后的base64编码
     */
    public static String getPDFBinary(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) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fin.close();
                bin.close();
                baos.close();
                bout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     *
     * @title 将base64编码转换成PDF
     * @param base64sString 需要转换的base64
     * @param filePath 文件路径
     */
    public static void base64StringToPDF(String base64sString, String filePath) {
        BufferedInputStream bin = null;
        FileOutputStream fout = null;
        BufferedOutputStream bout = null;
        try {
            // 将base64编码的字符串解码成字节数组
            byte[] bytes = decoder.decodeBuffer(base64sString);
            // apache公司的API
            // byte[] bytes = Base64.decodeBase64(base64sString);
            // 创建一个将bytes作为其缓冲区的ByteArrayInputStream对象
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            // 创建从底层输入流中读取数据的缓冲输入流对象
            bin = new BufferedInputStream(bais);
            // 指定输出的文件
            File file = new File(filePath);
            // 创建到指定文件的输出流
            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 {
                bin.close();
                fout.close();
                bout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 文件转pdf
     * @param filePath 文件路径
     * @param target 转换后路径
     */
    public static void fileToPdf(String filePath, String target) {
        Document document = new Document();
        //设置文档页边距
        document.setMargins(0,0,0,0);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(target);
            PdfWriter.getInstance(document, fos);
            //打开文档
            document.open();
            //获取图片的宽高
            Image image = Image.getInstance(filePath);
            float imageHeight=image.getScaledHeight();
            float imageWidth=image.getScaledWidth();
            //设置页面宽高与图片一致
            Rectangle rectangle = new Rectangle(imageWidth, imageHeight);
            document.setPageSize(rectangle);
            //图片居中
            image.setAlignment(Image.ALIGN_CENTER);
            //新建一页添加图片
            document.newPage();
            document.add(image);
        } catch (Exception ioe) {
            System.out.println(ioe.getMessage());
        } finally {
            //关闭文档
            document.close();
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

0

评论区