doc,excel,ppt转存pdf并预览
需要jar包:
下載aspose-words-15.8.0-jdk16.jar包http://pan.baidu.com/s/1nvbJwnv
 
下載aspose-cells-8.5.2.jar包?http://pan.baidu.com/s/1kUBzsQ7
 
下載aspose.slides-15.9.0.jar包?http://pan.baidu.com/s/1jH3ZNbK
 
預覽插件:
https://github.com/mozilla/pdf.js
 
遇到問題:
1,上傳文件org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoClassDefFoundError: com/aspose/words/License
解決:tomcat中bin目錄下catalina.sh文件中,增加?JAVA_OPTS="-Djava.awt.headless=true" ,加完重啟。
因為是一個項目調另一個項目,調用項目的aspose的jar包上傳有問題,重新上傳。
2,上傳文件內存溢出?14:19:11.569 [startQuertz_QuartzSchedulerThread] DEBUG o.quartz.core.QuartzSchedulerThread - batch acquisition of 0 triggers
 14:19:14.159 [http-bio-8081-exec-2] DEBUG o.s.w.m.c.CommonsMultipartResolver - Cleaning up multipart file [file] with original filename [aaa.docx], stored at [/xebest/tomcat-manager/work/Catalina/localhost/xe-manager/upload_5f4a16cc_15c1a35c502__8000_00000000.tmp]
 14:19:14.525 [http-bio-8081-exec-2] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
 Exception in thread "http-bio-8081-exec-2"?
 Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread "http-bio-8081-exec-2"
 Exception in thread "http-bio-8081-exec-1"?
解決:
#export JAVA_OPTS="-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=1090,server=y,suspend=n -Djava.awt.headless=true"
JAVA_OPTS="-server -Xms1024m -Xmx1024m -XX:PermSize=64M -XX:MaxNewSize=512m -XX:MaxPermSize=256m -Djava.awt.headless=true"
3, http://ip:port/projectName/js/pdf/web/viewer.html?file=pdf/aaa.pdf 訪問不到解決:解除攔截
項目web.xml 文件添加
<servlet-mapping>
 <servlet-name>default</servlet-name>
 <url-pattern>*.html</url-pattern>
 ? ?</servlet-mapping>
仍訪問不到 ? ?
解決:tomcat/conf/context.xml添加<Context allowLinking="true">
4,doc轉成的pdf文件亂碼(其他文件轉pdf不亂碼)
解決:
(1),代碼里設置轉換編碼格式;
(2)tomcat設置編碼格式;tomcat/conf/server.xml<Connector port="8010" protocol="AJP/1.3" redirectPort="8444" URIEncoding="UTF-8" />
(3)設置linux系統字體;
復制C:\Windows\fonts下字體到?/usr/share/Fonts。(此處為中文字體即可)
cd /usr/share/fonts/ #進入字體庫文件夾
 
