之前寫過(guò)一遍文章是 圖片生成PDF。
今天繼續(xù)來(lái)對(duì) doc等文件進(jìn)行pdf合并以及多個(gè)pdf合并為一個(gè)pdf。
兄弟們,還是開(kāi)箱即用。
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\\維修報(bào)告.docx";
outPath = "D:\\doc\\生成word、生成pdf、合并pdf\\12.pdf";
FileOutputStream os = null;
try {
// 新建一個(gè)空白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 相互轉(zhuǎn)換
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("關(guān)閉os失敗", e);
}
}
}
}
}
2、多個(gè)pdf合并為一個(gè)pdf
依賴文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-693145.html
<!-- 適用于 多個(gè)pdf合并 -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.28</version>
</dependency>
示例代碼文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-693145.html
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\\圖片\\測(cè)試pdf\\file_one.pdf"),
new File("D:\\SoftWare\\圖片\\測(cè)試pdf\\file_two.pdf"),
new File("D:\\SoftWare\\圖片\\測(cè)試pdf\\file_three.pdf")
};
// 定義合并后的輸出文件
String mergeFilePath = "D:\\SoftWare\\圖片\\測(cè)試pdf\\test\\merged.pdf";
//文件地址的目錄 是否存在,不存在新建目錄
File file = new File(mergeFilePath);
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
try {
// 創(chuàng)建PDF合并實(shí)用程序
PDFMergerUtility pdfMerger = new PDFMergerUtility();
// 將所有要合并的文件添加到實(shí)用程序中
for (File pdfFile : pdfFiles) {
pdfMerger.addSource(pdfFile);
}
// 設(shè)置合并后的輸出文件
pdfMerger.setDestinationFileName(mergeFilePath);
// 執(zhí)行合并操作
pdfMerger.mergeDocuments(null);
System.out.println("PDF合并成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
到了這里,關(guān)于Java doc等文件生成PDF、多個(gè)PDF合并的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!