aspose学习

引入jar

在这里插入图片描述

引入依赖

<!--
        进入jar目录及项目的outlib目录 执行
        mvn install:install-file -Dfile=aspose-words-21.11-jdk17p.jar -DgroupId=com.xysd.outlib -DartifactId=aspose-words -Dversion=21.11-jdk17p -Dpackaging=jar
        -->
        <dependency>
            <groupId>com.xysd.outlib</groupId>
            <artifactId>aspose-words</artifactId>
            <version>21.11-jdk17p</version>
        </dependency>
        <!--
        进入jar目录及项目的outlib目录 执行
        mvn install:install-file -Dfile=aspose-cells-21.11p.jar -DgroupId=com.xysd.outlib -DartifactId=aspose-cells -Dversion=21.11p -Dpackaging=jar
        -->
        <dependency>
            <groupId>com.xysd.outlib</groupId>
            <artifactId>aspose-cells</artifactId>
            <version>21.11p</version>
        </dependency>
        <!--
        进入jar目录及项目的outlib目录 执行
        mvn install:install-file -Dfile=aspose-slides-21.11-jdk16p.jar -DgroupId=com.xysd.outlib -DartifactId=aspose-slides -Dversion=21.11-jdk16p -Dpackaging=jar
        -->
        <dependency>
            <groupId>com.xysd.outlib</groupId>
            <artifactId>aspose-slides</artifactId>
            <version>21.11-jdk16p</version>
        </dependency>
        <!--
        进入jar目录及项目的outlib目录 执行
        mvn install:install-file -Dfile=aspose-pdf-21.11p.jar -DgroupId=com.xysd.outlib -DartifactId=aspose-pdf -Dversion=21.11p -Dpackaging=jar
        -->
        <dependency>
            <groupId>com.xysd.outlib</groupId>
            <artifactId>aspose-pdf</artifactId>
            <version>21.11p</version>
        </dependency>

指定证书

<License>
    <Data>
        <Products>
            <Product>Aspose.Total for Java</Product>
            <Product>Aspose.Words for Java</Product>
            <Product>Aspose.Cells for Java</Product>
            <Product>Aspose.Slides for Java</Product>
            <Product>Aspose.Pdf for Java</Product>
        </Products>
        <EditionType>Enterprise</EditionType>
        <SubscriptionExpiry>20991231</SubscriptionExpiry>
        <LicenseExpiry>20991231</LicenseExpiry>
        <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
    </Data>
    <Signature>
    sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=
    </Signature>
</License>

封装工具类

public class FileConvertUtils {
    private static Logger logger= LogManager.getLogger(FileConvertUtils.class);
    
    public static final String AsposeLicense_Type_Words="Words";//AsposeLicense 类型 Words
    public static final String AsposeLicense_Type_Cells="Cells";//AsposeLicense 类型 Cells
    public static final String AsposeLicense_Type_Slides="Slides";//AsposeLicense 类型 Slides
    public static final String AsposeLicense_Type_Pdf="Pdf";//AsposeLicense 类型 Pdf
    
    //已经加载 License 的类型
    private static Map<String,Boolean> loadedAsposeLicenseTypes=new ConcurrentHashMap<>();
    public static void loadAsposeLicense(String type) throws Exception {
        if(StringUtils.isBlank(type)) return;
        if(loadedAsposeLicenseTypes.containsKey(type)) {
            return;
        }
        InputStream licenseIs=null;
        try {
            synchronized(loadedAsposeLicenseTypes) {
                if(loadedAsposeLicenseTypes.containsKey(type)) {
                    return;
                }
                if(AsposeLicense_Type_Words.equals(type)) {
                    licenseIs = FileConvertUtils.class.getClassLoader().getResourceAsStream("aspose-license.xml");
                    com.aspose.words.License license = new com.aspose.words.License();
                    license.setLicense(licenseIs);
                }else if(AsposeLicense_Type_Cells.equals(type)) {
                    licenseIs = FileConvertUtils.class.getClassLoader().getResourceAsStream("aspose-license.xml");
                    com.aspose.cells.License license = new com.aspose.cells.License();
                    license.setLicense(licenseIs);
                }else if(AsposeLicense_Type_Slides.equals(type)) {
                    licenseIs = FileConvertUtils.class.getClassLoader().getResourceAsStream("aspose-license.xml");
                    com.aspose.slides.License license = new com.aspose.slides.License();
                    license.setLicense(licenseIs);
                }else if(AsposeLicense_Type_Pdf.equals(type)) {
                    licenseIs = FileConvertUtils.class.getClassLoader().getResourceAsStream("aspose-license.xml");
                    com.aspose.pdf.License license = new com.aspose.pdf.License();
                    license.setLicense(licenseIs);
                }
                loadedAsposeLicenseTypes.put(type, true);
            }
        } catch (Exception e) {
            throw new RuntimeException("加载aspose-license.xml出错",e);
        } finally {
            BaseUtils.clean(licenseIs);
        }
    }
    /**
     * word 转 pdf
     * @param wordFilePath word文件路径
     * @param pdfFilePath pdf文件路径
     * @param retainRevisions 是否保留修订备注等
     */
    public static void wordToPDF(String wordFilePath,String pdfFilePath,boolean retainRevisions){
        FileOutputStream os = null;
        try {
            loadAsposeLicense(AsposeLicense_Type_Words);
            long old = System.currentTimeMillis();
            os = new FileOutputStream(pdfFilePath);
            com.aspose.words.Document doc = new com.aspose.words.Document(wordFilePath);
            if(!retainRevisions) {
                doc.acceptAllRevisions();//接受修订
                // 遍历并删除备注 不会保存至源文件的
                com.aspose.words.NodeCollection<com.aspose.words.Comment> comments = doc.getChildNodes(com.aspose.words.NodeType.COMMENT, true);
                for (com.aspose.words.Comment comment : comments) {
                    comment.remove();
                }
            }
            // 创建一个 SaveOptions 实例,用于指定如何保存文档 可以设置字体嵌入等
            com.aspose.words.PdfSaveOptions options = new com.aspose.words.PdfSaveOptions();
            //设置是否将完整字体嵌入PDF文件中
            options.setEmbedFullFonts(true);
            doc.save(os, options);
//            doc.save(os, com.aspose.words.SaveFormat.PDF);
            long now = System.currentTimeMillis();
            logger.info("FileConvertUtils.wordToPDF 共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时
        } catch (Exception e) {
            logger.error("word转pdf失败,"+e.getMessage(),e);
            throw new RuntimeException(e);
        } finally {
            BaseUtils.clean(os);
        }
    }
    /**
     * word 转 pdf
     * @param wordFile word文件
     * @param pdfFile pdf文件
     * @param retainRevisions 是否保留修订备注等
     */
    public static void wordToPDF(File wordFile,File pdfFile,boolean retainRevisions){
        InputStream is = null;
        OutputStream os = null;
        try {
            loadAsposeLicense(AsposeLicense_Type_Words);
            is = new FileInputStream(wordFile);
            os = new FileOutputStream(pdfFile);
            long old = System.currentTimeMillis();
            com.aspose.words.Document doc = new com.aspose.words.Document(is);
            if(!retainRevisions) {
                doc.acceptAllRevisions();//接受修订
                // 遍历并删除备注 不会保存至源文件的
                com.aspose.words.NodeCollection<com.aspose.words.Comment> comments = doc.getChildNodes(com.aspose.words.NodeType.COMMENT, true);
                for (com.aspose.words.Comment comment : comments) {
                    comment.remove();
                }
            }
            // 创建一个 SaveOptions 实例,用于指定如何保存文档 可以设置字体嵌入等
            com.aspose.words.PdfSaveOptions options = new com.aspose.words.PdfSaveOptions();
            //设置是否将完整字体嵌入PDF文件中
            options.setEmbedFullFonts(true);
            doc.save(os, options);
//            doc.save(os, com.aspose.words.SaveFormat.PDF);
            long now = System.currentTimeMillis();
            logger.info("FileConvertUtils.wordToPDF 共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时
        } catch (Exception e) {
            logger.error("word转pdf失败,"+e.getMessage(),e);
            throw new RuntimeException(e);
        } finally {
            BaseUtils.clean(os,is);
        }
    }
    
    
    /**
     * excel 转 pdf
     * @param excelFilePath excel文件路径
     * @param pdfFilePath pdf文件路径
     * @param retainRevisions 是否保留修订备注等
     */
    public static void excelToPDF(String excelFilePath,String pdfFilePath,boolean retainRevisions){
        FileOutputStream os = null;
        try {
            loadAsposeLicense(AsposeLicense_Type_Cells);
            long old = System.currentTimeMillis();
            os = new FileOutputStream(pdfFilePath);
            com.aspose.cells.Workbook excel = new com.aspose.cells.Workbook(excelFilePath);
            if(!retainRevisions) {
                excel.acceptAllRevisions();//接受修订
            }
            // 创建一个 SaveOptions 实例,用于指定如何保存文档 可以设置字体嵌入等
            com.aspose.cells.PdfSaveOptions options = new com.aspose.cells.PdfSaveOptions();
            excel.save(os, options);
            long now = System.currentTimeMillis();
            logger.info("FileConvertUtils.excelToPDF 共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时
        } catch (Exception e) {
            logger.error("excel转pdf失败,"+e.getMessage(),e);
            throw new RuntimeException(e);
        } finally {
            BaseUtils.clean(os);
        }
    }
    /**
     * excel 转 pdf
     * @param excelFile excel文件
     * @param pdfFile pdf文件
     * @param retainRevisions 是否保留修订备注等
     */
    public static void excelToPDF(File excelFile,File pdfFile,boolean retainRevisions){
        InputStream is = null;
        OutputStream os = null;
        try {
            loadAsposeLicense(AsposeLicense_Type_Cells);
            is = new FileInputStream(excelFile);
            os = new FileOutputStream(pdfFile);
            com.aspose.cells.License license = new com.aspose.cells.License();
            //必须调用加载license
            license.setLicense((InputStream)null);
            long old = System.currentTimeMillis();
            com.aspose.cells.Workbook excel = new com.aspose.cells.Workbook(is);
            if(!retainRevisions) {
                excel.acceptAllRevisions();//接受修订
            }
            // 创建一个 SaveOptions 实例,用于指定如何保存文档 可以设置字体嵌入等
            com.aspose.cells.PdfSaveOptions options = new com.aspose.cells.PdfSaveOptions();
            excel.save(os, options);
            long now = System.currentTimeMillis();
            logger.info("FileConvertUtils.excelToPDF 共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时
        } catch (Exception e) {
            logger.error("excel转pdf失败,"+e.getMessage(),e);
            throw new RuntimeException(e);
        } finally {
            BaseUtils.clean(os,is);
        }
    }
    
    
    /**
     * ppt 转 pdf
     * @param pptFilePath ppt文件路径
     * @param pdfFilePath pdf文件路径
     * @param retainRevisions 是否保留修订备注等
     */
    public static void pptToPDF(String pptFilePath,String pdfFilePath,boolean retainRevisions){
        FileOutputStream os = null;
        try {
            loadAsposeLicense(AsposeLicense_Type_Slides);
            long old = System.currentTimeMillis();
            os = new FileOutputStream(pdfFilePath);
            com.aspose.slides.Presentation ppt = new com.aspose.slides.Presentation(pptFilePath);
            if(!retainRevisions) {
                
            }
            // 创建一个 SaveOptions 实例,用于指定如何保存文档 可以设置字体嵌入等
            com.aspose.slides.PdfOptions options = new com.aspose.slides.PdfOptions();
            //设置是否将完整字体嵌入PDF文件中
            options.setEmbedFullFonts(true);
            ppt.save(os, com.aspose.slides.SaveFormat.Pdf, options);
            long now = System.currentTimeMillis();
            logger.info("FileConvertUtils.pptToPDF 共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时
        } catch (Exception e) {
            logger.error("ppt转pdf失败,"+e.getMessage(),e);
            throw new RuntimeException(e);
        } finally {
            BaseUtils.clean(os);
        }
    }
    /**
     * ppt 转 pdf
     * @param pptFile ppt文件
     * @param pdfFile pdf文件
     * @param retainRevisions 是否保留修订备注等
     */
    public static void pptToPDF(File pptFile,File pdfFile,boolean retainRevisions){
        InputStream is = null;
        OutputStream os = null;
        try {
            loadAsposeLicense(AsposeLicense_Type_Slides);
            is = new FileInputStream(pptFile);
            os = new FileOutputStream(pdfFile);
            long old = System.currentTimeMillis();
            com.aspose.slides.Presentation ppt = new com.aspose.slides.Presentation(is);
            if(!retainRevisions) {
                
            }
            // 创建一个 SaveOptions 实例,用于指定如何保存文档 可以设置字体嵌入等
            com.aspose.slides.PdfOptions options = new com.aspose.slides.PdfOptions();
            //设置是否将完整字体嵌入PDF文件中
            options.setEmbedFullFonts(true);
            ppt.save(os, com.aspose.slides.SaveFormat.Pdf, options);
            long now = System.currentTimeMillis();
            logger.info("FileConvertUtils.pptToPDF 共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时
        } catch (Exception e) {
            logger.error("ppt转pdf失败,"+e.getMessage(),e);
            throw new RuntimeException(e);
        } finally {
            BaseUtils.clean(os,is);
        }
    }
    
    
    /**
     * pdf 转 word
     * @param pdfFilePath pdf文件路径
     * @param wordFilePath word文件路径
     * @param retainRevisions 是否保留修订备注等
     */
    public static void pdfToWord(String pdfFilePath,String wordFilePath,boolean retainRevisions){
        FileOutputStream os = null;
        com.aspose.pdf.Document pdf = null;
        try {
            loadAsposeLicense(AsposeLicense_Type_Pdf);
            long old = System.currentTimeMillis();
            os = new FileOutputStream(wordFilePath);
            pdf = new com.aspose.pdf.Document(pdfFilePath);
            if(!retainRevisions) {
                
            }
            // 创建一个 SaveOptions 实例,用于指定如何保存文档 可以设置字体嵌入等
//            com.aspose.pdf.DocSaveOptions options = new com.aspose.pdf.DocSaveOptions();
            pdf.save(os, com.aspose.pdf.SaveFormat.DocX);
            long now = System.currentTimeMillis();
            logger.info("FileConvertUtils.pdfToWord 共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时
        } catch (Exception e) {
            logger.error("pdf转Word失败,"+e.getMessage(),e);
            throw new RuntimeException(e);
        } finally {
            BaseUtils.clean(os,pdf);
        }
    }
    /**
     * ppt 转 pdf
     * @param pdfFile word文件
     * @param wordFile pdf文件
     * @param retainRevisions 是否保留修订备注等
     */
    public static void pdfToWord(File pdfFile,File wordFile,boolean retainRevisions){
        InputStream is = null;
        OutputStream os = null;
        com.aspose.pdf.Document pdf = null;
        try {
            loadAsposeLicense(AsposeLicense_Type_Pdf);
            is = new FileInputStream(pdfFile);
            os = new FileOutputStream(wordFile);
            long old = System.currentTimeMillis();
            pdf = new com.aspose.pdf.Document(is);
            if(!retainRevisions) {
                
            }
            // 创建一个 SaveOptions 实例,用于指定如何保存文档 可以设置字体嵌入等
//            com.aspose.pdf.DocSaveOptions options = new com.aspose.pdf.DocSaveOptions();
            pdf.save(os, com.aspose.pdf.SaveFormat.DocX);
            long now = System.currentTimeMillis();
            logger.info("FileConvertUtils.pdfToWord 共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时
        } catch (Exception e) {
            logger.error("pdf转Word失败,"+e.getMessage(),e);
            throw new RuntimeException(e);
        } finally {
            BaseUtils.clean(os,pdf,is);
        }
    }
     /**
     * word 替换书签
     * @param wordFile 原word文件
     * @param bmNameToContent 书签名称 对应 替换的内容 替换后删除书签
     * @param bmNameToContent2 书签名称 对应 替换的内容 替换后不删除书签
     */
    public static void setBookMarkText(File wordFile, Map<String,String> bmNameToContent,
            Map<String,String> bmNameToContent2, String tmpDir
            ){
        if(MapUtils.isEmpty(bmNameToContent)&&MapUtils.isEmpty(bmNameToContent2)) {
            return;
        }
        if(StringUtils.isBlank(tmpDir)) tmpDir=System.getProperty("java.io.tmpdir");
        File dir=new File(tmpDir, BaseUtils.getUUID(""));
        File newWordFile=new File(dir,wordFile.getName());
        InputStream is = null;
        OutputStream os = null;
        try {
            if(!dir.exists()) {
                dir.mkdirs();
            }
            FileConvertUtils.loadAsposeLicense(FileConvertUtils.AsposeLicense_Type_Words);
            is = new FileInputStream(wordFile);
            os = new FileOutputStream(newWordFile);
            long old = System.currentTimeMillis();
            com.aspose.words.Document doc = new com.aspose.words.Document(is);
            boolean hasChange=false;
            BookmarkCollection bookmarks = doc.getRange().getBookmarks();
            //无书签 跳出
            if(bookmarks.getCount()<=0) return;
            // 获取指定的书签
            if(MapUtils.isNotEmpty(bmNameToContent)) {
                for (Map.Entry<String,String> en : bmNameToContent.entrySet()) {
                    Bookmark bookmark = bookmarks.get(en.getKey());
                    if(bookmark==null) continue;
                    // 更新书签内容
                    bookmark.setText(en.getValue()==null?"":en.getValue());
                    bookmarks.remove(bookmark);
                    hasChange=true;
                }
            }
            if(MapUtils.isNotEmpty(bmNameToContent2)) {
                for (Map.Entry<String,String> en : bmNameToContent2.entrySet()) {
                    Bookmark bookmark = bookmarks.get(en.getKey());
                    if(bookmark==null) continue;
                    // 更新书签内容
                    bookmark.setText(en.getValue()==null?"":en.getValue());
                    hasChange=true;
                }
            }
            //无更改 则不处理 返回原文件
            if(!hasChange) return;
            
            if(wordFile.getName().toLowerCase().endsWith(".doc")) {
                doc.save(os, com.aspose.words.SaveFormat.DOC);
            }else {
                doc.save(os, com.aspose.words.SaveFormat.DOCX);
            }
            BaseUtils.clean(os,is);
            os=null;
            is=null;
            long now = System.currentTimeMillis();
            logger.info("WordOperationUtils.setBookMarkText 共耗时:" + ((now - old) / 1000.0) + "秒");
            BaseUtils.copyFile(newWordFile, wordFile);
        } catch (Exception e) {
            logger.error("word转设置书签内容失败,"+e.getMessage(),e);
            throw new RuntimeException(e);
        } finally {
            BaseUtils.clean(os,is);
            BaseUtils.deleteFile(newWordFile);
            BaseUtils.deleteFile(dir);
        }
    }
    /**
     * pdf 加水印
     * @param pdfFile 原pdf文件
     */
    public static void addWatermarkText(File pdfFile, String watermarkText, String tmpDir){
        if(StringUtils.isBlank(tmpDir)) tmpDir=System.getProperty("java.io.tmpdir");
        File dir=new File(tmpDir, BaseUtils.getUUID(""));
        File newPdfFile=new File(dir,pdfFile.getName());
        InputStream is = null;
        OutputStream os = null;
        com.aspose.pdf.Document pdfDocument = null;
        try {
            if(!dir.exists()) {
                dir.mkdirs();
            }
            FileConvertUtils.loadAsposeLicense(FileConvertUtils.AsposeLicense_Type_Pdf);
            is = new FileInputStream(pdfFile);
            os = new FileOutputStream(newPdfFile);
            long old = System.currentTimeMillis();
            pdfDocument = new com.aspose.pdf.Document(is);
            
//            // 创建水印字符串
//            TextStamp textStamp = new TextStamp(watermarkText);
            //背景水印
            textStamp.setBackground(true);
            //水印坐标
            textStamp.setXIndent(100);
            textStamp.setYIndent(100);
//            //水印倾斜度
//            textStamp.setRotateAngle(50);
//            
//            // 设置水印的 字体大小、颜色等
//            textStamp.getTextState().setFontSize(36);
//            textStamp.getTextState().setFont(FontRepository.findFont("Arial"));
//            textStamp.getTextState().setFontSize(34.0F);
//            textStamp.getTextState().setFontStyle(FontStyles.Italic);
//            textStamp.getTextState().setForegroundColor(Color.getLightGray());
//            // 设置水印的透明度
//            textStamp.setOpacity(0.5);
            
            // 在 PDF 的每一页上添加水印
            for (Page page : pdfDocument.getPages()) {
                WatermarkArtifact artifact = new WatermarkArtifact();
                artifact.setText(new FormattedText(watermarkText,java.awt.Color.GRAY,FontStyle.CourierOblique,EncodingType.Identity_h,true,72.0F)); 
//                artifact.setImage(is);
                artifact.setArtifactHorizontalAlignment(HorizontalAlignment.Center);
                artifact.setArtifactVerticalAlignment(VerticalAlignment.Center);
                artifact.setRotation(45);
                artifact.setOpacity(0.3);
                artifact.setBackground(false);
                page.getArtifacts().add(artifact);
            }
            // 保存带有水印的 PDF 文档
            pdfDocument.save(os);
            
            BaseUtils.clean(os,is);
            os=null;
            is=null;
            long now = System.currentTimeMillis();
            logger.info("PdfOperationUtils.addWatermarkText 共耗时:" + ((now - old) / 1000.0) + "秒");
            BaseUtils.copyFile(newPdfFile, pdfFile);
        } catch (Exception e) {
            logger.error("pdf加水印失败,"+e.getMessage(),e);
            throw new RuntimeException(e);
        } finally {
            BaseUtils.clean(os,pdfDocument,is);
            BaseUtils.deleteFile(newPdfFile);
            BaseUtils.deleteFile(dir);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值