Pdf转换为图片

来自ling
跳转至: 导航搜索
public static void pdfToImage(){
    File file = new File("e:/oo.pdf");
    try {
       PDDocument doc = PDDocument.load(file);
       PDFRenderer renderer = new PDFRenderer(doc);
       int pageCount = doc.getNumberOfPages();
       for(int i=0; i<pageCount; i++){
           BufferedImage image = renderer.renderImage(i, 2.5f);
//           BufferedImage image = renderer.renderImageWithDPI(i,296);
           ImageIO.write(image,"PNG",new File("e:/image/"+i+".png"));
        }
   } catch (IOException e) {
       e.printStackTrace();
   }
}
public static void pdfToImageToPdf(){
    File file = new File("e:/in.pdf");
    Document docOut = new Document();
    docOut.setMargins(0, 0, 0, 0);
    try {
        FileOutputStream os = new FileOutputStream("e:/out.pdf");
        PdfWriter.getInstance(docOut, os);
        docOut.open();
        PDDocument doc = PDDocument.load(file);
        PDFRenderer renderer = new PDFRenderer(doc);
        int pageCount = doc.getNumberOfPages();
        for(int i=0; i<pageCount; i++){
            long t1 = System.currentTimeMillis();
            ByteArrayOutputStream bb = new ByteArrayOutputStream();
            BufferedImage image = renderer.renderImage(i, 1.25f);   //第二个参数越大生成图片分辨率越高。
            long t2 = System.currentTimeMillis();
            ImageIO.write(image, "jpg",bb );
            long t3 = System.currentTimeMillis();
            Image jpg = Image.getInstance(bb.toByteArray());
            long t4 = System.currentTimeMillis();
            jpg.scalePercent(80.0f);       //此处百分比与前面的分辨率参数相乘结果为1,则可保证等比输出。
            jpg.setAlignment(Image.ALIGN_CENTER);
            docOut.add(jpg);
            long t5 = System.currentTimeMillis();
            System.out.println((t2 - t1) + "***" + (t3 - t2) + "***" + (t4 - t3) + "***" + (t5 - t4));
        }
        docOut.close();
    }catch (FileNotFoundException e){
        e.printStackTrace();
    }catch (DocumentException e){
        e.printStackTrace();
    }catch (IOException e){
        e.printStackTrace();
    }
}