位置:首页 » 文章/教程分享 » 利用pdfbox将pdf文档转换为图片
如果需要在网页上预览pdf文档的话,可以将pdf转换为flash,同时也可将pdf转换为图片文件。以下为使用 pdfbox 对pdf进行转换的实例。

需要用到的jar包:pdfbox-1.8.2.jar、fontbox-1.8.2.jar
public static void convertPdf2Image(String pdfFilePath,String imageFilePath)  
    throws IOException  
{  
    File pdfFile = new File(pdfFilePath);  
    File imageFile = new File(imageFilePath);  
    File imageFileParent = new File(imageFile.getParent());  
    OutputStream output = null;  
    PDDocument pdDoc = null;  
    List<File> files = new ArrayList<File>();  
    try{  
        if(pdfFile.exists()){  
            if(!imageFileParent.exists()){  
                imageFileParent.mkdirs();  
            }  
            pdDoc = PDDocument.load(pdfFile);  
            int pageCount = pdDoc.getNumberOfPages();  
            List pages = pdDoc.getDocumentCatalog().getAllPages();  
            for(int i = 0; i < pages.size(); i++){  
                PDPage page = (PDPage)pages.get(i);  
                BufferedImage image = page.convertToImage();  
                Iterator iter = ImageIO.getImageWritersBySuffix("jpg");  
                ImageWriter writer = (ImageWriter)iter.next();  
                File tempFile = new File(imageFileParent.getPath(),i+imageFile.getName());  
                files.add(tempFile);  
                output = new FileOutputStream(tempFile);  
                ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);  
                writer.setOutput(imageOut);  
                writer.write(new IIOImage(image,null,null));  
                output.close();  
            }  
            pdDoc.close();  
            mergeMultiImageFiles(files,imageFile);//合并多张图片为一张图片  
        }  
          
    }finally{  
        try{  
            if(pdDoc != null){  
                pdDoc.close();  
            }  
            if(output != null){  
                output.close();  
            }  
        }catch(IOException e){  
            e.printStackTrace();  
        }  
    }  
}