1. 程式人生 > >pdf轉高清圖片

pdf轉高清圖片

很多人在java中遇到ppt/pdf轉圖片的時候,有些插圖圖片轉不了或者是轉出來的圖片不清晰,也都是使用的官方jar包。有些是需要引用到icepdf外掛的,這裡不細說了,直接放一段稍微簡單一點的程式碼供參考:

package test;

import com.lowagie.text.pdf.PdfReader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class pdfToImage {
    public static void main(String[] args) {
        change("C:\\Users\\Administrator\\Desktop\\pdf\\使用者手冊V1.pdf", "C:\\Users\\Administrator\\Desktop\\pdf", 200);
    }

    public static void change(String PdfFilePath, String ImgFolder, 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 (ImgFolder.equals("")) {
                imgFolderPath = imgPDFPath + File.separator + imagePDFName;
            } else {
                imgFolderPath = ImgFolder + File.separator + imagePDFName;
            }

            if (createDirectory(imgFolderPath)) {

                pdDocument = PDDocument.load(file);
                PDFRenderer renderer = new PDFRenderer(pdDocument);
              
                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("文件轉轉成功!");

            } else {
                System.out.println("文件轉換失敗:" + "建立" + imgFolderPath + "失敗");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static boolean createDirectory(String folder) {
        File dir = new File(folder);
        if (dir.exists()) {
            return true;
        } else {
            return dir.mkdirs();
        }
    }

}

資料下載連結

      https://download.csdn.net/download/knight_key/10752175