pdfrenderer将pdf文件转化为图片

 String path = fileName + ".pdf";
title = URLEncoder.encode(title, "UTF-8");
FtpUtils.getInstance("def").getFile(path, bos);
os = response.getOutputStream();
         InputStream is = new ByteArrayInputStream(bos.toByteArray());
response.reset(); // 清除下载文件的空白行
response.resetBuffer();
response.setContentType(contentType);
response.setHeader("Content-Disposition", showMode + "; filename=" + title);
convertPdf2Image(is, os);//将图片显示在页面
//传入一个输入流,把pdf转化为图片之后流转到输出流中
public void convertPdf2Image(InputStream is, OutputStream os) throws IOException {
    int pagen = 1;
    PDFFile pdffile = null;
    byte[] byt = this.toByteArray(is);
    try {
        ByteBuffer buf = ByteBuffer.allocate(byt.length);//若长度不够会报outinex错误
        buf.put(byt);
        pdffile = new PDFFile(buf);
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (pagen < pdffile.getNumPages())
        return;

    //设置将第pagen也生成png图片
    PDFPage page = pdffile.getPage(pagen);
    int width = (int) page.getBBox().getWidth();
    int height = (int) page.getBBox().getHeight();
    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = img.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    PDFRenderer renderer = new PDFRenderer(page, g2,
            new Rectangle(0, 0, width, height), null, Color.white);//这个color为渲染出来的图片的背景颜色
    try {
        page.waitForFinish();
    } catch (Exception e) {
        e.printStackTrace();
    }
    renderer.run();
    g2.dispose();

    try {
        ImageIO.write(img, "png", os);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

//将一个输入流转化为字节数组

public static byte[] toByteArray(InputStream in) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024 * 20];
    int n = 0;
    while ((n = in.read(buffer)) != -1) {
        out.write(buffer, 0, n);
    }
    return out.toByteArray();
}
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值