之前写过一遍文章是 图片生成PDF。
今天继续来对 doc等文件进行pdf合并以及多个pdf合并为一个pdf。
兄弟们,还是开箱即用。
1、doc生成pdf
依赖
<!-- doc生成pdf --><dependency><groupId>com.aspose</groupId><artifactId>aspose-words</artifactId><version>20.4</version></dependency>
示例代码
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import lombok.extern.slf4j.Slf4j;
import java.io.*;/*** doc生成pdf 依靠依赖 aspose-words* @Author hanmw**/
@Slf4j
public class Doc2Pdf {public static void main(String[] args) throws Exception {doc2pdf(null,null);}/*** doc 生成 pdf* @param inPath doc路径* @param outPath pdf路径*/public static void doc2pdf(String inPath, String outPath) {inPath = "D:\\doc\\生成word、生成pdf、合并pdf\\维修报告.docx";outPath = "D:\\doc\\生成word、生成pdf、合并pdf\\12.pdf";FileOutputStream os = null;try {// 新建一个空白pdf文档File file = new File(outPath);os = new FileOutputStream(file);// 读取doc文档Document doc = new Document(inPath);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,EPUB, XPS, SWF 相互转换doc.save(os, SaveFormat.PDF);System.out.println("doc生成pdf成功!");} catch (Exception e) {log.error("doc2pdf failed", e);} finally {if (os != null) {try {os.close();} catch (IOException e) {log.error("关闭os失败", e);}}}}}
2、多个pdf合并为一个pdf
依赖
<!-- 适用于 多个pdf合并 --><dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.28</version></dependency>
示例代码
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import java.io.File;
import java.io.IOException;/*** 合并PDF 依靠依赖 org.apache.pdfbox* @Author hanmw**/
@Slf4j
public class PdfMergeController {public static void main(String[] args) {mergePdf();}public static void mergePdf(){// 定义要合并的PDF文件列表File[] pdfFiles = {new File("D:\\SoftWare\\图片\\测试pdf\\file_one.pdf"),new File("D:\\SoftWare\\图片\\测试pdf\\file_two.pdf"),new File("D:\\SoftWare\\图片\\测试pdf\\file_three.pdf")};// 定义合并后的输出文件String mergeFilePath = "D:\\SoftWare\\图片\\测试pdf\\test\\merged.pdf";//文件地址的目录 是否存在,不存在新建目录File file = new File(mergeFilePath);if(!file.getParentFile().exists()){file.getParentFile().mkdirs();}try {// 创建PDF合并实用程序PDFMergerUtility pdfMerger = new PDFMergerUtility();// 将所有要合并的文件添加到实用程序中for (File pdfFile : pdfFiles) {pdfMerger.addSource(pdfFile);}// 设置合并后的输出文件pdfMerger.setDestinationFileName(mergeFilePath);// 执行合并操作pdfMerger.mergeDocuments(null);System.out.println("PDF合并成功!");} catch (IOException e) {e.printStackTrace();}}}