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中插入图片的方法

在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java PDFBox是一个开源的Java库,可以用来处理PDF文件。它提供了丰富的功能,包括创建、编辑、合并和提取PDF文件的内容。 要将Word文件换为PDF,首先需要使用Java代码将Word文件读取到内存中。可以使用Apache POI库来实现这一功能。然后,可以使用PDFBox库将Word文件的内容和格式换为PDF格式。 首先,需要在你的Java项目中引入Apache POI和PDFBox的依赖库。然后,可以使用POI库的API读取Word文件的内容,并将其存储在内存中。接下来,可以使用PDFBox库的API创建一个空白的PDF文件,并将Word文件的内容和格式写入PDF文件中。 以下是一个简单的示例代码,用于将Word文件换为PDF: ```java import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.text.PDFTextStripper; import org.apache.poi.xwpf.extractor.XWPFParagraphDecorator; import org.apache.poi.xwpf.extractor.XWPFWordExtractorDecorator; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class WordToPDFConverter { public static void main(String[] args) { try { // 读取Word文件 File wordFile = new File("path/to/word/file.docx"); FileInputStream fis = new FileInputStream(wordFile); XWPFDocument doc = new XWPFDocument(fis); // 创建PDF文件 PDDocument pdfDoc = new PDDocument(); PDPage page = new PDPage(); pdfDoc.addPage(page); // 写入Word文件内容到PDF文件 PDPageContentStream contentStream = new PDPageContentStream(pdfDoc, page); PDFTextStripper stripper = new PDFTextStripper(); XWPFWordExtractorDecorator extractor = new XWPFWordExtractorDecorator(doc); stripper.writeText(contentStream, extractor.getDocument().getBodyElements()); // 保存PDF文件 pdfDoc.save("path/to/pdf/file.pdf"); pdfDoc.close(); doc.close(); System.out.println("WordPDF成功!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 运行上述代码后,将生成一个PDF文件,其中包含了Word文件的内容和格式。 需要注意的是,由于Word和PDF的格式差异较大,换过程中可能会丢失某些复杂的格式或布局。因此,在使用Java PDFBox进行WordPDF时,建议对换结果进行验证和调整,以确保与原始Word文件的一致性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值