JAVA合並word文檔生成目錄


下載jar包,或者引入相關maven

maven引入相關地址:https://www.e-iceblue.cn/licensing/install-spirepdf-for-java-from-maven-repository.html

jar包下載地址:點擊下載

 

如果不知道怎么引入jar包到項目中,請面向百度。

 

如果word文檔中已經設置了大綱就直接使用一段代碼即可

 

    public static void main(String[]args){
        //加載測試文檔
        Document doc = new Document("測試文件.docx");

        //在文檔最前面插入一個段落,寫入文本並格式化
        Paragraph parainserted = new Paragraph(doc);
        TextRange tr= parainserted.appendText("目 錄");
        tr.getCharacterFormat().setBold(true);
        tr.getCharacterFormat().setTextColor(Color.gray);
        doc.getSections().get(0).getParagraphs().insert(0,parainserted);
        parainserted.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
        
        //手動設置文檔中指定段落的大綱級別
        doc.getSections().get(0).getParagraphs().get(1).applyStyle(BuiltinStyle.Heading_1);
        doc.getSections().get(0).getParagraphs().get(2).applyStyle(BuiltinStyle.Heading_2);
        doc.getSections().get(0).getParagraphs().get(4).applyStyle(BuiltinStyle.Heading_2);
        doc.getSections().get(0).getParagraphs().get(6).applyStyle(BuiltinStyle.Heading_2);
        doc.getSections().get(0).getParagraphs().get(12).applyStyle(BuiltinStyle.Heading_2);
        doc.getSections().get(0).getParagraphs().get(13).applyStyle(BuiltinStyle.Heading_3);
        doc.getSections().get(0).getParagraphs().get(14).applyStyle(BuiltinStyle.Heading_3);
        doc.getSections().get(0).getParagraphs().get(15).applyStyle(BuiltinStyle.Heading_3);
        doc.getSections().get(0).getParagraphs().get(17).applyStyle(BuiltinStyle.Heading_1);
        doc.getSections().get(0).getParagraphs().get(18).applyStyle(BuiltinStyle.Heading_2);

        //添加目錄
        doc.getSections().get(0).getParagraphs().get(0).appendTOC(1,3);

        //更新目錄表
        doc.updateTableOfContents();

        //保存文檔
        doc.saveToFile("目錄.docx",FileFormat.Docx_2010);
    }

demo來源地址:https://www.e-iceblue.cn/spiredocforjavaformfield/add-word-toc-in-java.html

 

下面這個是沒有設置大綱的文檔生成目錄,我的方案是把每頁第一段設置為大綱,然后生成目錄。

