编程语言
首页 > 编程语言> > java中操作pdf【pdfbox】【itext】

java中操作pdf【pdfbox】【itext】

作者:互联网

PDF转PNG图片【pdfbox】

 /***
     * PDF文件转PNG图片,全部页数
     * @param PdfFilePath pdf完整路径
     * @param imgFilePath 图片存放的文件夹
     * @param dpi dpi越大转换后越清晰,相对转换速度越慢
     * @return
     */
    public void pdf2Image(String PdfFilePath, String dstImgFolder, int dpi) {
        File file = new File(PdfFilePath);
        PDDocument pdDocument;
        try {
            String imgPDFPath = file.getParent();
            int dot = file.getName().lastIndexOf('.');
            String imagePDFName = file.getName().substring(0, dot); // 获取图片文件名
            String imgFolderPath = null;
            if (dstImgFolder.equals("")) {
                imgFolderPath = imgPDFPath + File.separator + imagePDFName;// 获取图片存放的文件夹路径
            } else {
                imgFolderPath = dstImgFolder + File.separator + imagePDFName;
            }
            if (createDirectory(imgFolderPath)) {
                pdDocument = PDDocument.load(file);
                PDFRenderer renderer = new PDFRenderer(pdDocument);
                /* dpi越大转换后越清晰,相对转换速度越慢 */
                //下面两行代码获取pdf页数用到了itext,也可以用pdfbox,具体方法后面给出
                PdfReader reader = new PdfReader(PdfFilePath);
                int pages = reader.getNumberOfPages();
                StringBuffer imgFilePath = null;
                for (int i = 0; i < pages; i++) {
                    String imgFilePathPrefix = imgFolderPath + File.separator + imagePDFName;
                    imgFilePath = new StringBuffer();
                    imgFilePath.append(imgFilePathPrefix);
                    imgFilePath.append("_");
                    imgFilePath.append(String.valueOf(i + 1));
                    imgFilePath.append(".png");
                    File dstFile = new File(imgFilePath.toString());
                    BufferedImage image = renderer.renderImageWithDPI(i, dpi);
                    ImageIO.write(image, "png", dstFile);
                }
                System.out.println("PDF文档转PNG图片成功!");
            } else {
                System.out.println("PDF文档转PNG图片失败:" + "创建" + imgFolderPath + "失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

下面两个方法都可以获取pdf的页数【pdfbox】

PDDocument doc = PDDocument.load("e://aa.pdf");
System.out.println(doc.getNumberOfPages());

List<?> pages = doc.getDocumentCatalog().getAllPages();
System.out.println(pages.size());

Apache PDFBox 相关,参考:http://blog.csdn.net/chszs/article/details/9026439
Itext相关,参考http://api.itextpdf.com/pdfa/http://www.open-open.com/open25134.htm

标签:java,String,imgFolderPath,itext,File,new,pdfbox,dpi,imgFilePath
来源: https://www.cnblogs.com/easychill/p/12035070.html