poi在线预览office

2019-08-06 17:16:15 u013897140 阅读数 88

java实现在线预览
- -之poi实现word、excel、ppt转html
###简介
java实现在线预览功能是一个大家在工作中也许会遇到的需求,如果公司有钱,直接使用付费的第三方软件或者云在线预览服务就可以了,例如永中office、office web 365(http://www.officeweb365.com/)他们都有云在线预览服务,就是要钱0.0
如果想要免费的,可以用openoffice,还需要借助其他的工具(例如swfTools、FlexPaper等)才行,可参考这篇文章http://blog.csdn.net/z69183787/article/details/17468039,写的挺细的,实现原理就是:
1.通过第三方工具openoffice,将word、excel、ppt、txt等文件转换为pdf文件;
2.通过swfTools将pdf文件转换成swf格式的文件;
3.通过FlexPaper文档组件在页面上进行展示。
当然如果装了Adobe Reader XI,那把pdf直接拖到浏览器页面就可以直接打开预览,这样就不需要步骤2、3了,前提就是客户装了Adobe Reader XI这个pdf阅读器。
我这里介绍通过poi实现word、excel、ppt转html,这样就可以放在页面上了。

###word转html
--------------------- 
版权声明:本文为CSDN博主「yjclsx」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/yjclsx/article/details/51441632

package wordToHtml;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.w3c.dom.Document;
public class PoiWordToHtml {
 public static void main(String[] args) throws Throwable {
  final String path = "D:\\poi-test\\wordToHtml\\";
  final String file = "人员选择系分.doc";
  InputStream input = new FileInputStream(path + file);
  HWPFDocument wordDocument = new HWPFDocument(input);
  WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
    DocumentBuilderFactory.newInstance().newDocumentBuilder()
      .newDocument());
  wordToHtmlConverter.setPicturesManager(new PicturesManager() {
   public String savePicture(byte[] content, PictureType pictureType,
     String suggestedName, float widthInches, float heightInches) {
    return suggestedName;
   }
  });
  wordToHtmlConverter.processDocument(wordDocument);
  List pics = wordDocument.getPicturesTable().getAllPictures();
  if (pics != null) {
   for (int i = 0; i < pics.size(); i++) {
    Picture pic = (Picture) pics.get(i);
    try {
     pic.writeImageContent(new FileOutputStream(path
       + pic.suggestFullFileName()));
    } catch (FileNotFoundException e) {
     e.printStackTrace();
    }
   }
  }
  Document htmlDocument = wordToHtmlConverter.getDocument();
  ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  DOMSource domSource = new DOMSource(htmlDocument);
  StreamResult streamResult = new StreamResult(outStream);
  TransformerFactory tf = TransformerFactory.newInstance();
  Transformer serializer = tf.newTransformer();
  serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
  serializer.setOutputProperty(OutputKeys.INDENT, "yes");
  serializer.setOutputProperty(OutputKeys.METHOD, "html");
  serializer.transform(domSource, streamResult);
  outStream.close();
  String content = new String(outStream.toByteArray());
  FileUtils.writeStringToFile(new File(path, "人员选择系分.html"), content, "utf-8");
 }
}

###excel转html

package excelToHtml;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.converter.ExcelToHtmlConverter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.w3c.dom.Document;


public class PoiExcelToHtml {
	final static String path = "D:\\poi-test\\excelToHtml\\";
	 final static String file = "exportExcel.xls";
 public static void main(String args[]) throws Exception {
	 
	 InputStream input=new FileInputStream(path+file);
	 HSSFWorkbook excelBook=new HSSFWorkbook(input);
	 ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter (DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() );
	 excelToHtmlConverter.processWorkbook(excelBook);
	 List pics = excelBook.getAllPictures();
     if (pics != null) {
         for (int i = 0; i < pics.size(); i++) {
             Picture pic = (Picture) pics.get (i);
             try {
                 pic.writeImageContent (new FileOutputStream (path + pic.suggestFullFileName() ) );
             } catch (FileNotFoundException e) {
                 e.printStackTrace();
             }
         }
     }
     Document htmlDocument =excelToHtmlConverter.getDocument();
     ByteArrayOutputStream outStream = new ByteArrayOutputStream();
     DOMSource domSource = new DOMSource (htmlDocument);
     StreamResult streamResult = new StreamResult (outStream);
     TransformerFactory tf = TransformerFactory.newInstance();
     Transformer serializer = tf.newTransformer();
     serializer.setOutputProperty (OutputKeys.ENCODING, "utf-8");
     serializer.setOutputProperty (OutputKeys.INDENT, "yes");
     serializer.setOutputProperty (OutputKeys.METHOD, "html");
     serializer.transform (domSource, streamResult);
     outStream.close();

     String content = new String (outStream.toByteArray() );

     FileUtils.writeStringToFile(new File (path, "exportExcel.html"), content, "utf-8");
 }
}

###ppt转html
其实只是ppt转图片,有了图片后放到页面上去,点击下一页就一张张显示就可以了。这里只介绍ppt转图片的过程。

package pptToImg;

import java.awt.Dimension;   
import java.io.File;   
import java.io.FileInputStream;   
import java.io.FileNotFoundException;   
import java.io.FileOutputStream;   
import java.io.IOException;   
  
import java.awt.Color;   
import java.awt.Dimension;   
import java.awt.Graphics2D;   
import java.awt.geom.Rectangle2D;   
import java.awt.image.BufferedImage;   
  
import org.apache.poi.hslf.model.TextRun;   
import org.apache.poi.hslf.record.Slide;   
import org.apache.poi.hslf.usermodel.RichTextRun;   
import org.apache.poi.hslf.usermodel.SlideShow;   
  
public class PPTtoImage {   
    public static void main(String[] args) {   
        // 读入PPT文件   
        File file = new File("D:/poi-test/pptToImg/test.ppt");   
        doPPTtoImage(file);   
    }   
  