下面的是合並文檔然后生成目錄和頁碼的代碼邏輯。

 

    /**
    *    先臨時生成一個合並完成后的docx格式文檔,doc會出現亂碼。
    * @param pathList 所有需要合並的文檔的絕對路徑
    * @param savePath 一個路徑,但是沒有文件的后綴,之后進行拼接。
    * @return 狀態,是否保存成功
    */
   public static boolean mergeWordToPdf(List<String> pathList, String savePath){
       //判斷是否為pdf文件后綴的路徑
//       String[] split = savePath.split("\\.");
//       if (!"pdf".equals(split[split.length-1])) {
//           System.out.println("請給一個以pdf保存路徑結尾的路徑");
//           return false;
//       }
       //保存合並完成后臨時存放的文件
       String file =  savePath + ".docx";
       File newfile = new File(file);
       try {
           //判斷是否存在,存在則刪除
           if (newfile.exists()) {
               newfile.delete();
           }
           newfile.createNewFile();
           //創建一個新的doc文件
           Document doc = new Document(file);
           int count = 0;
           // 進行合並
           for (String filePath : pathList) {
               // 獲取文檔的路徑,然后合並
               count++;
               Document doc2 = new Document();
               doc2.loadFromFile(filePath);
               for (int j = 0; j < doc2.getSections().getCount(); j++) {
                   doc.getSections().add(doc2.getSections().get(j).deepClone());
               }
           }

           // 在開頭創建一個目錄頁
           ParagraphStyle title1style = new ParagraphStyle(doc);
           title1style.setName("TL1");
           title1style.getParagraphFormat().setOutlineLevel(OutlineLevel.Level_1);
           doc.getStyles().add(title1style);
           Section sec = doc.getSections().get(0);
           //設置邊距
           sec.getPageSetup().getMargins().setTop(71.882f);
           sec.getPageSetup().getMargins().setBottom(71.882f);
           sec.getPageSetup().getMargins().setLeft(90f);
           sec.getPageSetup().getMargins().setRight(90f);
           sec.getParagraphs().get(0).applyStyle(title1style.getName());

           //循環遍歷每一頁的標題,並添加到目錄頁中
           for (int i = 1; i <= count; i++) {
               sec = doc.getSections().get(i);
               sec.getParagraphs().get(0).applyStyle(title1style.getName());
           }
           sec = doc.getSections().get(0);
           Paragraph para = new Paragraph(doc);
           sec.getParagraphs().insert(0, para);
           TableOfContent toc = para.appendTOC(1, 3);
           toc.setUseHeadingStyles(false);
           toc.setUseHyperlinks(true);
           toc.setUseTableEntryFields(false);
           toc.setRightAlignPageNumbers(true);
           toc.setTOCLevelStyle(1, title1style.getName());
           doc.isUpdateFields();
           doc.updateTableOfContents();

           //設置目錄的字體
           TextRange range = para.appendText("目錄");
           range.getCharacterFormat().setFontName("宋體");
           range.getCharacterFormat().setFontSize(16);
           para.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
           sec.getParagraphs().insert(0, para);
           for (int i = 0; i < sec.getParagraphs().getCount(); i++) {
               Paragraph p = sec.getParagraphs().get(i);
               if (p.getStyleName().equals("TOC1")) {
                   for (int j = 0; j < p.getChildObjects().getCount(); j++) {
                       if (p.getChildObjects().get(j).getDocumentObjectType().equals(DocumentObjectType.Text_Range)) {
                           TextRange range0 = (TextRange) p.getChildObjects().get(j);
                           range0.getCharacterFormat().setFontName("宋體");
                           range0.getCharacterFormat().setBold(false);
                       }
                   }
               }
           }
           //刪除頁眉
           for (int i = 1; i <= count; i++) {
               ParagraphCollection paragraphsHeader = doc.getSections().get(i).getHeadersFooters().getHeader().getParagraphs();
               if (paragraphsHeader.getCount() > 0) {
                   paragraphsHeader.removeAt(0);
               }
               doc.getSections().get(i).getHeadersFooters().getFirstPageFooter().getChildObjects().clear();
               doc.getSections().get(i).getHeadersFooters().getOddFooter().getChildObjects().clear();
           }

           //添加文字、頁碼域和總頁數域到段落
           Paragraph paragraph = doc.getSections().get(0).getHeadersFooters().getFirstPageFooter().addParagraph();
           paragraph.appendField("page number", FieldType.Field_Page);
           paragraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Right);

           Paragraph paragraph1 = doc.getSections().get(0).getHeadersFooters().getOddFooter().addParagraph();
           paragraph1.appendField("page number", FieldType.Field_Page);
           paragraph1.getFormat().setHorizontalAlignment(HorizontalAlignment.Right);
           
           //在轉換為pdf時出現字體便亂的情況,格式化字體后解決。如果不需要轉換為pdf,此操作可以刪除。
           for (int a = 1; a <= count; a++) {
               Section s = doc.getSections().get(a);
               //更新全文的字體(不包括tbale里的)
               for (int i = 1; i < s.getParagraphs().getCount(); i++) {
                   Paragraph p = s.getParagraphs().get(i);
                   for (int j = 0; j < p.getChildObjects().getCount(); j++) {
                       if (p.getChildObjects().get(j).getDocumentObjectType().equals(DocumentObjectType.Text_Range)) {
                           TextRange range0 = (TextRange) p.getChildObjects().get(j);
                           range0.getCharacterFormat().setFontName("宋體");
                           range0.getCharacterFormat().setBold(false);
                       }
                   }
               }
               TableCollection tables = s.getTables();
               //更新table里字體
               if (tables.getCount() > 0) {
                   updateTable(tables);
               }
           }

           //保存word文件
           doc.saveToFile(file, FileFormat.Docx);
           //轉換為pdf,轉換的代碼在下一篇文章里,使用的不是同一個jar包,因為這個jar對生成pdf沒有限制,准確的說是破*了。
           //WordToPdfUtil.wordToPdf(file, savePath + ".pdf");return true;
       }catch (Exception e){
           e.printStackTrace();
       }
       return false;
   }

 

可能每個人的需求都不一樣,不過你可以去查看相關Api或者官方demo進行修改。

 

此產品版本是免費版的,我也是在用免費,除了只能單次識別25張一下的word和生成pdf有限制,其他的功能都和正式版差不多。

如果你幾十個文檔,每個文檔幾頁,輸出出來超過25頁,那沒關系,依然可以使用。別單個文檔超過25頁即可。

如果公司使用,請支持購買收費版。

 

 

轉換pdf的文章路徑:

https://www.cnblogs.com/hunmeng/p/11983882.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM