天天看點

Word轉pdf,再轉圖檔插入PDF

WORD轉PDF所需jar包:

https://yangtaotao.lanzous.com/ice1jlc

PDF轉圖檔所需jar包:

https://yangtaotao.lanzous.com/ice169c 

由于項目中之前就有,是以直接照搬。word轉pdf,使用的是ASPOSE.word ,ASPOSE.word的licence需要收費

package com.biolims.report.service;

import java.io.FileOutputStream;
import java.io.InputStream;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;

/**
 * 
 * 由于ASPOSE比較吃記憶體,操作大一點的檔案就會堆溢出,是以請先設定好java虛拟機參數:-Xms512m -Xmx512m(參考值)<br>
 * 如有疑問,請在CSDN下載下傳界面留言,或者聯系QQ569925980<br>
 * 
 * @author Spark
 *
 */
public class Test {

    /**
     * 擷取license
     * 
     * @return
     */
    public static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = Test.class.getClassLoader().getResourceAsStream("\\license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    public static void savedocx(String inPath, String outPath) {
         if (!getLicense()) {
                return;
            }

            try {
                long old = System.currentTimeMillis();
                Document doc = new Document(inPath);// 原始word路徑
               
                String pdfFile = outPath;
                FileOutputStream fileOS = new FileOutputStream(pdfFile);

                doc.save(fileOS, SaveFormat.PDF);

                long now = System.currentTimeMillis();
                System.out.println("共耗時:" + ((now - old) / 1000.0) + "秒");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    /**
     * 支援DOC, DOCX, OOXML, RTF, HTML, OpenDocument, PDF, EPUB, XPS, SWF等互相轉換<br>
     * 
     * @param args
     */
    public static void main(String[] args) {
        // 驗證License
        if (!getLicense()) {
            return;
        }

        try {
            long old = System.currentTimeMillis();
            Document doc = new Document("D:\\home\\lims\\報告管理需求 - 20190905.docx");// 原始word路徑
           
            String pdfFile = "D:\\home\\ff.pdf";
            FileOutputStream fileOS = new FileOutputStream(pdfFile);

            doc.save(fileOS, SaveFormat.PDF);

            long now = System.currentTimeMillis();
            System.out.println("共耗時:" + ((now - old) / 1000.0) + "秒");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}      

調用結合我之前發的導出word的文章

/**
     * 根據模闆生成word
     * 
     * @param path2
     *            模闆的路徑
     * @param params
     *            需要替換的參數
     * @param tableList
     *            需要插入的參數,裡面的list為每個表的資料
     * @param fileName
     *            生成word檔案的檔案名
     * @param response
     */
    public FileInfo getWord(String path2, Map<String, Object> params, List<List<String[]>> tableList, String fileName,
            HttpServletResponse response) throws Exception {
        File file = new File(path2);
        InputStream is = new FileInputStream(file);
        CustomXWPFDocument doc = new CustomXWPFDocument(is);
        this.replaceInPara(doc, params); // 替換文本裡面的變量
        this.replaceInTable(doc, params, tableList); // 替換表格裡面的變量



//        OutputStream os = response.getOutputStream();
//        response.setContentType("application/x-download");
//        response.setHeader("Content-disposition", "attachment; filename=" + fileName);
//        doc.write(os);

        SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
        String formFile = ConfigFileUtil.getValueByKey("file.report.form.path");
        File deskFile = new File(formFile, "report" + sdf.format(new Date()) + ".docx");
        String path = deskFile.getPath();
        // 寫到目标檔案
        OutputStream output = new FileOutputStream(deskFile);
        // document.write(output);
        doc.write(output);
        output.close();
        String name = sdf.format(new Date());
        String newPdfPath=formFile+"report" + name + ".pdf";  //新生成的pdf檔案路徑
        Test.savedocx(path, newPdfPath);

        String newImgPdfPath = pdf2Image(newPdfPath);

        File p = new File(deskFile.getPath());
        FileInfo fi = new FileInfo();

        fi.setFileName("report" + "" + name + ".pdf");
        fi.setUploadTime(new Date());
        fi.setOwnerModel("ReportItem");
        fi.setUseType("0");
        fi.setModelContentId("");
        fi.setFileType("pdf");
        fi.setFilePath(newImgPdfPath);

        this.close(is);

        return fi;

    }      

pdf轉圖檔,再插入pdf,使PDF就算用專業軟體也不能打開,但是我們上司覺得可能多頁會出現問題,但是還沒有好的解決辦法,如果有了請評論告知,不勝感激

public static String pdf2Image(String PdfFilePath) throws Exception {
        File file = new File(PdfFilePath);
        PdfDocument template_writer_pdfdoc = new PdfDocument(new PdfReader(PdfFilePath));
        Rectangle size=template_writer_pdfdoc.getFirstPage().getPageSize();
        int pages = template_writer_pdfdoc.getNumberOfPages();
        PDDocument pdDocument;
        String pdfPath="";
        try {
            String imgPDFPath = file.getParent();
            int dot = file.getName().lastIndexOf(\'.\');
            String imagePDFName = file.getName().substring(0, dot); // 擷取圖檔檔案名
            pdDocument = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(pdDocument);
            /* dpi越大轉換後越清晰,相對轉換速度越慢 */
            StringBuffer imgFilePath = null;
            List<String> pathList=new ArrayList<String>();
            for (int i = 0; i < pages; i++) {
                String imgFilePathPrefix = imgPDFPath + File.separator + imagePDFName;
                imgFilePath = new StringBuffer();
                imgFilePath.append(imgFilePathPrefix);
                imgFilePath.append("_");
                imgFilePath.append(String.valueOf(i + 1));
                imgFilePath.append(".jpg");
                File dstFile = new File(imgFilePath.toString());
                BufferedImage image = renderer.renderImageWithDPI(i, 300);
                ImageIO.write(image, "jpg", dstFile);
                pathList.add(imgFilePath.toString());
            }

            template_writer_pdfdoc.close();
            File file2 = new File(imgPDFPath + File.separator + file.getName());
            // 第一步:建立一個document對象。
            com.itextpdf.text.Document document = new com.itextpdf.text.Document();
            document.setMargins(0, 0, 0, 0);
            // 第二步:
            // 建立一個PdfWriter執行個體,
            com.itextpdf.text.pdf.PdfWriter.getInstance(document, new FileOutputStream(file2));
            // 第三步:打開文檔。

            document.open();
            for(String s:pathList) {
                com.itextpdf.text.Image img = com.itextpdf.text.Image.getInstance(s);
                img.setAlignment(com.itextpdf.text.Image.ALIGN_CENTER);
                img.scaleAbsoluteHeight(size.getHeight());
                img.scaleAbsoluteWidth(size.getWidth());
                // 根據圖檔大小設定頁面,一定要先設定頁面,再newPage(),否則無效
                document.setPageSize(new com.itextpdf.text.Rectangle(size.getWidth(), size.getHeight()));
                document.newPage();
                document.add(img);
            }
            document.close();
            pdfPath=imgPDFPath + File.separator + file.getName();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

        }
        return pdfPath;
    }