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://www.yiibai.com/pdfbox/pdfbox_overview.html)
[https://iowiki.com/pdfbox/pdfbox_quick_guide.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中插入图片的方法

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值