记录项目中使用的工具类:word转pdf、多个pdf合并

124 阅读1分钟
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.*;

public class PDFUtils {
    
    /**
     * Word转PDF
     * @param wordPath word文件的全路径
     * @param pdfPath 生成pdf存放位置的全路径
     */
    public static void wordToPdf (String wordPath,String pdfPath){
        File inputWord = new File(wordPath);
        File outputFile = new File(pdfPath);
        try  {
            InputStream docxInputStream = new FileInputStream(inputWord);
            OutputStream outputStream = new FileOutputStream(outputFile);
            IConverter converter = LocalConverter.builder().build();
            converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
            outputStream.close();
            log.info("success");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    /**
     * 多个PDF合并
     * @param files pdf文件全路径的集合
     * @param outputPath 输出路径
     * @param outputFileName 输出文件名
     */
    public static void mergePDF(List<String> files, String outputPath, String outputFileName) {
        String sep = java.io.File.separator;
        Document document = null;
        PdfCopy copy = null;
        PdfReader reader = null;
        try {
            document = new Document(new PdfReader(files.get(0)).getPageSize(1));
            copy = new PdfCopy(document, new FileOutputStream(outputPath + sep +outputFileName));
            document.open();
            for (int i = 0; i < files.size(); i++) {
                reader = new PdfReader(files.get(i));
                int numberOfPages = reader.getNumberOfPages();
                for (int j = 1; j <= numberOfPages; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);
                    copy.addPage(page);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }  finally {
            if (document != null)
                document.close();
            if (reader != null)
                reader.close();
            if (copy != null)
                copy.close();
        }
    }
}