mkdir fonttmp #創建自己使用的字體庫文件夾
chmod 755 /usr/share/fonts/windows/* ? ? #更改這些字體庫的權限
 
cd fonttmp #進行字體庫
 
cp *.ttc,cp *.ttf #copy windows下的字體文件 (ttc和ttf)或支持中文的字體文件(ttc和ttf)到此文件夾下
 
mkfontdir #生成字體查詢文件
 
mkfontscale #生成scale文件
 
fc-cache #掃描字體目錄并生成字體信息的緩存
 
代碼如下:
license.xml文件
<License>
 ? <Data>
 ? ? <Products>
 ? ? ? <Product>Aspose.Total for Java</Product>
 ? ? ? <Product>Aspose.Words 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>
 
DocToPdfUtil.java
 
 
package com.xebest.common.util;
 
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.InputStream;
 import com.aspose.words.Document;
 import com.aspose.words.License;
 import com.aspose.words.SaveFormat;
 
 public class DocToPdfUtil {
 
 // word轉pdf
 public static boolean getLicense() {
 boolean result = false;
 try {
 InputStream is = DocToPdfUtil.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml應放在..\WebRoot\WEB-INF\classes路徑下
 License aposeLic = new License();
 aposeLic.setLicense(is);
 result = true;
 } catch (Exception e) {
 e.printStackTrace();
 }
 return result;
 }
 
 public static void docToPdf(String fromUrl,String toUrl) {
 
 
 if (!getLicense()) { // 驗證License 若不驗證則轉化出的pdf文檔會有水印產生
 return;
 }
 try {
 //long old = System.currentTimeMillis();
 File file = new File(toUrl); // 新建一個空白pdf文檔
 FileOutputStream os = new FileOutputStream(file);
 Document doc = new Document(fromUrl); // Address是將要被轉化的word文檔
 doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML,
 // OpenDocument, PDF, EPUB, XPS, SWF
 // 相互轉換
 os.flush();
 os.close();
 // long now = System.currentTimeMillis();
 // System.out.println("共耗時:" + ((now - old) / 1000.0) + "秒"); // 轉化用時
 } catch (Exception e) {
 e.printStackTrace();
 }
 }
 
 }
 
 
ExcelToPdf.java
 
 
package com.xebest.common.util;
 
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.InputStream;
 import com.aspose.cells.License;
 import com.aspose.cells.SaveFormat;
 import com.aspose.cells.Workbook;
 
 public class ExcelToPdf {
 
 // excel轉pdf
 public static boolean getLicense() {
 boolean result = false;
 try {
 InputStream is = DocToPdfUtil.class.getClassLoader().getResourceAsStream("license.xml");?
 License aposeLic = new License();
 aposeLic.setLicense(is);
 result = true;
 } catch (Exception e) {
 e.printStackTrace();
 }
 return result;
 }
 
 public static void excelToPdf(String fromUrl,String toUrl) {
 
 if (!getLicense()) { // 驗證License 若不驗證則轉化出的pdf文檔會有水印產生
 return;
 }
 try {
 File pdfFile = new File(toUrl);// 輸出路徑
 Workbook wb = new Workbook(fromUrl);// 原始excel路徑
 FileOutputStream fileOS = new FileOutputStream(pdfFile);
 wb.save(fileOS, SaveFormat.PDF);
 fileOS.flush();
 fileOS.close();
 } catch (Exception e) {
 e.printStackTrace();
 }
 }
 }
 
 
PptToPdf.java
 
package com.xebest.common.util;
 
 import java.io.File;
 import java.io.FileOutputStream;
 import java.io.InputStream;
 import com.aspose.slides.License;
 import com.aspose.slides.Presentation;
 import com.aspose.slides.SaveFormat;
 
 public class PptToPdf {
 
 // ppt轉pdf
 public static boolean getLicense() {
 boolean result = false;
 try {
 InputStream is = DocToPdfUtil.class.getClassLoader().getResourceAsStream("license.xml");?
 License aposeLic = new License();
 aposeLic.setLicense(is);
 result = true;
 } catch (Exception e) {
 e.printStackTrace();
 }
 return result;
 }
 
 public static void pptToPdf(String fromUrl,String toUrl) {
 if (!getLicense()) { // 驗證License 若不驗證則轉化出的pdf文檔會有水印產生
 return;
 }
 try {
 // long old = System.currentTimeMillis();
 File file = new File(toUrl);// 輸出pdf路徑
 Presentation pres = new Presentation(fromUrl);// 輸入pdf路徑
 FileOutputStream fileOS = new FileOutputStream(file);
 pres.save(fileOS, SaveFormat.Pdf);
 fileOS.flush();
 fileOS.close();
 // long now = System.currentTimeMillis();
 // System.out.println("共耗時:" + ((now - old) / 1000.0) + "秒\n\n" +
 // "文件保存在:" + file.getPath()); //轉化過程耗時
 } catch (Exception e) {
 e.printStackTrace();
 }
 }
 }
 
調用
@RequestMapping("uploadFile")
 public void uploadFile(@RequestParam(value="file",required=false) MultipartFile file)throws IOException {
 String filePath=file==null?null:file.getOriginalFilename();
 String str = "nofile";
 String showStr = "nofile";
 JSONObject json=new JSONObject();
 if (StringUtils.isNotBlank(filePath)) {
 String fileSuffixName=filePath.substring(filePath.lastIndexOf(".")+1).toLowerCase();
 if (StringUtils.isNotBlank(fileSuffixName)&&("jpg".equals(fileSuffixName)
 || "jpeg".equals(fileSuffixName)|| "png".equals(fileSuffixName)
 || "bmp".equals(fileSuffixName)|| "doc".equals(fileSuffixName)
 || "docx".equals(fileSuffixName)|| "xlsx".equals(fileSuffixName)
 || "xls".equals(fileSuffixName)|| "pdf".equals(fileSuffixName))) {
 try {
 str=doUpload(file);
 showStr = str;
 if("doc".equals(fileSuffixName) || "docx".equals(fileSuffixName)
 ||"xlsx".equals(fileSuffixName) || "xls".equals(fileSuffixName)
 ||"pdf".equals(fileSuffixName)){
 if(!"pdf".equals(fileSuffixName)){
 showStr = fileSuffixName + "pdf";
 }
 json.put("type", 1);
 }else{
 json.put("type", 2);
 }
 }catch (IOException e) {
 log.info("上傳附件出錯BrokerageController+uploadFile:",e);
 }
 }
 }
 json.put("fileUrl", str);
 json.put("showUrl", showStr);
 sendAjaxResponseForHtml(response,json);
 /*PrintWriter pw = null;
 try {
 response.setCharacterEncoding("UTF-8");
 //response.setContentType("text/html");
 response.setContentType("text/html;charset=utf-8");
 pw=response.getWriter();//{"reUrl":["pic.xebest.com/product/245/400/29bca1a343fe495e835fce762ce09e7e.jpg"],"recode":0}
 pw.print(str);
 pw.print(JSONObject.toJSON(json));
 } catch (IOException e) {
 e.printStackTrace();
 }finally{
 pw.flush();
 pw.close();
 }*/
 }
 
 public String doUpload(MultipartFile file)throws IOException{
 String returnStr = "nofile";
 String filePath=file==null?null:file.getOriginalFilename();
 String fromUrl = "nofile";
 String targetPath = ImagesConfInit.getStringValue("files_path");
 File targetURL = new File(targetPath);
 if (!targetURL.exists())
 targetURL.mkdirs();
 
 if (StringUtils.isNotBlank(filePath)) {
 String fileSuffixName=filePath.substring(filePath.lastIndexOf(".")+1);
 if(StringUtils.isNotBlank(fileSuffixName)){
 fromUrl = targetPath+filePath;
 File newFile = new File(fromUrl);
 try {
 file.transferTo(newFile);
 log.info("文件路徑----------------->"+targetPath+filePath);
 returnStr = targetPath+filePath.substring(0,filePath.lastIndexOf(".")+1)+"pdf";
 if(fileSuffixName.toLowerCase().equals("doc")
 || fileSuffixName.toLowerCase().equals("docx")){
 DocToPdfUtil.docToPdf(fromUrl, returnStr);
 returnStr = filePath.substring(0,filePath.lastIndexOf(".")+1)+"pdf";
 }else if(fileSuffixName.toLowerCase().equals("xlsx")
 || fileSuffixName.toLowerCase().equals("xls")){
 ExcelToPdf.excelToPdf(fromUrl, returnStr);
 returnStr = filePath.substring(0,filePath.lastIndexOf(".")+1)+"pdf";
 }else{
 returnStr = filePath;
 }
 }catch (IOException e) {
 log.info(fromUrl+"上傳附件出錯BrokerageController+uploadFile+doUpload:",e);
 }
 }
 }
 return returnStr;
 }
 
 @RequestMapping("showFile")
 public void showFile(String fileUrl){
 int type = 0;//1,pdf;2,圖片;0,失敗
 JSONObject json=new JSONObject();
 String showUrl ="nopic";
 String fileSuffixName=fileUrl.substring(fileUrl.lastIndexOf(".")+1).toLowerCase();
 if(StringUtils.isNotBlank(fileSuffixName)&&?
 ("doc".equals(fileSuffixName) || "docx".equals(fileSuffixName)
 ||"xlsx".equals(fileSuffixName) || "xls".equals(fileSuffixName)
 ||"pdf".equals(fileSuffixName))){
 if(!"pdf".equals(fileSuffixName)){
 showUrl = fileSuffixName + "pdf";
 }else{
 showUrl = fileUrl;
 }
 type = 1;
 }else{
 type = 2;
 showUrl = fileUrl;
 }
 json.put("type", type);
 json.put("showUrl", showUrl);
 sendAjaxResponseForHtml(response,json);
 }
參考文章:感謝各位大神文章的指點,原文鏈接如下
http://www.cnblogs.com/qiwu1314/p/6101400.html
http://www.cnblogs.com/qiwu1314/p/6121696.html
 
http://www.cnblogs.com/qiwu1314/p/6121649.html
 
http://blog.csdn.net/iphone4grf/article/details/46376935
 
http://blog.csdn.net/nantian321/article/details/51200180
 
http://blog.csdn.net/shanelooli/article/details/7212812
http://www.th7.cn/Program/java/201606/878222.shtml
 
 
總結
以上是生活随笔為你收集整理的doc,excel,ppt转存pdf并预览的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: python 进程池不足_python
 - 下一篇: 前端:QuickJS到底能干什么