java pdfbox 合併PDF、PDF轉圖片、PDF插入圖片

1、添加依賴

		<dependency>
			<groupId>org.apache.pdfbox</groupId>
			<artifactId>pdfbox</artifactId>
			<version>2.0.8</version>
		</dependency>

1.1 找到一個對pdfbox較好的文檔地址

https://www.yiibai.com/pdfbox/pdfbox_overview.html

https://iowiki.com/pdfbox/pdfbox_quick_guide.html

2、工具類

import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.rendering.PDFRenderer;

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

/**
 * <b> 合併PDF及PDF轉圖片
 * </b><br><br><i>Description</i> :
 * <br><br>Date: 2019/12/26 ${time}    <br>Author : dxl
 */
public class PdfBoxUtil {
    /**
     * pdf合併拼接
     * @Title:mulFile2One
     * @Description: TODO
     * @date 2019年9月22日 上午10:05:37
     * @author yqwang
     * @param files 文件列表
     * @param targetPath 合併到
     * @return
     * @throws IOException
     */
    public static File somePdfToOne(List<File> files, String targetPath) throws IOException {
        // pdf合併工具類
        PDFMergerUtility mergePdf = new PDFMergerUtility();
        for (File f : files) {
            if(f.exists() && f.isFile()){
                // 循環添加要合併的pdf
                mergePdf.addSource(f);
            }
        }
        // 設置合併生成pdf文件名稱
        mergePdf.setDestinationFileName(targetPath);
        // 合併pdf
        mergePdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
        return new File(targetPath);
    }

    public static void main(String[] args) throws IOException {
        imgInPdf();

    }
    /***
     * PDF文件轉PNG圖片,全部頁數
     *
     * @param PdfFilePath pdf完整路徑
     * @param dstImgFolder 圖片存放的文件夾
     * @param dpi dpi越大轉換後越清晰,相對轉換速度越慢
     * @return
     */
    public static void pdfToImage(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越大轉換後越清晰,相對轉換速度越慢 */
                int pages = pdDocument.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));
                    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();
        }
    }

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

  /**
    * <b> pdf中插入圖片
    * </b><br><br><i>Description</i> : 
    * @return void
    * <br><br>Date: 2019/12/27 9:42     <br>Author : dxl 
    */    
    public static void imgInPdf() throws IOException {
        //Loading an existing document
        File file = new File("D:/test/1.pdf");
        PDDocument doc = PDDocument.load(file);

        //Retrieving the page
        PDPage page = doc.getPage(0);

        //Creating PDImageXObject object
        PDImageXObject pdImage = PDImageXObject.createFromFile("D:/test/11.jpg",doc);

        //creating the PDPageContentStream object
        PDPageContentStream contents = new PDPageContentStream(doc, page);

        //Drawing the image in the PDF document
        contents.drawImage(pdImage, 0, 0,590,840);

        System.out.println("Image inserted");

        //Closing the PDPageContentStream object
        contents.close();

        //Saving the document
        doc.save("D:/test/121.pdf");

        //Closing the document
        doc.close();
//原文出自【易百教程】,商業轉載請聯繫作者獲得授權,非商業請保留原文鏈接:https://www.yiibai.com/pdfbox/pdfbox_inserting_image.html

    }

}

2.1對上面pdf中插入圖片的方法

是對易百教程中drawImage方法改變了(看了源代碼,有重載方法,多了後面兩個設置圖片寬高的參數,即590,840)在其他教程的功能中可以參考,使用前根據需要修改方法。PS:好似有的圖片插入後會當做掃描的,會把圖片類似於切割,也就是可以分塊編輯 :(

發佈了64 篇原創文章 · 獲贊 6 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章