    public static boolean doPPTtoImage(File file) {   
        boolean isppt = checkFile(file);   
        if (!isppt) {   
            System.out.println("The image you specify don't exit!");   
            return false;   
        }   
        try {   
  
            FileInputStream is = new FileInputStream(file);   
            SlideShow ppt = new SlideShow(is);   
            is.close();   
            Dimension pgsize = ppt.getPageSize();   
            org.apache.poi.hslf.model.Slide[] slide = ppt.getSlides();   
            for (int i = 0; i < slide.length; i++) {   
                System.out.print("第" + i + "页。");   
                   
                TextRun[] truns = slide[i].getTextRuns();      
                for ( int k=0;k<truns.length;k++){      
                   RichTextRun[] rtruns = truns[k].getRichTextRuns();      
                  for(int l=0;l<rtruns.length;l++){      
                       int index = rtruns[l].getFontIndex();      
                        String name = rtruns[l].getFontName();                
                        rtruns[l].setFontIndex(1);      
                        rtruns[l].setFontName("宋体");  
//                        System.out.println(rtruns[l].getText());
                   }      
                }      
                BufferedImage img = new BufferedImage(pgsize.width,pgsize.height, BufferedImage.TYPE_INT_RGB);   
  
                Graphics2D graphics = img.createGraphics();   
                graphics.setPaint(Color.BLUE);   
                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));   
                slide[i].draw(graphics);   
  
                // 这里设置图片的存放路径和图片的格式(jpeg,png,bmp等等),注意生成文件路径   
                FileOutputStream out = new FileOutputStream("D:/poi-test/pptToImg/pict_"+ (i + 1) + ".jpeg");   
                javax.imageio.ImageIO.write(img, "jpeg", out);   
                out.close();   
  
            }   
            System.out.println("success!!");   
            return true;   
        } catch (FileNotFoundException e) {   
            System.out.println(e);   
            // System.out.println("Can't find the image!");   
        } catch (IOException e) {   
        }   
        return false;   
    }   
  
    // function 检查文件是否为PPT   
    public static boolean checkFile(File file) {   
  
        boolean isppt = false;   
        String filename = file.getName();   
        String suffixname = null;   
        if (filename != null && filename.indexOf(".") != -1) {   
            suffixname = filename.substring(filename.indexOf("."));   
            if (suffixname.equals(".ppt")) {   
                isppt = true;   
            }   
            return isppt;   
        } else {   
            return isppt;   
        }   
    }   
  
}  

 

2019-08-21 21:32:53 LiRunchen 阅读数 549

java实现在线预览- -之poi实现word、excel、ppt转html

简介

java实现在线预览功能是一个大家在工作中也许会遇到的需求,如果公司有钱,直接使用付费的第三方软件或者云在线预览服务就可以了,例如永中office、office web 365(http://www.officeweb365.com/)他们都有云在线预览服务,就是要钱0.0
如果想要免费的,可以用openoffice,还需要借助其他的工具(例如swfTools、FlexPaper等)才行,可参考这篇文章http://blog.csdn.net/z69183787/article/details/17468039,写的挺细的,实现原理就是:
1.通过第三方工具openoffice,将word、excel、ppt、txt等文件转换为pdf文件;
2.通过swfTools将pdf文件转换成swf格式的文件;
3.通过FlexPaper文档组件在页面上进行展示。
当然如果装了Adobe Reader XI,那把pdf直接拖到浏览器页面就可以直接打开预览,这样就不需要步骤2、3了,前提就是客户装了Adobe Reader XI这个pdf阅读器。
我这里介绍通过poi实现word、excel、ppt转html,这样就可以放在页面上了。

word转html


package com.lrc.wordhtml;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.w3c.dom.Document;
public class PoiWordToHtml {

 public static void main(String[] args) throws Throwable {
 
  final String path = "D:\\poi-test\\wordToHtml\\";
  final String file = "人员选择系分.doc";
  InputStream input = new FileInputStream(path + file);
  HWPFDocument wordDocument = new HWPFDocument(input);
  WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
    DocumentBuilderFactory.newInstance().newDocumentBuilder()
      .newDocument());
  wordToHtmlConverter.setPicturesManager(new PicturesManager() {
   public String savePicture(byte[] content, PictureType pictureType,
     String suggestedName, float widthInches, float heightInches) {
    return suggestedName;
   }
  });
  wordToHtmlConverter.processDocument(wordDocument);
  List pics = wordDocument.getPicturesTable().getAllPictures();
  if (pics != null) {
   for (int i = 0; i < pics.size(); i++) {
    Picture pic = (Picture) pics.get(i);
    try {
     pic.writeImageContent(new FileOutputStream(path
       + pic.suggestFullFileName()));
    } catch (FileNotFoundException e) {
     e.printStackTrace();
    }
   }
  }
  Document htmlDocument = wordToHtmlConverter.getDocument();
  ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  DOMSource domSource = new DOMSource(htmlDocument);
  StreamResult streamResult = new StreamResult(outStream);
  TransformerFactory tf = TransformerFactory.newInstance();
  Transformer serializer = tf.newTransformer();
  serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
  serializer.setOutputProperty(OutputKeys.INDENT, "yes");
  serializer.setOutputProperty(OutputKeys.METHOD, "html");
  serializer.transform(domSource, streamResult);
  outStream.close();
  String content = new String(outStream.toByteArray());
  FileUtils.writeStringToFile(new File(path, "人员选择系分.html"), content, "utf-8");
 }
}

excel转html


package com.lrc.excelToHtml;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.converter.ExcelToHtmlConverter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.w3c.dom.Document;


public class PoiExcelToHtml {

	final static String path = "D:\\poi-test\\excelToHtml\\";
	 final static String file = "exportExcel.xls";
	 
 public static void main(String args[]) throws Exception {
 
	 
	 InputStream input=new FileInputStream(path+file);
	 HSSFWorkbook excelBook=new HSSFWorkbook(input);
	 ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter (DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() );
	 excelToHtmlConverter.processWorkbook(excelBook);
	 List pics = excelBook.getAllPictures();
     if (pics != null) {
         for (int i = 0; i < pics.size(); i++) {
             Picture pic = (Picture) pics.get (i);
             try {
                 pic.writeImageContent (new FileOutputStream (path + pic.suggestFullFileName() ) );
             } catch (FileNotFoundException e) {
                 e.printStackTrace();
             }
         }
     }
     Document htmlDocument =excelToHtmlConverter.getDocument();
     ByteArrayOutputStream outStream = new ByteArrayOutputStream();
     DOMSource domSource = new DOMSource (htmlDocument);
     StreamResult streamResult = new StreamResult (outStream);
     TransformerFactory tf = TransformerFactory.newInstance();
     Transformer serializer = tf.newTransformer();
     serializer.setOutputProperty (OutputKeys.ENCODING, "utf-8");
     serializer.setOutputProperty (OutputKeys.INDENT, "yes");
     serializer.setOutputProperty (OutputKeys.METHOD, "html");
     serializer.transform (domSource, streamResult);
     outStream.close();

     String content = new String (outStream.toByteArray() );

     FileUtils.writeStringToFile(new File (path, "exportExcel.html"), content, "utf-8");
 }
}

