base64转pdf pdf转image

maven


	org.apache.pdfbox
	pdfbox
	2.0.6



    commons-io
    commons-io
    2.6

测试类

package com.pdf;

import java.awt.image.BufferedImage;
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.FileOutputStream;
import java.io.InputStream;

import javax.imageio.ImageIO;

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;

public class Base64ToPdf {
public static void main(String[] args) throws Exception {
String base64 = “”;
base64StringToPdf(base64,“d://123.pdf”);

	pdfToImg("d://123.pdf","d://123.png","png");
}

/**
 * 
 * @param base64Content
 * @param filePath
 * @return
 * @throws Exception
 */
public static boolean base64StringToPdf(String base64Content,String filePath) throws Exception{
    BASE64Decoder decoder = new BASE64Decoder();
    BufferedInputStream bis = null;
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;

    try {
        byte[] bytes = decoder.decodeBuffer(base64Content);//base64编码内容转换为字节数组
        
        bis = new BufferedInputStream(new ByteArrayInputStream(bytes));
        
        File file = new File(filePath);
        file.getParentFile().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();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }finally{
        try {
        	bis.close();
        	fos.close();
        	bos.close();
        } catch (Exception e) {
        }
    }
}

/**
 * pdf转图片
 * @param pdfPath
 * @param imgPath
 * @param formatName
 */
public static void pdfToImg(String pdfPath,String imgPath,String formatName){
    InputStream stream = null;
    try {
        stream = new FileInputStream(new File(pdfPath));
        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, formatName, os);
            byte[] datas = os.toByteArray();
            FileUtils.writeByteArrayToFile(new File(imgPath),datas);
        }

    }catch (Exception e){

    }

}

}

你可能感兴趣的:(demo,java)