doc,excel,ppt转存pdf并预览

来源:互联网 发布:js 计算时间间隔 天 编辑:程序博客网 时间:2024/09/21 06:34

需要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


原创粉丝点击