ppt转html
其实只是ppt转图片,有了图片之后,放到页面上去,点击下一页就一张张显示就可以了。这里只介绍ppt转图片的过程。


package com.lrc.pptToImg;

import java.awt.Dimension;   
import java.io.File;   
import java.io.FileInputStream;   
import java.io.FileNotFoundException;   
import java.io.FileOutputStream;   
import java.io.IOException;   
  
import java.awt.Color;   
import java.awt.Dimension;   
import java.awt.Graphics2D;   
import java.awt.geom.Rectangle2D;   
import java.awt.image.BufferedImage;   
  
import org.apache.poi.hslf.model.TextRun;   
import org.apache.poi.hslf.record.Slide;   
import org.apache.poi.hslf.usermodel.RichTextRun;   
import org.apache.poi.hslf.usermodel.SlideShow;   
  
public class PPTtoImage {   
    public static void main(String[] args) {   
        // 读入PPT文件   
        File file = new File("D:/poi-test/pptToImg/test.ppt");   
        doPPTtoImage(file);   
    }   
  
    public static boolean doPPTtoImage(File file) {   
        boolean isppt = checkFile(file);   
        if (!isppt) {   
            System.out.println("The image you specify don't exit!");   
            return false;   
        }   
        try {   
  
            FileInputStream is = new FileInputStream(file);   
            SlideShow ppt = new SlideShow(is);   
            is.close();   
            Dimension pgsize = ppt.getPageSize();   
            org.apache.poi.hslf.model.Slide[] slide = ppt.getSlides();   
            for (int i = 0; i < slide.length; i++) {   
                System.out.print("第" + i + "页。");   
                   
                TextRun[] truns = slide[i].getTextRuns();      
                for ( int k=0;k<truns.length;k++){      
                   RichTextRun[] rtruns = truns[k].getRichTextRuns();      
                  for(int l=0;l<rtruns.length;l++){      
                       int index = rtruns[l].getFontIndex();      
                        String name = rtruns[l].getFontName();                
                        rtruns[l].setFontIndex(1);      
                        rtruns[l].setFontName("宋体");  
//                        System.out.println(rtruns[l].getText());
                   }      
                }      
                BufferedImage img = new BufferedImage(pgsize.width,pgsize.height, BufferedImage.TYPE_INT_RGB);   
  
                Graphics2D graphics = img.createGraphics();   
                graphics.setPaint(Color.BLUE);   
                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));   
                slide[i].draw(graphics);   
  
                // 这里设置图片的存放路径和图片的格式(jpeg,png,bmp等等),注意生成文件路径   
                FileOutputStream out = new FileOutputStream("D:/poi-test/pptToImg/pict_"+ (i + 1) + ".jpeg");   
                javax.imageio.ImageIO.write(img, "jpeg", out);   
                out.close();   
  
            }   
            System.out.println("success!!");   
            return true;   
        } catch (FileNotFoundException e) {   
            System.out.println(e);   
            // System.out.println("Can't find the image!");   
        } catch (IOException e) {   
        }   
        return false;   
    }   
  
    // function 检查文件是否为PPT   
    public static boolean checkFile(File file) {   
  
        boolean isppt = false;   
        String filename = file.getName();   
        String suffixname = null;   
        if (filename != null && filename.indexOf(".") != -1) {   
            suffixname = filename.substring(filename.indexOf("."));   
            if (suffixname.equals(".ppt")) {   
                isppt = true;   
            }   
            return isppt;   
        } else {   
            return isppt;   
        }   
    }   
  
}  

ppt转图片有个缺陷,就是ppt里不是宋体的字有些可能会变成框框。
以上都需要引入poi的jar包。
要实现在线预览,只需把转换得到的html在新标签页打开或者镶嵌到某块区域就可以展现了。

2015-12-10 18:13:40 hwd15219166920 阅读数 4802
web 中在线预览office 是个头疼的问题。 今天项目刚好做完一个PPT在线预览的功能   在这里分享给大家
 
思路:
     获取网络PPT 文件 将PPT每一页的幻灯片都转换成单张图片  用流输出到页面展示
     1, 首先获取PPT格式  PPT格式无非两种 PPTX,PPT
     2,获取PPT幻灯片页数传递到JSP中
     3,JSP循环获取每页PPT
上代码:
         首先获取在线PPT 文件  并且获取PPT幻灯片页数




/**
 * 本类应用了Apache POI系统库,POI 是 Apache 下的 Jakata 项目的一个子项目,主要用于提供 Java 操作 Microsoft Office 办公套件如 Excel,Word,Powerpoint 等文件的 API。
 */

