当前位置: 首页 > 工具软件 > PDF Renderer > 使用案例 >

pdfrenderer将pdf文件转化为图片

常永长
2023-12-01
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();
}
 类似资料: