<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>
封装工具类
publicclassFileConvertUtils{privatestaticLogger logger=LogManager.getLogger(FileConvertUtils.class);publicstaticfinalStringAsposeLicense_Type_Words="Words";//AsposeLicense 类型 WordspublicstaticfinalStringAsposeLicense_Type_Cells="Cells";//AsposeLicense 类型 CellspublicstaticfinalStringAsposeLicense_Type_Slides="Slides";//AsposeLicense 类型 SlidespublicstaticfinalStringAsposeLicense_Type_Pdf="Pdf";//AsposeLicense 类型 Pdf//已经加载 License 的类型privatestaticMap<String,Boolean> loadedAsposeLicenseTypes=newConcurrentHashMap<>();publicstaticvoidloadAsposeLicense(String type)throwsException{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 =newcom.aspose.words.License();
license.setLicense(licenseIs);}elseif(AsposeLicense_Type_Cells.equals(type)){
licenseIs =FileConvertUtils.class.getClassLoader().getResourceAsStream("aspose-license.xml");com.aspose.cells.License license =newcom.aspose.cells.License();
license.setLicense(licenseIs);}elseif(AsposeLicense_Type_Slides.equals(type)){
licenseIs =FileConvertUtils.class.getClassLoader().getResourceAsStream("aspose-license.xml");com.aspose.slides.License license =newcom.aspose.slides.License();
license.setLicense(licenseIs);}elseif(AsposeLicense_Type_Pdf.equals(type)){
licenseIs =FileConvertUtils.class.getClassLoader().getResourceAsStream("aspose-license.xml");com.aspose.pdf.License license =newcom.aspose.pdf.License();
license.setLicense(licenseIs);}
loadedAsposeLicenseTypes.put(type,true);}}catch(Exception e){thrownewRuntimeException("加载aspose-license.xml出错",e);}finally{BaseUtils.clean(licenseIs);}}/**
* word 转 pdf
* @param wordFilePath word文件路径
* @param pdfFilePath pdf文件路径
* @param retainRevisions 是否保留修订备注等
*/publicstaticvoidwordToPDF(String wordFilePath,String pdfFilePath,boolean retainRevisions){FileOutputStream os =null;try{loadAsposeLicense(AsposeLicense_Type_Words);long old =System.currentTimeMillis();
os =newFileOutputStream(pdfFilePath);com.aspose.words.Document doc =newcom.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 =newcom.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);thrownewRuntimeException(e);}finally{BaseUtils.clean(os);}}/**
* word 转 pdf
* @param wordFile word文件
* @param pdfFile pdf文件
* @param retainRevisions 是否保留修订备注等
*/publicstaticvoidwordToPDF(File wordFile,File pdfFile,boolean retainRevisions){InputStream is =null;OutputStream os =null;try{loadAsposeLicense(AsposeLicense_Type_Words);
is =newFileInputStream(wordFile);
os =newFileOutputStream(pdfFile);long old =System.currentTimeMillis();com.aspose.words.Document doc =newcom.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 =newcom.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);thrownewRuntimeException(e);}finally{BaseUtils.clean(os,is);}}/**
* excel 转 pdf
* @param excelFilePath excel文件路径
* @param pdfFilePath pdf文件路径
* @param retainRevisions 是否保留修订备注等
*/publicstaticvoidexcelToPDF(String excelFilePath,String pdfFilePath,boolean retainRevisions){FileOutputStream os =null;try{loadAsposeLicense(AsposeLicense_Type_Cells);long old =System.currentTimeMillis();
os =newFileOutputStream(pdfFilePath);com.aspose.cells.Workbook excel =newcom.aspose.cells.Workbook(excelFilePath);if(!retainRevisions){
excel.acceptAllRevisions();//接受修订}// 创建一个 SaveOptions 实例,用于指定如何保存文档 可以设置字体嵌入等com.aspose.cells.PdfSaveOptions options =newcom.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);thrownewRuntimeException(e);}finally{BaseUtils.clean(os);}}/**
* excel 转 pdf
* @param excelFile excel文件
* @param pdfFile pdf文件
* @param retainRevisions 是否保留修订备注等
*/publicstaticvoidexcelToPDF(File excelFile,File pdfFile,boolean retainRevisions){InputStream is =null;OutputStream os =null;try{loadAsposeLicense(AsposeLicense_Type_Cells);
is =newFileInputStream(excelFile);
os =newFileOutputStream(pdfFile);com.aspose.cells.License license =newcom.aspose.cells.License();//必须调用加载license
license.setLicense((InputStream)null);long old =System.currentTimeMillis();com.aspose.cells.Workbook excel =newcom.aspose.cells.Workbook(is);if(!retainRevisions){
excel.acceptAllRevisions();//接受修订}// 创建一个 SaveOptions 实例,用于指定如何保存文档 可以设置字体嵌入等com.aspose.cells.PdfSaveOptions options =newcom.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);thrownewRuntimeException(e);}finally{BaseUtils.clean(os,is);}}/**
* ppt 转 pdf
* @param pptFilePath ppt文件路径
* @param pdfFilePath pdf文件路径
* @param retainRevisions 是否保留修订备注等
*/publicstaticvoidpptToPDF(String pptFilePath,String pdfFilePath,boolean retainRevisions){FileOutputStream os =null;try{loadAsposeLicense(AsposeLicense_Type_Slides);long old =System.currentTimeMillis();
os =newFileOutputStream(pdfFilePath);com.aspose.slides.Presentation ppt =newcom.aspose.slides.Presentation(pptFilePath);if(!retainRevisions){}// 创建一个 SaveOptions 实例,用于指定如何保存文档 可以设置字体嵌入等com.aspose.slides.PdfOptions options =newcom.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);thrownewRuntimeException(e);}finally{BaseUtils.clean(os);}}/**
* ppt 转 pdf
* @param pptFile ppt文件
* @param pdfFile pdf文件
* @param retainRevisions 是否保留修订备注等
*/publicstaticvoidpptToPDF(File pptFile,File pdfFile,boolean retainRevisions){InputStream is =null;OutputStream os =null;try{loadAsposeLicense(AsposeLicense_Type_Slides);
is =newFileInputStream(pptFile);
os =newFileOutputStream(pdfFile);long old =System.currentTimeMillis();com.aspose.slides.Presentation ppt =newcom.aspose.slides.Presentation(is);if(!retainRevisions){}// 创建一个 SaveOptions 实例,用于指定如何保存文档 可以设置字体嵌入等com.aspose.slides.PdfOptions options =newcom.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);thrownewRuntimeException(e);}finally{BaseUtils.clean(os,is);}}/**
* pdf 转 word
* @param pdfFilePath pdf文件路径
* @param wordFilePath word文件路径
* @param retainRevisions 是否保留修订备注等
*/publicstaticvoidpdfToWord(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 =newFileOutputStream(wordFilePath);
pdf =newcom.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);thrownewRuntimeException(e);}finally{BaseUtils.clean(os,pdf);}}/**
* ppt 转 pdf
* @param pdfFile word文件
* @param wordFile pdf文件
* @param retainRevisions 是否保留修订备注等
*/publicstaticvoidpdfToWord(File pdfFile,File wordFile,boolean retainRevisions){InputStream is =null;OutputStream os =null;com.aspose.pdf.Document pdf =null;try{loadAsposeLicense(AsposeLicense_Type_Pdf);
is =newFileInputStream(pdfFile);
os =newFileOutputStream(wordFile);long old =System.currentTimeMillis();
pdf =newcom.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);thrownewRuntimeException(e);}finally{BaseUtils.clean(os,pdf,is);}}/**
* word 替换书签
* @param wordFile 原word文件
* @param bmNameToContent 书签名称 对应 替换的内容 替换后删除书签
* @param bmNameToContent2 书签名称 对应 替换的内容 替换后不删除书签
*/publicstaticvoidsetBookMarkText(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=newFile(tmpDir,BaseUtils.getUUID(""));File newWordFile=newFile(dir,wordFile.getName());InputStream is =null;OutputStream os =null;try{if(!dir.exists()){
dir.mkdirs();}FileConvertUtils.loadAsposeLicense(FileConvertUtils.AsposeLicense_Type_Words);
is =newFileInputStream(wordFile);
os =newFileOutputStream(newWordFile);long old =System.currentTimeMillis();com.aspose.words.Document doc =newcom.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);thrownewRuntimeException(e);}finally{BaseUtils.clean(os,is);BaseUtils.deleteFile(newWordFile);BaseUtils.deleteFile(dir);}}/**
* pdf 加水印
* @param pdfFile 原pdf文件
*/publicstaticvoidaddWatermarkText(File pdfFile,String watermarkText,String tmpDir){if(StringUtils.isBlank(tmpDir)) tmpDir=System.getProperty("java.io.tmpdir");File dir=newFile(tmpDir,BaseUtils.getUUID(""));File newPdfFile=newFile(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 =newFileInputStream(pdfFile);
os =newFileOutputStream(newPdfFile);long old =System.currentTimeMillis();
pdfDocument =newcom.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 =newWatermarkArtifact();
artifact.setText(newFormattedText(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);thrownewRuntimeException(e);}finally{BaseUtils.clean(os,pdfDocument,is);BaseUtils.deleteFile(newPdfFile);BaseUtils.deleteFile(dir);}}}