public class ConvertPPTFileToImage {


public ConvertPPTFileToImage() {

}
/**
*  PPTX 格式的处理
* @param filePath  图片网络路径URL 
* @param page   页数
* @param orignalPPTFileName 文件名
* @param imageFormatNameString  创建图片格式 (JPG,PNG,JPEG...等等)
* @param outputStream   输出
* @throws Exception
* 本来字体是要设置成PPT的字体  但是上传到linux 时候linux需要自己上传字体 否则所有中文都会变成乱码  口口口  无法显示   所以这里只
         * 使用宋体  
*如果大家想用其他字体 同样也是 linux 服务器的情况下  请自己上传字体到linux 中避免中文无法显示   下面会介绍如何上传字体到linux 中
*/

public static void convertPPTXtoImage(String filePath,int page,String orignalPPTFileName, String imageFormatNameString, OutputStream outputStream) throws Exception {
/**
* 多文件转码处理避免有中文或者特殊字符无法读取
*/

InputStream orignalPPTFileInputStream =null;
   String encodeName="";
        String igs[]=orignalPPTFileName.split("/");
           for(int x=0;x<igs.length;x++){
            if(x==igs.length-1){
              encodeName+=URLEncoder.encode(igs[x]).replace("+","%20");
            }else{
               encodeName+=URLEncoder.encode(igs[x]).replace("+","%20")+"/";
            }
           }
           URL url=new URL(filePath+encodeName);
           HttpURLConnection conn = (HttpURLConnection)url.openConnection();
           conn.setRequestMethod("GET");   //使用get
           orignalPPTFileInputStream=conn.getInputStream();


//FileOutputStream orignalPPTFileOutputStream =null;
/**
*  org.apache.poi.hslf, 这个包只支持 PowerPoint 2007 以前的 ppt 文档解析. 因为 Office 2007 的文件底层实现方案(OOXML)和以前的版本(OLE2)有根本的变化。
*  支持 office 2007 的包为: org.apache.poi.xslf 
*/

XMLSlideShow oneSlideShow =null;
try{
try {
oneSlideShow = new XMLSlideShow(orignalPPTFileInputStream);
} catch (IOException e) {
e.printStackTrace();
}
/**
* 获得PPT每页的尺寸大小(宽和高度)
*/

Dimension onePPTPageSize = oneSlideShow.getPageSize();
/**
* 获得PPT文件中的所有的PPT页面,并转换为一张张的播放片
*/

XSLFSlide[] pptPageXSLFSlideArray = oneSlideShow.getSlides();
if(pptPageXSLFSlideArray.length<=0||page>=pptPageXSLFSlideArray.length){
return ;
}
/**
* 下面的XML配置文件定义转换后的图片内的文字字体,否则将会出现转换后的图片内的中文为乱码
*/

String xmlFontFormat1="<xml-fragment xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" xmlns:p=\"http://schemas.openxmlformats.org/presentationml/2006/main\">";
String xmlFontFormat2="<a:rPr lang=\"zh-CN\" altLang=\"en-US\" dirty=\"0\" smtClean=\"0\"> ";
String xmlFontFormat3="<a:latin typeface=\"+mj-ea\"/> ";
String xmlFontFormat4="</a:rPr>";
String xmlFontFormat5="</xml-fragment>";
StringBuffer xmlFontFormatStringBuffer=new StringBuffer();
xmlFontFormatStringBuffer.append(xmlFontFormat1);
xmlFontFormatStringBuffer.append(xmlFontFormat2);
xmlFontFormatStringBuffer.append(xmlFontFormat3);
xmlFontFormatStringBuffer.append(xmlFontFormat4);
xmlFontFormatStringBuffer.append(xmlFontFormat5);

/**
*设置字体为宋体,解决中文乱码问题 
*/

           CTSlide oneCTSlide=pptPageXSLFSlideArray[page].getXmlObject();
           CTGroupShape oneCTGroupShape = oneCTSlide.getCSld().getSpTree();
           CTShape[] oneCTShapeArray = oneCTGroupShape.getSpArray();
           for (CTShape oneCTShape : oneCTShapeArray) {
               CTTextBody oneCTTextBody = oneCTShape.getTxBody();
               if (null == oneCTTextBody){
                   continue;
               }
               CTTextParagraph[] oneCTTextParagraph = oneCTTextBody.getPArray();               
               CTTextFont oneCTTextFont =null;
try {
oneCTTextFont = CTTextFont.Factory.parse(xmlFontFormatStringBuffer.toString());
}
catch (XmlException e) {
e.printStackTrace();
}
               for (CTTextParagraph textParagraph : oneCTTextParagraph) {
                   CTRegularTextRun[] oneCTRegularTextRunArray = textParagraph.getRArray();
                   for (CTRegularTextRun oneCTRegularTextRun : oneCTRegularTextRunArray) {
                       CTTextCharacterProperties oneCTTextCharacterProperties=oneCTRegularTextRun.getRPr();
                       oneCTTextCharacterProperties.setLatin(oneCTTextFont);
                   }
               }
           }
/**
* 创建BufferedImage对象,图象的尺寸为原来PPT的每页的尺寸
*/

BufferedImage oneBufferedImage = new BufferedImage(onePPTPageSize.width, onePPTPageSize.height, BufferedImage.TYPE_INT_RGB);
Graphics2D oneGraphics2D = oneBufferedImage.createGraphics();
/**
* 将PPT文件中的每个页面中的相关内容画到转换后的图片中
*/

pptPageXSLFSlideArray[page].draw(oneGraphics2D);
/**
* 设置图片的存放路径和图片的格式,注意生成的文件路径为绝对路径,最终获得各个图像文件所对应的输出流对象
*/

try {
ImageIO.write(oneBufferedImage, imageFormatNameString, outputStream);
} catch (IOException e) {
e.printStackTrace();
}
//}
}
finally{
try {
if(orignalPPTFileInputStream != null ){
orignalPPTFileInputStream.close();
}

catch (IOException e) {
e.printStackTrace();
}
}
}



/**
*  PPT 格式的处理
* @param filePath  图片网络路径URL 
* @param page   页数
* @param orignalPPTFileName 文件名
* @param imageFormatNameString  创建图片格式 (JPG,PNG,JPEG...等等)
* @param outputStream   输出
* @throws Exception
*  本来是设置成PPT的字体  但是上传到linux 时候linux需要自己上传字体 否则所有中文都会变成乱码  口口口  无法显示   所以这里只使用宋体  
* 如果大家想用其他字体 同样也是 linux 服务器的情况下  请自己上传字体到linux 中避免中文无法显示   下面会介绍如何上传字体到linux 中
*/

public static void convertPPTtoImage(String filePath,int page,String orignalPPTFileName, String imageFormatNameString,OutputStream outputStream) throws Exception {
/**
* convertReturnResult代表转换的结果,返回 false则表示转换不成功
*/

InputStream orignalPPTFileInputStream =null;
   String encodeName="";
        String igs[]=orignalPPTFileName.split("/");
           for(int x=0;x<igs.length;x++){
            if(x==igs.length-1){
              encodeName+=URLEncoder.encode(igs[x]).replace("+","%20");
            }else{
               encodeName+=URLEncoder.encode(igs[x]).replace("+","%20")+"/";
            }
           }
           URL url=new URL(filePath+encodeName);
           HttpURLConnection conn = (HttpURLConnection)url.openConnection();
           conn.setRequestMethod("GET");  
           orignalPPTFileInputStream=conn.getInputStream();
SlideShow oneSlideShow =null;
try{
try {
oneSlideShow = new SlideShow(orignalPPTFileInputStream);
} catch (IOException e) {
e.printStackTrace();
}
/**
* 获得PPT每页的尺寸大小(宽和高度)
*/

Dimension onePPTPageSize = oneSlideShow.getPageSize();
/**
* 获得PPT文件中的所有的PPT页面(获得每一张幻灯片),并转换为一张张的播放片
*/

Slide[] pptPageSlideArray = oneSlideShow.getSlides();
/**
* 下面的循环的主要功能是实现对PPT文件中的每一张幻灯片进行转换和操作。
*/

if(pptPageSlideArray.length<=0||page>=pptPageSlideArray.length){
return ;
}

TextRun[] textRunsArray = pptPageSlideArray[page].getTextRuns();
for (int textRunsArrayIndex = 0; textRunsArrayIndex < textRunsArray.length; textRunsArrayIndex++) {
RichTextRun[] pptRichTextRunsArray = textRunsArray[textRunsArrayIndex].getRichTextRuns();
for (int pptRichTextRunsArrayIndex = 0; pptRichTextRunsArrayIndex < pptRichTextRunsArray.length; pptRichTextRunsArrayIndex++) {
/**原来是直接设置为宋体,这样会使得转换后的图片上的文字与原PPT的文字不一致,应该改变为应用PPT本身的字体名
* pptRichTextRunsArray[pptRichTextRunsArrayIndex].setFontIndex(1);
* pptRichTextRunsArray[pptRichTextRunsArrayIndex].setFontName("宋体");
*/ 
/**
* 获得某个文本框内的字体名字符串,并识别是否为null(未正确地获得相关的字体名字符串),则设置为默认的字体名——宋体
* 但如果PPT文件在WPS中保存过,则pptRichTextRunsArray[pptRichTextRunsArrayIndex].getFontSize()的值可能为0或者26040。因此,
* 首先识别当前文本框内的字体尺寸是否为0或者大于26040,则设置默认的字体尺寸。
*/

int currentFontSize = pptRichTextRunsArray[pptRichTextRunsArrayIndex].getFontSize();
if((currentFontSize <=0)||(currentFontSize >=26040)){
pptRichTextRunsArray[pptRichTextRunsArrayIndex].setFontSize(30);
}

String currentFontName=pptRichTextRunsArray[pptRichTextRunsArrayIndex].getFontName();
/**
* 本来是设置成PPT的字体  但是上传到linux 时候linux需要自己上传字体 否则所有中文都会变成乱码  口口口  无法显示   所以这里只使用宋体  
* 如果大家想用其他字体 同样也是 linux 服务器的情况下  请自己上传字体到linux 中避免中文无法显示   下面会介绍如何上传字体到linux 中
*/

/* if(currentFontName == null){  */  
 int index = pptRichTextRunsArray[pptRichTextRunsArrayIndex].getFontIndex();
 pptRichTextRunsArray[pptRichTextRunsArrayIndex].setFontIndex(1);
 pptRichTextRunsArray[pptRichTextRunsArrayIndex].setFontName("宋体");
//}
/*else{
pptRichTextRunsArray[pptRichTextRunsArrayIndex].setFontName(currentFontName);
}*/
/**
* 应用 pptRichTextRunsArray[pptRichTextRunsArrayIndex].getText() 可以获得其中的文字
* int pptRichTextRunsNumberIndex = pptRichTextRunsArray[pptRichTextRunsArrayIndex].getFontIndex();
String fontNameForPPTText = pptRichTextRunsArray[pptRichTextRunsArrayIndex].getFontName();
*/

}
}
/**
* 下面的代码是获取某一页PPT中的第一个备注文字串
    System.out.println("备注文字:" + pptPageSlideArray[pptPageSlideIndex].getNotesSheet().getTextRuns()[0].getText());
    */
/**
* 创建BufferedImage对象,图象的尺寸为原来PPT的每页的尺寸
*/

BufferedImage oneBufferedImage = new BufferedImage(onePPTPageSize.width, onePPTPageSize.height, BufferedImage.TYPE_INT_RGB);
Graphics2D oneGraphics2D = oneBufferedImage.createGraphics();
oneGraphics2D.setFont(new Font("宋体", Font.PLAIN, 12));

/**
* 设置转换后的图片的背景颜色为白色
* oneGraphics2D.setPaint(Color.white);
oneGraphics2D.fill(new Rectangle2D.Float(0, 0, onePPTPageSize.width ,onePPTPageSize.height));
*/

pptPageSlideArray[page].draw(oneGraphics2D);
/**
* 图像文件的格式字符串为“jpg”、“jpeg”、"bmp"、"png"、 "gif"、"tiff"等,将转换后的各个图片文件保存到指定的目录中
*/

try {
ImageIO.write(oneBufferedImage, imageFormatNameString, outputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
finally{
try {
if(orignalPPTFileInputStream != null ){
orignalPPTFileInputStream.close();
}

catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*    检查文件是否为ppt或者pptx格式 
* @param orignalPPTFileName需要转换的原始PPT的文件名称
* @return
*/

public static short checkOrignalFileFormat(String  orignalPPTFileName) {
/**
* PPT格式的识别结果, =0 不是PPT或者PPTX的格式文件, =1 代表*.ppt 格式, =2  代表 *.pptx 格式
*/

short pptORpptxFormatFile = 0;
/**
* 识别需要转换的原始PPT的文件是否为真正的PPT文件
*/

String orignalPPTFileSuffixName = null;
if (orignalPPTFileName != null && orignalPPTFileName.lastIndexOf(".") != -1) {
/**
* 获得需要转换的原始ppt或者pptx的文件扩展名,返回的结果应该为“ppt”或者"pptx"字符串
*/

orignalPPTFileSuffixName = orignalPPTFileName.substring(orignalPPTFileName.lastIndexOf(".") );
/** 
* 识别是否为.ppt格式
*/

if (".ppt".equals(orignalPPTFileSuffixName)) {
pptORpptxFormatFile = 1;
}
/**
* 识别是否为.pptx格式
*/

else if (".pptx".equals(orignalPPTFileSuffixName)) {
pptORpptxFormatFile = 2;
}
/**
* 如果不是.ppt格式或者*.pptx格式,则表示为非法的文件格式,则不能进行转换,符合检测的结果编码为0
*/

}
return pptORpptxFormatFile;
}

/**
* 判断文件是否存在   并且返回PPT幻灯片的页数
* @param filePath   文件路径URL
* @param orignalPPTFileName  文件名
* @return
* @throws Exception
*/

public static int getPPTImgCount(String filePath,String orignalPPTFileName) throws Exception{
/**
* 对文件名转码处理 避免有中文和特殊字符时无法获取图片
*/

SlideShow oneSlideShow =null;
XMLSlideShow oneSlideShow2 =null;
InputStream orignalPPTFileInputStream =null;
   String encodeName="";
        String igs[]=orignalPPTFileName.split("/");
           for(int x=0;x<igs.length;x++){
            if(x==igs.length-1){
              encodeName+=URLEncoder.encode(igs[x]).replace("+","%20");
            }else{
               encodeName+=URLEncoder.encode(igs[x]).replace("+","%20")+"/";
            }
           }
           URL url=new URL(filePath+encodeName);
           HttpURLConnection conn = (HttpURLConnection)url.openConnection();
           conn.setRequestMethod("GET"); 
            int state = conn.getResponseCode();
            if( state!=200){
            return 0;
            }
             
           orignalPPTFileInputStream=conn.getInputStream();

int count=0;
switch(checkOrignalFileFormat(orignalPPTFileName)){
case 0:
System.out.println("待转换的PPT文件不存在或者不是PPT和PPTX格式的文件!");
break;
case 1:
try {
oneSlideShow = new SlideShow(orignalPPTFileInputStream);
} catch (IOException e) {
e.printStackTrace();
return 0;
}
count= oneSlideShow.getSlides().length;
break;
case 2:
try {
oneSlideShow2 = new XMLSlideShow(orignalPPTFileInputStream);
} catch (IOException e) {
e.printStackTrace();
return 0;
}
count = oneSlideShow2.getSlides().length;
break;
}
return count;
}

}
      /**
          获取PPT页数到JSP 创建图片
      */

@RequestMapping(value = "ppts")
public String get(HttpServletRequest request,int id,String isFav) throws Exception{
request.setAttribute("pptCount", ConvertPPTFileToImage.getPPTImgCount(uploadHelper, data.value.getCASE_INTRO_URL()));
return "dtl";
}


    /**
          获取PPT图片
          page  为幻灯片页数
      */

@RequestMapping(value = "loaddtlppt")
public void  loadDtlPpt(HttpServletRequest req,HttpServletResponse rsp,int page) throws Exception{
String loadPath= (String) req.getSession().getAttribute("loadPptUrl");
String imageFormatNameString ="jpeg";
rsp.setHeader("Pragma", "No-cache");
rsp.setHeader("Cache-Control", "No-cache");
rsp.setDateHeader("Expires", 0);
// 指定生成的响应是图片
rsp.setContentType("image/jpeg");
switch(ConvertPPTFileToImage.checkOrignalFileFormat(loadPath)){
case 0:
System.out.println("待转换的PPT文件不存在或者不是PPT和PPTX格式的文件!");
break;
case 1:
ConvertPPTFileToImage.convertPPTtoImage([自行改成PPT文件路径],page,[文件名], imageFormatNameString,rsp.getOutputStream());
break;
case 2:
ConvertPPTFileToImage.convertPPTXtoImage([自行改成PPT文件路径],page,[文件名],imageFormatNameString,rsp.getOutputStream());
break;
}

}









-------------------------jsp  代码---------------------------


ppts.jsp   html


<c:forEach begin="1" end="${pptCount}" varStatus="status">
<img alt="方案详情" src="<c:url value="/${base}loaddtlppt?page=${status.index-1}" />&time=<%=System.currentTimeMillis()%>" />
</c:forEach>




html  end









//---------------------------------------------------------------
相关JAR    没有用mave 也可以直接下载 poi 包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.10-FINAL</version>
</dependency>


<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi-scratchpad</artifactId>
   <version>3.11-beta3</version>
</dependency>




Linux 上传  字体   


首先 找到 windows 下的字体 这里以宋体为例子
C:\Windows\Fonts\simsun.ttc   
上传到  linux jar 的 font 目录下
$HOME_PATH/jar/lib/fonts/fallback 目录下
(如果fonts下没有 fallback 目录自己创建    然后重启tomcat 就可以了  ,注意 是 ttc 后缀 不是ttf)




就此完毕  希望能帮到大家 ---------------第一次写







2014-08-26 16:22:50 Senssic 阅读数 5106

最近项目用到在线预览office相关文件。额、一想。貌似不难实现、java的poi可以实现、然后。。。发现事不如愿、针对office的格式多样化。poi显的力不从心、遂放弃折腾、由于服务器为linux!故有关使用 jacob-1.15-M4-x86.dll 来转换的方法也得淘汰。发现QQ邮箱、163邮箱等邮件中附件在线预览很是牛叉。经了解。原来他们使用国人的永中office来转换。效果非常好。不过设计付费、版权等问题。也不实际。所以另辟蹊径、找到基于openoffice的转换方式、兼容window与linux。开源免费、大块人心。
将Word转Html的原理是这样的:


1、客户上传Word文档到服务器
2、服务器调用OpenOffice程序打开上传的Word文档
3、OpenOffice将Word文档另存为Html格式
4、Over

关于openoffice的安装与服务的启动这里不做太多介绍了。下面附上利用openoffice将word转html的核心代码:

package common.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import config.AppConfig;

/**
 * 利用jodconverter(基于OpenOffice服务)将word文件(*.doc)转化为html格式,
 * 使用前请检查OpenOffice服务是否已经开启,
 * OpenOffice进程名称:soffice.exe | soffice.bin
 * @author linshutao
 * */
public class Doc2HtmlUtil {

	Log log = LogFactory.getLog(getClass());
	private static Doc2HtmlUtil doc2HtmlUtil;

	/**
	 * 获取Doc2HtmlUtil实例
	 * */
	public static synchronized Doc2HtmlUtil getDoc2HtmlUtilInstance(){
		if(doc2HtmlUtil == null){
			doc2HtmlUtil = new Doc2HtmlUtil();
		}
		return doc2HtmlUtil;		
	}
	/**
	 * 转换文件
	 * @param fromFileInputStream: 
	 * */
	public String doc2Html(InputStream fromFileInputStream, File toFileFolder){
		String soffice_host = AppConfig.getProperty(AppConfig.SOFFICE_HOST_KEY);
		String soffice_port = AppConfig.getProperty(AppConfig.SOFFICE_PORT_KEY);
		log.debug("soffice_host:"+soffice_host+",soffice_port:"+soffice_port);

		Date date = new Date();
		SimpleDateFormat sdf =new SimpleDateFormat("yyyyMMddHHmmss");
		String timesuffix = sdf.format(date);
		String htmFileName = "htmlfile"+timesuffix+".html";
		String docFileName = "docfile"+timesuffix+".doc";

		File htmlOutputFile = new File(toFileFolder.toString()+File.separatorChar+htmFileName);		
		File docInputFile = new File(toFileFolder.toString()+File.separatorChar+docFileName);
		log.debug("########htmlOutputFile:"+toFileFolder.toString()+File.pathSeparator+htmFileName);
		/**
		 * 由fromFileInputStream构建输入文件
		 * */
		try {
			OutputStream os = new FileOutputStream(docInputFile);
			int bytesRead = 0;
			 byte[] buffer = new byte[1024 * 8];
			while ((bytesRead = fromFileInputStream.read(buffer)) != -1) {
					os.write(buffer, 0, bytesRead);
			}

			os.close();
			fromFileInputStream.close();
		} catch (IOException e) {
			log.error(e.getMessage(), e);
		}

		OpenOfficeConnection connection = new SocketOpenOfficeConnection(soffice_host,Integer.parseInt(soffice_port));
		try {
			connection.connect();
		} catch (ConnectException e) {
			 System.err.println("文件转换出错,请检查OpenOffice服务是否启动。");  
			 log.error(e.getMessage(), e);
		}
		// convert
		DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
		converter.convert(docInputFile, htmlOutputFile);
		connection.disconnect();
/*		File  htmlOutputFile_rn = new File
		(htmlOutputFile.getAbsolutePath().substring(0,htmlOutputFile.getAbsolutePath().lastIndexOf("."))+".htm");
		htmlOutputFile.renameTo(htmlOutputFile_rn);
		return htmlOutputFile_rn.getName();*/

		//转换完之后删除word文件
		docInputFile.delete();
		log.debug("删除上传文件:"+docInputFile.getName());
		return htmFileName;
	}

}

转http://aijava.cn/1939.html

而在前台展示可以使用html直接展示也可以使用openoffic转成pdf然后在用flexpaper(比如播放ppt)


2017-08-31 11:47:04 YangMing_number 阅读数 574
package com.pde.xzjg.p9.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.converter.ExcelToHtmlConverter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.w3c.dom.Document;

import com.pde.ams.p9.service.LogWriter;
import com.pde.app.common.domain.PdeSessionBean;
import com.pde.app.common.params.PdpSystemParams;
import com.pde.xzjg.p9.domain.CauseJGbean;
import com.pde.xzjg.p9.domain.OrgInfo;
import com.pde.xzjg.p9.service.JGOneService;

import sun.misc.BASE64Encoder;

public class CommonTools {
	
	
	/**
	 * @param uploadpath 需要转换的文件的路径
	 * @param parmas     获取工作空间的service
	 * @param session
	 * @param request
	 * @return   返回转换后的html路径
	 */
	public static void showView(String uploadpath,PdpSystemParams parmas,PdeSessionBean session,HttpServletRequest request,HttpServletResponse response){
		String newPath = null;
		if(uploadpath!=null && uploadpath.length()>0){
			String compltePath = parmas.getValue(PdpSystemParams.AMS_WORKSPACE)+uploadpath;//得到要转换的文件的全路径
			int index = compltePath.lastIndexOf("/")+1;//获取到最后一个/的位置索引
			try{
				if(compltePath.substring(index).endsWith(".DOC")||compltePath.substring(index).endsWith(".doc")){
					newPath = CommonTools.wordtoHtml(uploadpath, parmas, session, request);
	        		if(newPath!=null && newPath.length()>0){
	        			newPath = newPath.replaceAll("/", "\\\\\\\\");
	        		}
				}else if(compltePath.substring(index).endsWith(".XLS")||compltePath.substring(index).endsWith(".xls")){
					newPath = CommonTools.exceltoHtml(uploadpath, parmas, session, request);
	        		if(newPath!=null && newPath.length()>0){
	        			newPath = newPath.replaceAll("/", "\\\\\\\\");
	        		}
	        		 
	        	}else{
	        		
	        	}
				File readFile = null;
				 try {
					readFile = new File(newPath);
     	        	FileInputStream hFile = new FileInputStream(readFile); // 以byte流的方式打开文件 d:\1.gif
     				int i=hFile.available(); //得到文件大小
     				byte data[]=new byte[i];
     				hFile.read(data); //读数据
     				hFile.close();
     				//response.setContentType("application/msword"); //设置返回的文件类型
     				response.setContentType("text/html;charset=utf-8");
     				OutputStream toClient=response.getOutputStream(); //得到向客户端输出二进制数据的对象
     				toClient.write(data); //输出数据
     				toClient.close();
     				//readFile.delete();//删除转换后的临时文件
     			} catch (Exception e) {
     				PrintWriter toClient;
     				try {
     					toClient = response.getWriter();
     				//到向客户端输出文本的对象
     				response.setContentType("text/html;charset=UTF-8");
     				toClient.write("无法打开图片!");
     				toClient.close();
     				//readFile.delete();//删除转换后的临时文件
     				} catch (IOException e1) {
     					e1.printStackTrace();
     				} 
     			}
			}catch(Exception e){
				e.printStackTrace();
			}
			
		}
	}
	
	public static String wordtoHtml(String uploadpath,PdpSystemParams parmas,PdeSessionBean session,HttpServletRequest request) throws Exception {
		UUID uuid = UUID.randomUUID();//生成一个uuid,为新文件的名字(防止与别的转换后的文件有名字冲突)
		String compltePath = parmas.getValue(PdpSystemParams.AMS_WORKSPACE)+uploadpath;//得到要转换的文件的全路径
    	int index = compltePath.lastIndexOf("/")+1;//获取到最后一个/的位置索引
    	String newPath = compltePath.substring(0,index)+session.getUserId()+"/";
    	//创建新的文件夹,以用户id为文件名
    	//request.getSession().getServletContext().setAttribute("tempFilePath", newPath);
    	File dir = new File(newPath);
    	if(!dir.isDirectory()){
    		if(!dir.exists()){
    		dir.mkdirs();
    		}
    	}
    	String oldPath = compltePath.substring(0,index);
    	String fileName = compltePath.substring(index);
    	String randomNumber = uuid.toString();
		String oldAllpath = oldPath + fileName;
		oldAllpath = oldAllpath.replaceAll("/", "\\\\\\\\");
		File f = new File(oldAllpath);
		InputStream input = new FileInputStream(f);
		String content = null;

		HWPFDocument wordDocument = new HWPFDocument(input);
		WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
				DocumentBuilderFactory.newInstance().newDocumentBuilder()
						.newDocument());
		wordToHtmlConverter.setPicturesManager(new PicturesManager() {
			public String savePicture(byte[] content, PictureType pictureType,
					String suggestedName, float widthInches, float heightInches) {
				return suggestedName;
			}
		});
		wordToHtmlConverter.processDocument(wordDocument);
		

		Document htmlDocument = wordToHtmlConverter.getDocument();
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		DOMSource domSource = new DOMSource(htmlDocument);
		StreamResult streamResult = new StreamResult(outStream);
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer serializer = tf.newTransformer();
		serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
		serializer.setOutputProperty(OutputKeys.METHOD, "html");
		serializer.transform(domSource, streamResult);
		outStream.close();
		content = new String(outStream.toByteArray(),"utf-8");
		
		
		List pics = wordDocument.getPicturesTable().getAllPictures();
		if (pics != null) {
			for (int i = 0; i < pics.size(); i++) {
				Picture pic = (Picture) pics.get(i);
				try {
					ByteArrayOutputStream outStreamImg = new ByteArrayOutputStream();
					pic.writeImageContent(outStreamImg);
					String imgStr = new BASE64Encoder().encodeBuffer(outStreamImg.toByteArray());//base64加密
					content = content.replaceAll("img src=\""+pic.suggestFullFileName()+"\"", 
							"img src=\"data:image/png;base64,"+imgStr+ "\"");
					outStreamImg.close();
					/*pic.writeImageContent(new FileOutputStream(oldPath
							+ pic.suggestFullFileName()));*/
					
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}
		}
		FileUtils.writeStringToFile(
				new File(newPath + randomNumber + ".html"), content, "utf-8");
		return newPath + randomNumber + ".html";
	}


	/**
	 * @param uploadpath
	 * @param parmas
	 * @param session
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public static String exceltoHtml(String uploadpath,PdpSystemParams parmas,PdeSessionBean session,HttpServletRequest request) throws Exception {
		UUID uuid = UUID.randomUUID();//生成一个uuid,为新文件的名字(防止与别的转换后的文件有名字冲突)
		String compltePath = parmas.getValue(PdpSystemParams.AMS_WORKSPACE)+uploadpath;//得到要转换的文件的全路径
    	int index = compltePath.lastIndexOf("/")+1;//获取到最后一个/的位置索引
    	String newPath = compltePath.substring(0,index)+session.getUserId()+"/";
    	//创建新的文件夹,以用户id为文件名
    	//request.getSession().getServletContext().setAttribute("tempFilePath", newPath);
    	
    	File dir = new File(newPath);
    	if(!dir.isDirectory()){
    		if(!dir.exists()){
    		dir.mkdirs();
    		}
    	}
    	String oldPath = compltePath.substring(0,index);
    	String fileName = compltePath.substring(index);
    	String randomNumber = uuid.toString();
		String oldAllpath = oldPath + fileName;
		oldAllpath = oldAllpath.replaceAll("/", "\\\\\\\\");
		File f = new File(oldAllpath);
		InputStream input = new FileInputStream(f);
		
		HSSFWorkbook excelBook = new HSSFWorkbook(input);
		excelBook.setSheetName(0, "  ");//不在页面显示sheet的名字
		ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter(
				DocumentBuilderFactory.newInstance().newDocumentBuilder()
						.newDocument());
		excelToHtmlConverter.setOutputColumnHeaders(false);//把excel转换成html 去掉序号列
		excelToHtmlConverter.setOutputRowNumbers(false);//把excel转换成html 去掉序号列
		excelToHtmlConverter.processWorkbook(excelBook);
		
		Document htmlDocument = excelToHtmlConverter.getDocument();
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		DOMSource domSource = new DOMSource(htmlDocument);
		StreamResult streamResult = new StreamResult(outStream);
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer serializer = tf.newTransformer();
		serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
		serializer.setOutputProperty(OutputKeys.METHOD, "html");
		serializer.transform(domSource, streamResult);
		outStream.close();

		String content = new String(outStream.toByteArray(),"utf-8");
		List pics = excelBook.getAllPictures();
		if (pics != null) {
			for (int i = 0; i < pics.size(); i++) {
				Picture pic = (Picture) pics.get(i);
				try {
					ByteArrayOutputStream outStreamImg = new ByteArrayOutputStream();
					pic.writeImageContent(outStreamImg);
					String imgStr = new BASE64Encoder().encodeBuffer(outStreamImg.toByteArray());
					content = content.replaceAll("img src=\""+pic.suggestFullFileName()+"\"", 
							"img src=\"data:image/png;base64,"+imgStr+ "\"");
					outStreamImg.close();
					/*pic.writeImageContent(new FileOutputStream(oldPath
						+ pic.suggestFullFileName()));*/
					
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}
		}
		FileUtils.writeStringToFile(
				new File(newPath + randomNumber + ".html"), content, "utf-8");
		return newPath + randomNumber + ".html";
	}
	

	/**
	 * @param request
	 * @param uploadpath 模块类型/当前年份/(如果涉及季度|月就加季度|月)/     如:jg1/2017 
	 * @param parmas   获取工作空间
	 * @param jgoneService  获取机构编码
	 * @param session  
	 * @return
	 */
	public static String upLoad(HttpServletRequest request,String uploadpath, CommonsMultipartFile file,PdpSystemParams parmas,JGOneService jgoneService,PdeSessionBean session){
		 //将当前上下文初始化给  CommonsMutipartResolver (多部分解析器)
        String fileNameNew = null;
                if(file!=null)
                {
                	String fileDir = parmas.getValue(PdpSystemParams.AMS_WORKSPACE)+"/xzjg/"+ uploadpath + "/";
                	File dir = new File(fileDir);
                	if(!dir.isDirectory()){
                		if(!dir.exists()){
                		dir.mkdirs();
                		}
                	}
                	String suffexName = (file.getOriginalFilename()).substring( (file.getOriginalFilename()).lastIndexOf(".")+1 );
                	String newFileName = UUID.randomUUID().toString() + "." + suffexName;
                	//文件格式:机构编码+userid+uuid文件名(用uuid替代原始文件名,原始文件名(file.getOriginalFilename())有中文时,传到前台时会有乱码,导致异常)
                	OrgInfo info = jgoneService.getOrgInfoByUserId(String.valueOf(session.getUserId()));
                	String path=parmas.getValue(PdpSystemParams.AMS_WORKSPACE)+"/xzjg/" + uploadpath +"/"+info.getDic_value()+"_"+session.getUserId()+"_"+newFileName;
                    //上传
                    try {
						file.transferTo(new File(path));
						fileNameNew = newFileName;
						return fileNameNew;
					}catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						LogWriter.saveErr("XZJG", e.getMessage());
					}
                    
                }
        
        return fileNameNew;
	}
	
	
	public static void delAllFile(String folderPath) {  
        File file = new File(folderPath);  
        if (file.exists()) {
        	file.delete();
        }
    }  
	
	
	/**
	 * 获取已经存在的年度
	 * @param bean 查询的类型获取来源 例如 jg1 jg2 jg3 jg4 jg5
	 * @param jgoneService
	 * @return
	 */
   public static List<String> getYear(CauseJGbean bean,JGOneService jgoneService){
	   List<String> year = jgoneService.getYear(bean);
	   return year;
   }
   
   /**
    * 获取所有的管理单位
    * @return
    */
   public static List<String> getUnit(JGOneService jgoneService){
	   List<String> unit = jgoneService.getUnit();
	   return unit;
   }

	
	
	
	
}