在Java中使用Aspose對文檔操作示例


Aspose簡介

Aspose是一個商業.NET類庫,可以使得應用程序處理大量的文件任務。Aspose可以支持Doc,Docx,PDF,Excel 等格式的文件處理。我們可以通過使用Aspose生成、修改、轉換和打印文檔。
Aspose並非開源,所以在使用的時候需要獲取版權,否則在操作文檔中會顯示版權相關信息的水印。

版權注冊代碼如下

    /**
      * @Description TODO
      * @param licensePath 版權文件所在路徑
      * @Return void
      * @Author Mr.Walloce
      * @Date 2019/7/27 22:18
      */
    private static void setLicense(String licensePath) {
        try {
            InputStream inputStream = FileCustUtil.class.getClassLoader().getResourceAsStream(licensePath);
            License aposeLicense = new License();
            aposeLicense.setLicense(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

文檔轉換 -- word轉PDF

    /**
      * @Description TODO
      * @param inputPath  需要被轉換的word全路徑帶文件名
      * @param outPath 轉換之后pdf的全路徑帶文件名
      * @Return void
      * @Author Mr.Walloce
      * @Date 2019/7/27 13:47
      */
    public static void docToPdf(String inputPath, String outPath) {
        try {
            //word文檔
            Document doc = new Document(inputPath);

            //新建一個pdf文檔
            File file = new File(outPath);
            FileOutputStream os = new FileOutputStream(file);

            //保存為pdf文件,saveFormat取的是words包下的,值為:40
            doc.save(os, com.aspose.words.SaveFormat.PDF);
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

**
word文檔轉換為PDF文檔時,是將word中的內容完全轉換為PDF文檔,包括word中的圖片、表格等特殊的數據。
**

文檔轉換 -- excel轉PDF

    /**
      * @Description TODO
      * @param inputPath 需要被轉換的excel全路徑帶文件名
      * @param outPath 轉換之后pdf的全路徑帶文件名
      * @Return void
      * @Author Mr.Walloce
      * @Date 2019/7/27 13:48
      */
    public static void excelToPdf(String inputPath, String outPath) {
        /*if (!getLicense()) {
            return;
        }*/
        try {
            //Excel文件數據
            Workbook wb = new Workbook(inputPath);
            FileOutputStream fileOS = new FileOutputStream(new File(outPath));
            //保存為pdf文件,saveFormat取的是cells包下的,值為:13
            wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);
            fileOS.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

**
Excel表格數據轉換為PDF數據時,有多個sheet時會自動按sheet的順序將數據填充到PDF文檔中。每個sheet都會啟動一個新的頁,按順序拼接在后面。
**

word文檔拼接

    /**
      * @Description TODO 文檔拼接
      * @param mainDoc 主文檔
      * @param addDoc 要拼接的文檔
      * @param isPortrait 是否橫向拼接
      * @Return com.aspose.words.Document 返回拼接后新的文檔
      * @Author Mr.Walloce
      * @Date 2019/7/27 18:31
      */
    public static Document appendDocument(Document mainDoc, Document addDoc, boolean isPortrait) {

        String bookmark = "單位信息";
        DocumentBuilder builder = null;
        try {
            builder = new DocumentBuilder(mainDoc);
            BookmarkCollection bms = mainDoc.getRange().getBookmarks();
            Bookmark bm = bms.get(bookmark);
            if (bm != null) {
                builder.moveToBookmark(bookmark, true, false);
                builder.writeln();
                builder.getPageSetup().setPaperSize(PaperSize.A4);
                Node insertAfterNode = builder.getCurrentParagraph().getPreviousSibling();
                insertDocumentAfterNode(insertAfterNode, mainDoc, addDoc);
            }
            //builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
            if (isPortrait) {
                // 縱向紙張
                builder.getPageSetup().setOrientation(Orientation.PORTRAIT);
                //builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
            } else {
                // 橫向
                builder.getPageSetup().setOrientation(Orientation.LANDSCAPE);
            }
            builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
            // builder.insertBreak(BreakType.PAGE_BREAK);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return mainDoc;
    }

    /**
      * @Description 向書簽后插入文檔
      * @param mainDoc 主文檔
      * @param tobeInserted 拼接的文檔
      * @param bookmark 書簽
      * @Return com.aspose.words.Document
      * @Author Mr.Walloce
      * @Date 2019/7/27 18:33
      */
    private static Document insertDocumentAfterBookMark(Document mainDoc, Document tobeInserted, String bookmark)
            throws Exception {
        if (mainDoc == null) {
            return null;
        } else if (tobeInserted == null) {
            return mainDoc;
        } else {
            //構建新文檔
            DocumentBuilder mainDocBuilder = new DocumentBuilder(mainDoc);
            if (bookmark != null && bookmark.length() > 0) {
                //獲取到書簽
                BookmarkCollection bms = mainDoc.getRange().getBookmarks();
                Bookmark bm = bms.get(bookmark);
                if (bm != null) {
                    mainDocBuilder.moveToBookmark(bookmark, true, false);
                    mainDocBuilder.writeln();
                    //獲取到插入的位置
                    Node insertAfterNode = mainDocBuilder.getCurrentParagraph().getPreviousSibling();
                    insertDocumentAfterNode(insertAfterNode, mainDoc, tobeInserted);
                }
            } else {
                appendDoc(mainDoc, tobeInserted, true);
            }

            return mainDoc;
        }
    }

    /**
      * @Description TODO
      * @param insertAfterNode 插入的位置
      * @param mainDoc
      * @param srcDoc
      * @Return void
      * @Author Mr.Walloce
      * @Date 2019/7/27 14:51
      */
    private static void insertDocumentAfterNode(Node insertAfterNode, Document mainDoc, Document srcDoc)
            throws Exception {
        if (insertAfterNode.getNodeType() != 8 & insertAfterNode.getNodeType() != 5) {
            throw new Exception("The destination node should be either a paragraph or table.");
        } else {
            CompositeNode dstStory = insertAfterNode.getParentNode();

            while (null != srcDoc.getLastSection().getBody().getLastParagraph()
                    && !srcDoc.getLastSection().getBody().getLastParagraph().hasChildNodes()) {
                srcDoc.getLastSection().getBody().getLastParagraph().remove();
            }

            NodeImporter importer = new NodeImporter(srcDoc, mainDoc, 1);
            int sectCount = srcDoc.getSections().getCount();

            for (int sectIndex = 0; sectIndex < sectCount; ++sectIndex) {
                Section srcSection = srcDoc.getSections().get(sectIndex);
                int nodeCount = srcSection.getBody().getChildNodes().getCount();

                for (int nodeIndex = 0; nodeIndex < nodeCount; ++nodeIndex) {
                    Node srcNode = srcSection.getBody().getChildNodes().get(nodeIndex);
                    Node newNode = importer.importNode(srcNode, true);
                    dstStory.insertAfter(newNode, insertAfterNode);
                    insertAfterNode = newNode;
                }
            }

        }
    }

    /**
      * @Description 文檔拼接
      * @param dstDoc
      * @param srcDoc
      * @param includeSection
      * @Return void
      * @Author Mr.Walloce
      * @Date 2019/7/27 14:53
      */
    private static void appendDoc(Document dstDoc, Document srcDoc, boolean includeSection) throws Exception {
        if (includeSection) {
            Iterator<Section> var3 = srcDoc.getSections().iterator();
            while (var3.hasNext()) {
                Section srcSection = (Section) var3.next();
                Node dstNode = dstDoc.importNode(srcSection, true, 0);
                dstDoc.appendChild(dstNode);
            }
        } else {
            Node node = dstDoc.getLastSection().getBody().getLastParagraph();
            if (node == null) {
                node = new Paragraph(srcDoc);
                dstDoc.getLastSection().getBody().appendChild(node);
            }

            if (node.getNodeType() != 8 & node.getNodeType() != 5) {
                throw new Exception("Use appendDoc(dstDoc, srcDoc, true) instead of appendDoc(dstDoc, srcDoc, false)");
            }

            insertDocumentAfterNode(node, dstDoc, srcDoc);
        }

    }

**
文檔拼接主要是用於業務在不同地方生成的文檔根據需求拼接成一個完整的主文檔。
**


以上僅為學習內容,如內容有錯希望提醒指正!


免責聲明!

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



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