先用ajaxFileUpload方法上传文件
$.ajaxFileUpload({
url : "<%=basePath%>apply/upFile.gxw",
fileElementId : 'upfile',
type: 'post',
secureuri : false,
data : {
"file" : ""
},
dataType : 'json',
success : function(data) {
$("#fileTd").find("a").remove();
$("#shangchuan").after("<a style='margin-left:20px;' href='<%=basePath%>"+data.relatPath+"' target='_blank'>"+data.oriName+"</a>");
$("#fileName").val(data.realName);
},
error : function(data) {
}
});
@RequestMapping("upFile.gxw")
@ResponseBody
public Map<String, String> upFile(HttpServletRequest request) throws IllegalStateException, IOException{
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
String rootDir = request.getRealPath("/");
String relatDir = File.separator+"qcenter"+File.separator+"resource"
+File.separator+"upload"+File.separator+"file";
//文件夹不存在则创建
File fdir = new File(rootDir+relatDir);
if (!fdir.exists()) { fdir.mkdirs(); }
String oriName = file.getOriginalFilename();
String newName = new Date().getTime()+"_"+oriName;
File tempFile = new File(fdir.getPath()+File.separator+newName);
file.transferTo(tempFile);
Map<String, String> result = new HashMap<String, String>();
result.put("oriName", oriName);
result.put("realName", tempFile.getName());
result.put("relatPath", relatDir+File.separator+newName);
return result;
}
文件已经存到tomcat里了,返回的有文件名,文件路径,tomcat里的文件名。
接着来处理已经上传好的文件,可以是word,excel,pdf格式。
原理是通过jacob来处理文件,将文件都先转成pdf格式,再将pdf格式分拆为一张张的图片,把这些对应关系存到一张表里,要能通过文件的id找到对应的png图片的id,这样就关联起来了。就实现了上传文件可以在浏览器里预览的目的了。
jacob自己去网上找,要区分32位和64位,里面有个dll文件要放到jdk目录里,一般都有说明。
excelToPdf工具类
package com.tec.base.util;
import java.io.*;
import java.util.Calendar;
import java.util.Date;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class ExcelToPdf {
private String path;
private String filePath;
private int index;
private String fileName;
public ExcelToPdf(String filePath,String path,int index,String fileName){
this.filePath=filePath;
this.path =path;
this.index = index;
this.fileName = fileName;
}
public void listAllFile(){
String outFile = "";
Dispatch sheet = null;
Dispatch sheets = null;
ActiveXComponent actcom=new ActiveXComponent("Excel.Application");
try{
actcom.setProperty("Visible", new Variant(false));
Dispatch excels=actcom.getProperty("Workbooks").toDispatch();
Dispatch excel = Dispatch.invoke(excels,"Open",Dispatch.Method, new Object[]{filePath,new Variant(false),new Variant(true)}, new int[9] ).toDispatch();
sheets= Dispatch.get(excel, "Sheets").toDispatch();
sheet = Dispatch.invoke(sheets, "Item", Dispatch.Get,new Object[] { new Integer(index) }, new int[1]).toDispatch();
Dispatch.call(sheet, "Activate");
Dispatch.call(sheet, "Select");
outFile = path+fileName+".pdf";
Dispatch.invoke(excel,"SaveAs",Dispatch.Method,new Object[]{outFile,new Variant(57), new Variant(false),
new Variant(57), new Variant(57),new Variant(false), new Variant(true),new Variant(57), new Variant(false),
new Variant(true), new Variant(false) },new int[1]);
Dispatch.call(excel, "Close",new Variant(false));
if(actcom!=null){
actcom.invoke("Quit",new Variant[]{});
actcom=null;
}
ComThread.Release();
File ftemp=new File(filePath);
ftemp.renameTo(new File(filePath));
ftemp=new File(filePath);
ftemp=null;
}catch(Exception es){
es.printStackTrace();
}
}
public String getDateStr(){
Calendar cl=Calendar.getInstance();
cl.setTime(new Date());
String str=cl.get(Calendar.YEAR)+""+(cl.get(Calendar.MONTH)+1)+""
+cl.get(Calendar.DATE)+""+cl.get(Calendar.HOUR)+""+cl.get(Calendar.MINUTE)+""
+cl.get(Calendar.SECOND);
return str;
}
}
wordToPdf工具类
package com.tec.base.util;
import java.io.File;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.qcsoft.qcenterframework.permission.util.JuelUtil;
public class JacobUtil {
// 8 代表word保存成html
public static final int WORD_HTML = 8;
static final int wdDoNotSaveChanges = 0;// 不保存待定的更改。
static final int wdFormatPDF = 17;// word转PDF 格式
public static void main(String[] args) {
String docfile = "D:\\2号炉后屏金相分析2017.2.28(1).docx";
String htmlfile = "D:\\2.pdf";
//JacobUtil.wordToHtml(docfile, htmlfile);
//JacobUtil.word2pdf(docfile, htmlfile);
JacobUtil.printPdf(docfile);
}
/**
* WORD转HTML
* @param docfile WORD文件全路径
* @param htmlfile 转换后HTML存放路径
*/
public static void wordToHtml(String docfile, String htmlfile)
{
// 启动word应用程序(Microsoft Office Word 2003)
ActiveXComponent app = new ActiveXComponent("Word.Application");
System.out.println("*****正在转换...*****");
try
{
// 设置word应用程序不可见
app.setProperty("Visible", new Variant(false));
// documents表示word程序的所有文档窗口,(word是多文档应用程序)
Dispatch docs = app.getProperty("Documents").toDispatch();
// 打开要转换的word文件
Dispatch doc = Dispatch.invoke(
docs,
"Open",
Dispatch.Method,
new Object[] { docfile, new Variant(false),
new Variant(true) }, new int[1]).toDispatch();
// 作为html格式保存到临时文件
Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
htmlfile, new Variant(WORD_HTML) }, new int[1]);
// 关闭word文件
Dispatch.call(doc, "Close", new Variant(false));
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
//关闭word应用程序
app.invoke("Quit", new Variant[] {});
}
System.out.println("*****转换完毕********");
}
public static void word2PDF(String inputFile,String pdfFile){
//打开word应用程序
ActiveXComponent app = new ActiveXComponent("Word.Application");
//设置word不可见,否则会弹出word界面
app.setProperty("Visible", false);
//获得word中所有打开的文档,返回Documents对象
Dispatch docs = app.getProperty("Documents").toDispatch();
//调用Documents对象中Open方法打开文档,并返回打开的文档对象Document
Dispatch doc = Dispatch.call(docs,
"Open",
inputFile,
false,
true
).toDispatch();
//调用Document对象的SaveAs方法,将文档保存为pdf格式
Dispatch.call(doc,
"ExportAsFixedFormat",
pdfFile,
wdFormatPDF //word保存为pdf格式
);
//关闭文档
Dispatch.call(doc, "Close",false);
//关闭word应用程序
app.invoke("Quit", 0);
}
public static boolean word2pdf(String source, String target) {
System.out.println("Word转PDF开始启动...");
long start = System.currentTimeMillis();
ActiveXComponent app = null;
try {
app = new ActiveXComponent("Word.Application");
app.setProperty("Visible", false);
Dispatch docs = app.getProperty("Documents").toDispatch();
System.out.println("打开文档:" + source);
Dispatch doc = Dispatch.call(docs, "Open", source, false, true).toDispatch();
System.out.println("转换文档到PDF:" + target);
File tofile = new File(target);
if (tofile.exists()) {
tofile.delete();
}
Dispatch.call(doc, "SaveAs", target, wdFormatPDF);
Dispatch.call(doc, "Close", false);
long end = System.currentTimeMillis();
System.out.println("转换完成,用时:" + (end - start) + "ms");
return true;
} catch (Exception e) {
System.out.println("Word转PDF出错:" + e.getMessage());
return false;
} finally {
if (app != null) {
app.invoke("Quit", wdDoNotSaveChanges);
}
}
}
public static void printPdf(String filePath){
System.out.println("开始打印");
ComThread.InitSTA();
ActiveXComponent word=new ActiveXComponent("Word.Application");
Dispatch doc=null;
Dispatch.put(word, "Visible", new Variant(false));
Dispatch docs=word.getProperty("Documents").toDispatch();
doc=Dispatch.call(docs, "Open", filePath).toDispatch();
try {
Dispatch.call(doc, "PrintOut");//打印
} catch (Exception e) {
e.printStackTrace();
System.out.println("打印失败");
}finally{
try {
if(doc!=null){
Dispatch.call(doc, "Close",new Variant(0));
}
} catch (Exception e2) {
e2.printStackTrace();
}
//释放资源
ComThread.Release();
}
}
}
pdfToPng方法
public void pdf2Pic(String pdfPath, String path,String headText,String type){
System.out.println("==开始PDF转换png==");
// ImageHead ih = new ImageHead();
Document document = new Document();
document.setFile(pdfPath);
float scale = 2.5f;//缩放比例
float rotation = 0f;//旋转角度
FileUtil fileUtil = new FileUtil();
String imgNameString = pdfPath.substring(pdfPath.lastIndexOf("\\")+1,pdfPath.lastIndexOf("."));
for (int i = 0; i < document.getNumberOfPages(); i++) {
BufferedImage image = (BufferedImage)document.getPageImage(i, GraphicsRenderingHints.SCREEN, org.icepdf.core.pobjects.Page.BOUNDARY_CROPBOX, rotation, scale);
RenderedImage rendImage = image;
try {
String imgName = imgNameString+ i + ".png";
File file = new File(path + imgName);
ImageIO.write(rendImage, "png", file);
String paths=path+imgNameString+i+"s.png";
cutImage(path+"/"+imgNameString+i+".png",paths,1320,1885,type);
// if(!StringUtil.isNullOrBlank(headText)&&0==i){
// System.out.println("paths:"+paths+"\nheadText:"+headText);
// ih.drawTextInImg(paths, paths, headText);
// }
permissionService.addWord2Png(imgNameString, imgNameString+i+"s.png");
fileUtil.deleteFile(path+imgName);
} catch (IOException e) {
e.printStackTrace();
}
image.flush();
}
document.dispose();
System.out.println("==结束PDF转换png==");
}
图片裁剪方法
/**
* 图片裁剪
* @param srcImageFile 图片裁剪地址
* @param result 图片输出文件夹
* @param destWidth 图片裁剪宽度
* @param destHeight 图片裁剪高度
*/
public final static void cutImage(String srcImageFile, String result,
int destWidth, int destHeight,String type) {
try {
Iterator iterator = ImageIO.getImageReadersByFormatName("PNG");/*PNG,BMP*/
ImageReader reader = (ImageReader)iterator.next();/*获取图片尺寸*/
InputStream inputStream = new FileInputStream(srcImageFile);
ImageInputStream iis = ImageIO.createImageInputStream(inputStream);
reader.setInput(iis, true);
ImageReadParam param = reader.getDefaultReadParam();
/**
* 构造一个新的 Rectangle,其左上角被指定为 (x,y),其宽度和高度由同名的参数指定。
* x - 左上角的 X 坐标。
* y - 左上角的 Y 坐标。
* width - Rectangle 的宽度
* height - Rectangle 的高度
*/
Rectangle rectangle ;
if(type!=null && "excel".equals(type)){
//excel取最大长宽
rectangle = new Rectangle(5,5,1480,2100);/*指定截取范围*/
}else{
rectangle = new Rectangle(80, 92, destWidth, destHeight);/*指定截取范围*/
}
param.setSourceRegion(rectangle);
BufferedImage bi = reader.read(0,param);
ImageIO.write(bi, "PNG", new File(result));
inputStream.close();
iis.close();
} catch (Exception e) {
e.printStackTrace();
//LOG.error("图片裁剪出现异常:"+e);
}
}