利用POI将word转换成html实现在线阅读|Java开发|码途山海.智隐长卷 -

程序人生|重庆纽新

找回密码
立即注册

QQ登录

只需一步,快速开始

欢迎访问【程序人生-重庆纽新】,本网站为软件开发人员视觉的IT资讯、软件开发中各种问题的解决办法!!
搜索
发新帖


2308

积分

0

好友

259

主题
楼主
发表于 2015-7-29 23:38:09 | 查看: 1178| 回复: 0
一、分析

通过网上找资料,发现用java实现word在线阅读有以下的实现方式:

1
Word=> PDF(OpenOffice+JodConverter)=>SWF(pdf2swf)=>FlexPaper浏览
2
Word=> PDF(MSOffice+JACOB)=>SWF(pdf2swf)=>FlexPaper浏览
3
Word =>SWF (FlashPaper)=> FlexPaper浏览
4
Word=>SWF(print2flash)=> FlexPaper浏览
5
用第三方收费组件:PageOffice
6
1) 利用 POI Word2003转换成 html
2) 利用OpenOffice+JodConverterword2003转换成html

  前4种方式,目标都是一致的,就是都将word文档转换成flash文件,只是中间的实现不大一样。前两种方式比较麻烦,都是先转成PDF,再转成SWF,最后用FlexPaper浏览。两种比较快捷,可直接将源文件转为SWF,用FlexPaper浏览。第二种方式用到的jacob是微软的组件,在linux平台下基本是无望的了,第一个淘汰。由于FlashPaper不是开源工具,加之Win8系统不兼容(我现在用的系统),所以就没采用第三种实现方式。Print2flash是开源工具,即使公司产品中用到也不会出现版权纠纷,遗憾的是没找到如何用程序控制该工具转换文件的命令。所以第3,4种方式也淘汰了。通过下载,预使用,发现第5种方式用PageOffice是最省时省力的,也能将word文档完美的展现,但是,要钱!!好吧,一提到钱,此种实现只能暂作废。

后面一开始是想用OpenOffice+JodConverter实现转swf的,后面在逛百度文库的时候,发现一个让我很好奇的东西。就是,百度文库里的文档基本上都用html进行展示了,也就是说,我们上传的word文档,百度对其做了html转换的处理,与页面的嵌合也相当的好。这让我想到,我们的项目中是否也可以用此方式实现word的在线预览呢。

        基于这个想法,我到谷歌找相关的资料,发现将word转html的开源工具没几个。其中,介绍得比较多的就是用POI进行转换,但是,由于POI对word的处理功能相当的弱,因此,开启了使用POI将wordàhtml的艰苦历程(后面发现网上有介绍用OpenOffice+JodConverter将word2003转换成html的方式,但是,我没有深究,有兴趣的同学可以去观望一下http://www.cnblogs.com/codeplus/archive/2011/10/22/2220952.html):

二、实现

1.      POI介绍:

Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office格式档案读和写的功能。POI为“Poor Obfuscation Implementation”的首字母缩写,意为“可怜的模糊实现”。

Apache POI 是创建和维护操作各种符合Office Open XML(OOXML)标准和微软的OLE 2复合文档格式(OLE2)的Java API。用它可以使用Java读取和创建,修改MS Excel文件.而且,还可以使用Java读取和创建MS Word和MSPowerPoint文件。Apache POI 提供Java操作Excel解决方案(适用于Excel97-2008)。

基本结构:

HSSF -提供读写Microsoft Excel XLS格式档案的功能。

XSSF -提供读写Microsoft Excel OOXML XLSX格式档案的功能。

HWPF -提供读写Microsoft Word DOC格式档案的功能。

HSLF -提供读写Microsoft PowerPoint格式档案的功能。

HDGF -提供读Microsoft Visio格式档案的功能。

HPBF -提供读Microsoft Publisher格式档案的功能。

HSMF -提供读Microsoft Outlook格式档案的功能。

其实,POI比较拿手的是处理Excel表格,即上面的HSSF及XSSF,我们的很多项目,只要涉及报表的,基本上都有用到它吧。用对于HWPF即处理DOC的包,功能就没有那么健全了,且API也不完善。

2.      poi相关包及依赖包配置。

3.      处理流程图:

1)   主体流程:


2)   进行word文档解释转换子流程



3)   处理表格子流程(略)

4)   处理图片子流程(略)

4.      代码实现

  1. package com;

  2. import java.awt.image.BufferedImage;
  3. import java.io.BufferedWriter;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.FileNotFoundException;
  7. import java.io.FileOutputStream;
  8. import java.io.IOException;
  9. import java.io.OutputStream;
  10. import java.io.OutputStreamWriter;

  11. import javax.imageio.ImageIO;

  12. import org.apache.poi.hwpf.HWPFDocument;
  13. import org.apache.poi.hwpf.model.PicturesTable;
  14. import org.apache.poi.hwpf.usermodel.CharacterRun;
  15. import org.apache.poi.hwpf.usermodel.Paragraph;
  16. import org.apache.poi.hwpf.usermodel.Picture;
  17. import org.apache.poi.hwpf.usermodel.Range;
  18. import org.apache.poi.hwpf.usermodel.Table;
  19. import org.apache.poi.hwpf.usermodel.TableCell;
  20. import org.apache.poi.hwpf.usermodel.TableIterator;
  21. import org.apache.poi.hwpf.usermodel.TableRow;
  22. import org.apache.xmlbeans.impl.piccolo.io.FileFormatException;


  23. /**
  24. * @Description: 利用poi将word简单的转换成html文件
  25. * @author 柯颖波
  26. * @date 2013-12-20 上午09:32:44
  27. * @version v1.0
  28. */
  29. public class Word2Html {
  30.         /**
  31.          * 回车符ASCII码
  32.          */
  33.         private static final short ENTER_ASCII = 13;

  34.         /**
  35.          * 空格符ASCII码
  36.          */
  37.         private static final short SPACE_ASCII = 32;

  38.         /**
  39.          * 水平制表符ASCII码
  40.          */
  41.         private static final short TABULATION_ASCII = 9;

  42.         private static String htmlText = "";
  43.         private static String htmlTextTbl = "";
  44.         private static int counter = 0;
  45.         private static int beginPosi = 0;
  46.         private static int endPosi = 0;
  47.         private static int beginArray[];
  48.         private static int endArray[];
  49.         private static String htmlTextArray[];
  50.         private static boolean tblExist = false;

  51.         /**
  52.          * 项目路径
  53.          */
  54.         private static String projectRealPath = "";
  55.         /**
  56.          * 临时文件路径
  57.          */
  58.         private static String tempPath = "/upfile/" + File.separator + "transferFile" + File.separator;
  59.         /**
  60.          * word文档名称
  61.          */
  62.         private static String wordName = "";

  63.         public static void main(String argv[]) {
  64.                 try {
  65.                         wordToHtml("F:\SVN\BobUtil\web\", "2012年高考广东数学(文)试卷解析(精析word版)(学生版).doc");
  66.                 } catch (Exception e) {
  67.                         e.printStackTrace();
  68.                 }
  69.         }

  70.         /**
  71.          * 读取每个文字样式
  72.          *
  73.          * @param fileName
  74.          * @throws Exception
  75.          */

  76.         private static void getWordAndStyle(String fileName) throws Exception {
  77.                 FileInputStream in = new FileInputStream(new File(fileName));
  78.                 HWPFDocument doc = new HWPFDocument(in);

  79.                 Range rangetbl = doc.getRange();// 得到文档的读取范围
  80.                 TableIterator it = new TableIterator(rangetbl);

  81.                 int num = 100;

  82.                 beginArray = new int[num];
  83.                 endArray = new int[num];
  84.                 htmlTextArray = new String[num];
  85.                 tblExist = false;

  86.                 // 取得文档中字符的总数
  87.                 int length = doc.characterLength();
  88.                 // 创建图片容器
  89.                 PicturesTable pTable = doc.getPicturesTable();
  90.                 // 创建段落容器

  91.                 htmlText = ""<br />                                + doc.getSummaryInformation().getTitle()<br />                                + "[align=center][align=left]";
  92.                 // 创建临时字符串,好加以判断一串字符是否存在相同格式

  93.                 if (it.hasNext()) {
  94.                         readTable(it, rangetbl);
  95.                 }

  96.                 int cur = 0;
  97.                 String tempString = "";
  98.                 for (int i = 0; i < length - 1; i++) {
  99.                         // 整篇文章的字符通过一个个字符的来判断,range为得到文档的范围
  100.                         Range range = new Range(i, i + 1, doc);
  101.                         CharacterRun cr = range.getCharacterRun(0);
  102.                         // beginArray=new int[num];
  103.                         // endArray=new int[num];
  104.                         // htmlTextArray=new String[num];
  105.                         if (tblExist) {
  106.                                 if (i == beginArray[cur]) {
  107.                                         htmlText += tempString + htmlTextArray[cur];
  108.                                         tempString = "";
  109.                                         i = endArray[cur] - 1;
  110.                                         cur++;
  111.                                         continue;
  112.                                 }
  113.                         }
  114.                         if (pTable.hasPicture(cr)) {
  115.                                 htmlText += tempString;
  116.                                 // 读写图片
  117.                                 try {
  118.                                         readPicture(pTable, cr);
  119.                                 } catch (Exception e) {
  120.                                         e.printStackTrace();
  121.                                 }
  122.                                 tempString = "";
  123.                         } else {

  124.                                 Range range2 = new Range(i + 1, i + 2, doc);
  125.                                 // 第二个字符
  126.                                 CharacterRun cr2 = range2.getCharacterRun(0);
  127.                                 char c = cr.text().charAt(0);
  128.                                 // System.out.println(c);
  129.                                 // /System.out.println(i+"::"+range.getEndOffset()+"::"+range.getStartOffset()+"::"+c);

  130.                                 // 判断是否为回车符
  131.                                 if (c == ENTER_ASCII) {
  132.                                         tempString += "
  133. ";
  134.                                 }
  135.                                 // 判断是否为空格符
  136.                                 else if (c == SPACE_ASCII)
  137.                                         tempString += " ";
  138.                                 // 判断是否为水平制表符
  139.                                 else if (c == TABULATION_ASCII)
  140.                                         tempString += "    ";
  141.                                 // 比较前后2个字符是否具有相同的格式
  142.                                 boolean flag = compareCharStyle(cr, cr2);
  143.                                 if (flag)
  144.                                         tempString += cr.text();
  145.                                 else {
  146.                                         String fontStyle = "<span style="\&quot;font-family:&quot;" +="" cr.getfontname()="" ";font-size:"
  147.                                                         + cr.getFontSize() / 2 + "pt;";

  148.                                         if (cr.isBold())
  149.                                                 fontStyle += "font-weight:bold;";
  150.                                         if (cr.isItalic())
  151.                                                 fontStyle += "font-style:italic;";
  152.                                         if (cr.isStrikeThrough())
  153.                                                 fontStyle += "text-decoration:line-through;";

  154.                                         int fontcolor = cr.getIco24();
  155.                                         int[] rgb = new int[3];
  156.                                         if (fontcolor != -1) {
  157.                                                 rgb[0] = (fontcolor >> 0) & 0xff; // red;
  158.                                                 rgb[1] = (fontcolor >> 8) & 0xff; // green
  159.                                                 rgb[2] = (fontcolor >> 16) & 0xff; // blue
  160.                                         }
  161.                                         fontStyle += "color: rgb(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + ");";
  162.                                         htmlText += fontStyle + "\">" + tempString + cr.text() + "";
  163.                                         tempString = "";
  164.                                 }
  165.                         }
  166.                 }

  167.                 htmlText += tempString + "[/align]
  168. [/align]
  169. ";
  170.                 // System.out.println(htmlText);
  171.         }

  172.         /**
  173.          * 读写文档中的表格
  174.          *
  175.          * @param pTable
  176.          * @param cr
  177.          * @throws Exception
  178.          */
  179.         private static void readTable(TableIterator it, Range rangetbl) throws Exception {

  180.                 htmlTextTbl = "";
  181.                 // 迭代文档中的表格

  182.                 counter = -1;
  183.                 while (it.hasNext()) {
  184.                         tblExist = true;
  185.                         htmlTextTbl = "";
  186.                         Table tb = (Table) it.next();
  187.                         beginPosi = tb.getStartOffset();
  188.                         endPosi = tb.getEndOffset();

  189.                         // System.out.println("............"+beginPosi+"...."+endPosi);
  190.                         counter = counter + 1;
  191.                         // 迭代行,默认从0开始
  192.                         beginArray[counter] = beginPosi;
  193.                         endArray[counter] = endPosi;

  194.                         htmlTextTbl += "";
  195.                         for (int i = 0; i < tb.numRows(); i++) {
  196.                                 TableRow tr = tb.getRow(i);

  197.                                 htmlTextTbl += "";
  198.                                 // 迭代列,默认从0开始
  199.                                 for (int j = 0; j < tr.numCells(); j++) {
  200.                                         TableCell td = tr.getCell(j);// 取得单元格
  201.                                         int cellWidth = td.getWidth();

  202.                                         // 取得单元格的内容
  203.                                         for (int k = 0; k < td.numParagraphs(); k++) {
  204.                                                 Paragraph para = td.getParagraph(k);
  205.                                                 CharacterRun crTemp = para.getCharacterRun(0);
  206.                                                 String fontStyle = "<span style="\&quot;font-family:&quot;" +="" crtemp.getfontname()="" ";font-size:"
  207.                                                                 + crTemp.getFontSize() / 2 + "pt;color:" + crTemp.getColor() + ";";

  208.                                                 if (crTemp.isBold())
  209.                                                         fontStyle += "font-weight:bold;";
  210.                                                 if (crTemp.isItalic())
  211.                                                         fontStyle += "font-style:italic;";

  212.                                                 String s = fontStyle + "\">" + para.text().toString().trim() + "";
  213.                                                 if (s == "") {
  214.                                                         s = " ";
  215.                                                 }
  216.                                                 // System.out.println(s);
  217.                                                 htmlTextTbl += "";
  218.                                                 // System.out.println(i + ":" + j + ":" + cellWidth + ":" + s);
  219.                                         } // end for
  220.                                 } // end for
  221.                         } // end for
  222.                         htmlTextTbl += "[table]
  223. [tr][td]" + s + "[/td][/tr]
  224. [/table]";
  225.                         htmlTextArray[counter] = htmlTextTbl;

  226.                 } // end while
  227.         }

  228.         /**
  229.          * 读写文档中的图片
  230.          *
  231.          * @param pTable
  232.          * @param cr
  233.          * @throws Exception
  234.          */
  235.         private static void readPicture(PicturesTable pTable, CharacterRun cr) throws Exception {
  236.                 // 提取图片
  237.                 Picture pic = pTable.extractPicture(cr, false);
  238.                 BufferedImage image = null;// 图片对象
  239.                 // 获取图片样式
  240.                 int picHeight = pic.getHeight() * pic.getAspectRatioY() / 100;
  241.                 int picWidth = pic.getAspectRatioX() * pic.getWidth() / 100;
  242.                 if (picWidth > 500) {
  243.                         picHeight = 500 * picHeight / picWidth;
  244.                         picWidth = 500;
  245.                 }
  246.                 String style = " style='height:" + picHeight + "px;width:" + picWidth + "px'";

  247.                 // 返回POI建议的图片文件名
  248.                 String afileName = pic.suggestFullFileName();
  249.                 //单元测试路径
  250.                 String directory = "images/" + wordName + "/";
  251.                 //项目路径
  252.                 //String directory = tempPath + "images/" + wordName + "/";
  253.                 makeDir(projectRealPath, directory);// 创建文件夹

  254.                 int picSize = cr.getFontSize();
  255.                 int myHeight = 0;

  256.                 if (afileName.indexOf(".wmf") > 0) {
  257.                         OutputStream out = new FileOutputStream(new File(projectRealPath + directory + afileName));
  258.                         out.write(pic.getContent());
  259.                         out.close();
  260.                         afileName = Wmf2Png.convert(projectRealPath + directory + afileName);

  261.                         File file = new File(projectRealPath + directory + afileName);

  262.                         try {
  263.                                 image = ImageIO.read(file);
  264.                         } catch (Exception e) {
  265.                                 e.printStackTrace();
  266.                         }

  267.                         int pheight = image.getHeight();
  268.                         int pwidth = image.getWidth();
  269.                         if (pwidth > 500) {
  270.                                 htmlText += "                                                + afileName + "\"/>";
  271.                         } else {
  272.                                 myHeight = (int) (pheight / (pwidth / (picSize * 1.0)) * 1.5);
  273.                                 htmlText += "";
  274.                         }

  275.                 } else {
  276.                         OutputStream out = new FileOutputStream(new File(projectRealPath + directory + afileName));
  277.                         // pic.writeImageContent(out);
  278.                         out.write(pic.getContent());
  279.                         out.close();
  280.                         // 处理jpg或其他(即除png外)
  281.                         if (afileName.indexOf(".png") == -1) {
  282.                                 try {
  283.                                         File file = new File(projectRealPath + directory + afileName);
  284.                                         image = ImageIO.read(file);
  285.                                         picHeight = image.getHeight();
  286.                                         picWidth = image.getWidth();
  287.                                         if (picWidth > 500) {
  288.                                                 picHeight = 500 * picHeight / picWidth;
  289.                                                 picWidth = 500;
  290.                                         }
  291.                                         style = " style='height:" + picHeight + "px;width:" + picWidth + "px'";
  292.                                 } catch (Exception e) {
  293.                                         // e.printStackTrace();
  294.                                 }
  295.                         }
  296.                         htmlText += "";
  297.                 }
  298.                 if (pic.getWidth() > 450) {
  299.                         htmlText += "
  300. ";
  301.                 }
  302.         }

  303.         private static boolean compareCharStyle(CharacterRun cr1, CharacterRun cr2) {
  304.                 boolean flag = false;
  305.                 if (cr1.isBold() == cr2.isBold() && cr1.isItalic() == cr2.isItalic()
  306.                                 && cr1.getFontName().equals(cr2.getFontName()) && cr1.getFontSize() == cr2.getFontSize()) {
  307.                         flag = true;
  308.                 }
  309.                 return flag;
  310.         }

  311.         /**
  312.          * 写文件(成功返回true,失败则返回false)
  313.          *
  314.          * @param s
  315.          *            要写入的内容
  316.          * @param filePath
  317.          *            文件
  318.          */
  319.         private static boolean writeFile(String s, String filePath) {
  320.                 FileOutputStream fos = null;
  321.                 BufferedWriter bw = null;
  322.                 s = s.replaceAll("EMBED", "").replaceAll("Equation.DSMT4", "");
  323.                 try {
  324.                         makeDir(projectRealPath, tempPath);// 创建文件夹
  325.                         File file = new File(filePath);
  326.                         if (file.exists()) {
  327.                                 return false;
  328.                         }
  329.                         fos = new FileOutputStream(file);
  330.                         bw = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"));
  331.                         bw.write(s);
  332.                         // System.out.println(filePath + "文件写入成功!");
  333.                 } catch (FileNotFoundException fnfe) {
  334.                         fnfe.printStackTrace();
  335.                 } catch (IOException ioe) {
  336.                         ioe.printStackTrace();
  337.                 } finally {
  338.                         try {
  339.                                 if (bw != null)
  340.                                         bw.close();
  341.                                 if (fos != null)
  342.                                         fos.close();
  343.                         } catch (IOException ie) {
  344.                                 ie.printStackTrace();
  345.                         }
  346.                 }
  347.                 return true;
  348.         }

  349.         /**
  350.          * 根据路径名生成多级路径
  351.          *
  352.          * @param url
  353.          *            参数要以"classescnqtone\"或者"/classes/cn/qtone/"
  354.          */
  355.         private static String makeDir(String root, String url) {
  356.                 String[] sub;
  357.                 url = url.replaceAll("\/", "\\");
  358.                 if (url.indexOf("\") > -1) {
  359.                         sub = url.split("\\");
  360.                 } else {
  361.                         return "-1";
  362.                 }

  363.                 File dir = null;
  364.                 try {
  365.                         dir = new File(root);
  366.                         for (int i = 0; i < sub.length; i++) {
  367.                                 if (!dir.exists() && !sub[i].equals("")) {
  368.                                         dir.mkdir();
  369.                                 }
  370.                                 File dir2 = new File(dir + File.separator + sub[i]);
  371.                                 if (!dir2.exists()) {
  372.                                         dir2.mkdir();
  373.                                 }
  374.                                 dir = dir2;
  375.                         }
  376.                 } catch (Exception e) {
  377.                         e.printStackTrace();
  378.                         return "-1";
  379.                 }
  380.                 return dir.toString();
  381.         }

  382.         /**
  383.          * 将word文档转化,返回转化后的文件路径
  384.          *
  385.          * @param projectPath
  386.          *            项目路径
  387.          * @param relativeFilePath
  388.          *            文件相对路径
  389.          * @return 返回生成的htm路径(如果出错,则返回null)
  390.          */
  391.         public static String wordToHtml(String projectPath, String relativeFilePath) {
  392.                 String resultPath = null;
  393.                 projectRealPath = projectPath;// 项目路径
  394.                 String filePath = "";
  395.                 // System.out.println(projectRealPath + tempPath);
  396.                 // System.out.println(makeDir(projectRealPath, tempPath));
  397.                 try {
  398.                         File file = new File(projectPath + relativeFilePath);
  399.                         if (file.exists()) {
  400.                                 if (file.getName().indexOf(".doc") == -1 || file.getName().indexOf(".docx") > 0) {
  401.                                         throw new FileFormatException("请确认文件格式为doc!");
  402.                                 } else {
  403.                                         wordName = file.getName();
  404.                                         wordName = wordName.substring(0, wordName.indexOf("."));

  405.                                         filePath = projectRealPath + tempPath + wordName + ".htm";
  406.                                         synchronized (relativeFilePath) {// 处理线程同步问题
  407.                                                 File ff = new File(filePath);
  408.                                                 if (!ff.exists()) {// 如果不存在则进行转换
  409.                                                         getWordAndStyle(projectPath + relativeFilePath);
  410.                                                         writeFile(htmlText, filePath);
  411.                                                 }
  412.                                         }
  413.                                         resultPath = tempPath + wordName + ".htm";
  414.                                 }
  415.                         } else {
  416.                                 throw new FileNotFoundException("没找到相关文件!");
  417.                         }
  418.                 } catch (NullPointerException e) {
  419.                         e.printStackTrace();
  420.                 } catch (FileNotFoundException e) {
  421.                         e.printStackTrace();
  422.                 } catch (Exception e) {
  423.                         e.printStackTrace();
  424.                 }
  425.                 return resultPath;
  426.         }
  427. }
复制代码
  1. package com;

  2. import java.io.ByteArrayInputStream;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.FileOutputStream;
  7. import java.io.InputStream;
  8. import java.io.OutputStream;
  9. import java.util.Scanner;
  10. import java.util.zip.GZIPOutputStream;

  11. import javax.xml.parsers.DocumentBuilder;
  12. import javax.xml.parsers.DocumentBuilderFactory;
  13. import javax.xml.transform.OutputKeys;
  14. import javax.xml.transform.Transformer;
  15. import javax.xml.transform.TransformerFactory;
  16. import javax.xml.transform.dom.DOMSource;
  17. import javax.xml.transform.stream.StreamResult;

  18. import net.arnx.wmf2svg.gdi.svg.SvgGdi;
  19. import net.arnx.wmf2svg.gdi.wmf.WmfParser;

  20. import org.apache.batik.transcoder.TranscoderInput;
  21. import org.apache.batik.transcoder.TranscoderOutput;
  22. import org.apache.batik.transcoder.TranscodingHints;
  23. import org.apache.batik.transcoder.image.PNGTranscoder;
  24. import org.apache.batik.transcoder.wmf.tosvg.WMFTranscoder;
  25. import org.apache.commons.lang.StringUtils;
  26. import org.w3c.dom.Document;
  27. import org.w3c.dom.Element;

  28. public class Wmf2Png {
  29.         public static void main(String[] args) throws Exception {
  30.                 // convert("F:\SVN\BobUtil\web\25177.wmf");
  31.                 // System.out.println((20 / (21 * 1.0)));
  32.                 // svgToPng("F:\SVN\BobUtil\web\25177.svg", "F:\SVN\BobUtil\web\25177.png");
  33.         }

  34.         /**
  35.          * @Description: 进行转换
  36.          * @param filePath
  37.          *            文件路径
  38.          * @return 设定文件
  39.          */
  40.         public static String convert(String filePath) {
  41.                 String pngFile = "";
  42.                 File wmfFile = new File(filePath);
  43.                 try {
  44.                         if (!wmfFile.getName().contains(".wmf")) {
  45.                                 throw new Exception("请确认输入的文件类型是wmf");
  46.                         }
  47.                         // wmf -> svg
  48.                         String svgFile = filePath.replace("wmf", "svg");
  49.                         wmfToSvg(filePath, svgFile);
  50.                         // 对svg做预出理
  51.                         PreprocessSvgFile(svgFile);
  52.                         // svg -> png
  53.                         pngFile = filePath.replace("wmf", "png");
  54.                         svgToPng(svgFile, pngFile);
  55.                         // 删除 svg
  56.                         File file = new File(svgFile);
  57.                         if (file.exists()) {
  58.                                 file.delete();
  59.                         }
  60.                         // 删除 wmf
  61.                         if (wmfFile.exists()) {
  62.                                 wmfFile.delete();
  63.                         }

  64.                 } catch (Exception e) {
  65.                         try {
  66.                                 e.printStackTrace();
  67.                                 wmfToJpg(filePath);
  68.                         } catch (Exception e1) {
  69.                                 e1.printStackTrace();
  70.                         }
  71.                 }
  72.                 return wmfFile.getName().replace("wmf", "png");
  73.         }

  74.         /**
  75.          * 将wmf转换为svg
  76.          *
  77.          * @param src
  78.          * @param dest
  79.          */
  80.         public static void wmfToSvg(String src, String dest) throws Exception {
  81.                 boolean compatible = false;
  82.                 try {
  83.                         InputStream in = new FileInputStream(src);
  84.                         WmfParser parser = new WmfParser();
  85.                         final SvgGdi gdi = new SvgGdi(compatible);
  86.                         parser.parse(in, gdi);

  87.                         Document doc = gdi.getDocument();
  88.                         OutputStream out = new FileOutputStream(dest);
  89.                         if (dest.endsWith(".svgz")) {
  90.                                 out = new GZIPOutputStream(out);
  91.                         }

  92.                         output(doc, out);
  93.                 } catch (Exception e) {
  94.                         throw e;
  95.                 }
  96.         }

  97.         /**
  98.          * @Description: 输出svg文件
  99.          * @param doc
  100.          * @param out
  101.          * @throws Exception
  102.          *             设定文件
  103.          */
  104.         private static void output(Document doc, OutputStream out) throws Exception {
  105.                 TransformerFactory factory = TransformerFactory.newInstance();
  106.                 Transformer transformer = factory.newTransformer();
  107.                 transformer.setOutputProperty(OutputKeys.METHOD, "xml");
  108.                 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
  109.                 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  110.                 transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//W3C//DTD SVG 1.0//EN");
  111.                 transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
  112.                                 "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd");
  113.                 transformer.transform(new DOMSource(doc), new StreamResult(out));
  114.                 out.flush();
  115.                 out.close();
  116.                 out = null;
  117.         }

  118.         /**
  119.          * @Description:对svg文件做预处理(这里主要是调整大小,先缩小10倍,如果还大于默认值,则按比例缩小)
  120.          * @param svgFile
  121.          * @throws Exception
  122.          *             设定文件
  123.          */
  124.         private static void PreprocessSvgFile(String svgFile) throws Exception {
  125.                 int defaultWeight = 500;// 默认宽度
  126.                 FileInputStream inputs = new FileInputStream(svgFile);
  127.                 Scanner sc = new Scanner(inputs, "UTF-8");
  128.                 ByteArrayOutputStream os = new ByteArrayOutputStream();
  129.                 while (sc.hasNextLine()) {
  130.                         String ln = sc.nextLine();
  131.                         if (!ln.startsWith("                                os.write((ln + "").getBytes());
  132.                         }
  133.                 }
  134.                 os.flush();
  135.                
  136.                 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  137.                 DocumentBuilder builder;
  138.                 builder = factory.newDocumentBuilder();
  139.                 Document doc = null;
  140.                 try {
  141.                         doc = builder.parse(new ByteArrayInputStream(os.toByteArray()));
  142.                 } catch (Exception e) {
  143.                         inputs = new FileInputStream(svgFile);
  144.                         os = new ByteArrayOutputStream();
  145.                         int noOfByteRead = 0;
  146.                         while ((noOfByteRead = inputs.read()) != -1) {
  147.                                 os.write(noOfByteRead);
  148.                         }
  149.                         os.flush();
  150.                         doc = builder.parse(new ByteArrayInputStream(os.toByteArray()));
  151.                 } finally {
  152.                         os.close();
  153.                         inputs.close();
  154.                 }
  155.                
  156.                 int height = Integer.parseInt(((Element) doc.getElementsByTagName("svg").item(0)).getAttribute("height"));
  157.                 int width = Integer.parseInt(((Element) doc.getElementsByTagName("svg").item(0)).getAttribute("width"));
  158.                 int newHeight = 0;// 新高
  159.                 int newWidth = 0;// 新宽
  160.                 newHeight = height / 10;// 高缩小10倍
  161.                 newWidth = width / 10; // 宽缩小10倍
  162.                 // 如果缩小10倍后宽度还比defaultHeight大,则进行调整
  163.                 if (newWidth > defaultWeight) {
  164.                         newWidth = defaultWeight;
  165.                         newHeight = defaultWeight * height / width;
  166.                 }

  167.                 ((Element) doc.getElementsByTagName("svg").item(0)).setAttribute("width", String.valueOf(newWidth));
  168.                 ((Element) doc.getElementsByTagName("svg").item(0)).setAttribute("height", String.valueOf(newHeight));
  169.                 OutputStream out = new FileOutputStream(svgFile);
  170.                 output(doc, out);
  171.         }

  172.         /**
  173.          * 将svg图片转成png图片
  174.          *
  175.          * @param filePath
  176.          * @throws Exception
  177.          */
  178.         public static void svgToPng(String svgPath, String pngFile) throws Exception {
  179.                 File svg = new File(svgPath);
  180.                 FileInputStream wmfStream = new FileInputStream(svg);
  181.                 ByteArrayOutputStream imageOut = new ByteArrayOutputStream();
  182.                 int noOfByteRead = 0;
  183.                 while ((noOfByteRead = wmfStream.read()) != -1) {
  184.                         imageOut.write(noOfByteRead);
  185.                 }
  186.                 imageOut.flush();
  187.                 imageOut.close();
  188.                 wmfStream.close();

  189.                 ByteArrayOutputStream jpg = new ByteArrayOutputStream();
  190.                 FileOutputStream jpgOut = new FileOutputStream(pngFile);

  191.                 byte[] bytes = imageOut.toByteArray();
  192.                 PNGTranscoder t = new PNGTranscoder();
  193.                 TranscoderInput in = new TranscoderInput(new ByteArrayInputStream(bytes));
  194.                 TranscoderOutput out = new TranscoderOutput(jpg);
  195.                 t.transcode(in, out);
  196.                 jpgOut.write(jpg.toByteArray());
  197.                 jpgOut.flush();
  198.                 jpgOut.close();
  199.                 imageOut = null;
  200.                 jpgOut = null;
  201.         }

  202.         /**
  203.          * 将wmf图片转成png图片(备用方法,即当上面的转换失败时用这个)
  204.          *
  205.          * @param filePath
  206.          * @throws Exception
  207.          */
  208.         public static String wmfToJpg(String wmfPath) throws Exception {
  209.                 //先wmf-->svg
  210.                 File wmf = new File(wmfPath);
  211.                 FileInputStream wmfStream = new FileInputStream(wmf);
  212.                 ByteArrayOutputStream imageOut = new ByteArrayOutputStream();
  213.                 int noOfByteRead = 0;
  214.                 while ((noOfByteRead = wmfStream.read()) != -1) {
  215.                         imageOut.write(noOfByteRead);
  216.                 }
  217.                 imageOut.flush();
  218.                 imageOut.close();
  219.                 wmfStream.close();

  220.                 // WMFHeaderProperties prop = new WMFHeaderProperties(wmf);
  221.                 WMFTranscoder transcoder = new WMFTranscoder();
  222.                 TranscodingHints hints = new TranscodingHints();
  223.                 transcoder.setTranscodingHints(hints);
  224.                 TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(imageOut.toByteArray()));
  225.                 ByteArrayOutputStream svg = new ByteArrayOutputStream();
  226.                 TranscoderOutput output = new TranscoderOutput(svg);
  227.                 transcoder.transcode(input, output);
  228.                
  229.                 //再svg-->png
  230.                 ByteArrayOutputStream jpg = new ByteArrayOutputStream();
  231.                 String jpgFile = StringUtils.replace(wmfPath, "wmf", "png");
  232.                 FileOutputStream jpgOut = new FileOutputStream(jpgFile);

  233.                 byte[] bytes = svg.toByteArray();
  234.                 PNGTranscoder t = new PNGTranscoder();
  235.                 TranscoderInput in = new TranscoderInput(new ByteArrayInputStream(bytes));
  236.                 TranscoderOutput out = new TranscoderOutput(jpg);
  237.                 t.transcode(in, out);
  238.                 jpgOut.write(jpg.toByteArray());
  239.                 jpgOut.flush();
  240.                 jpgOut.close();
  241.                 return jpgFile;
  242.         }
  243. }
复制代码

重点难点解释探讨:

1)  读取表格部分:

a)        找出表格的开始与结束标记;

b)        遍历整个表格内容,逐个单元格的内容取出并追加到变量中。

2)  读取图片部分

a)        图片文件的格式问题。

如果图片格式为png或者jpg,则可以直接进行处理并加入标签中,前台的html展示没有问题,但是,如果图片格式为wmf(详细看附录1),则html无法对基解释,那么我们只能对其进行转换格式:

百度后,网上很多说法都建议用batik工具包进行格式转换,其实思路就是:wmfàsvgàpng。查阅相关资料(如附录2),发现其处理svg文件的能力相当的强,即从svg—>png这一步是比较完美的。但是,在处理wmf—>svg这一步却导致部分图像丢失,即失真的情况,且很严重。查看相关的api看是否参数设置问题,但是无论怎么设置,结果还是不尽人意。一度想放弃,找别的包。

后来,无意中,在csdn中有网友建议先用wmf2svg工具类将wmf转换为svg,再用batik将svg转换为png。Very good!!有了这个思路,感觉已经看到署光了。

类写出来后,进行类型转换测试,确实效果很好,完全没有失真。于是将其嵌入word—>html这个工具类中。再用各种包含了wmf图片的文档进行测试。生成的html文件,基本没有问题,当时那个开心啊!!(我去,程序员也就这德行)

好景不长,放到正式项目进行测试过程中,发现有个别文档一进行转换,服务器就跨了,直接报内存溢出。通过排查检测,原来就是进行图片转换过程中,将内存给挤爆了。奇怪了,虽然知道图片处理是比较耗内存,但也没想到1G的内存,一下子就被挤爆(刚跑起来占去300M左右,一跑word转换功能,不过一会就报OutOfMemorry)。

一度怀疑,是不是batik这个工具包是不是有bug,处理不了大的svg。还将问题放上了bakit的官网。后来,查看相关资料后,发现是wmf2svg工具生成的svg的高与宽都太大了,举个例子:15040* 13088,宽高都达到上万级别,结果得到的象素是上亿的,不爆内存才怪。

用dom工具,将每一个生成的svg文件再进行预处理,即将其高与宽都先缩小一倍,如果宽度依然比500要大,则将其设成500,并将高也按比例缩小。经过此步骤生成的svg再用batik进行转换就没有任何问题了。

到这里,差不多已经解决图片转换的问题了,但是,在使用过程中,发现wmf2svg这个工具也不是很稳定,偶尔会报异常,并且,我测试发现,报异常的这个wmf用之前batik直接进行wmf—>svgàpng的方案可以成功生成没有失真的png,于是,在wmf2svg的产生异常进行捕捉,并调用了wmfToJpg(String wmfPath)的备用方法。到此,大部分的wmf转换问题已经解决。

b)        生成html文本的标签的width与height问题。

如果图片格式原本为png的话,直接用

  1. // 获取图片样式
  2. intpicHeight = pic.getHeight() * pic.getAspectRatioY() / 100;
复制代码
  1.   intpicWidth = pic.getAspectRatioX() * pic.getWidth() / 100;
复制代码

即可以将图片的宽与高设置与word文档一致;但是,发果wmf格式,要分两种情况分析:


Ø  如果转换生成的png宽度不小于500,则将期作为一般图片处理:

  1. BufferedImage  image = ImageIO.read(file);
  2. int pheight = image.getHeight();
  3. int pwidth = image.getWidth();
复制代码
如果转换生成的png宽度小于500,则认为是一般的公式,则应该与它旁边的字体宽度相近,这里设成字体的1.5倍宽度,高度为:
  1. myHeight= (int) (pheight / (pwidth / (picSize * 1.0)) * 1.5);
复制代码
如果图片即非wmf与非png(如jpg)的情况下,上面获取高与宽的方法不起作用,不知道是不是POI的bug。只能按以下方式处理:
  1. BufferedImage  image = ImageIO.read(file);
  2. int pheight = image.getHeight();
  3. int pwidth = image.getWidth();
复制代码

即跟上面处理wmf的第一种方式一致。

三、结束语

讲到这,将word转换成html的处理也大体上讲完了。这几天的边学边用,特别是真正能解决问题的时候,非常有成就感。其实,上面的处理还存在以下的问题待解决的:

1)读取表格部分:

a)        表格中如果再含有表格,POI无法进行很好的区分,比如,有一个两行两列的表格中,第一行第一列中又包含了一个两行两列的表格,那POI会将此表格解释成:第一行为2+2*2 = 6个单元格;第二行为2个单元格,这样解释出来的表格就很怪异了。

b)        表格中有果有合并单格的情况,程序暂未做此处理(后续看不能优化),表格也很怪异。

c)        表格中如果有图像,程序没有做相应的处理。

2)读取图片部分:

a) 有部分wmf->png的方式有个别图片还是没有转换成功,会报异常,但没有影响整体的功能;

b) word有部分公式生成的图片无法识别模式,不知道是不是POI无法将其解释,还是其他原因,就是有文档,生成没有后缀的图片文件,且这部分文件无法读取,用图片工具也打不开,暂时未找到很好的解决方案。

3)读取word的目录:

在读取目录会出现将格式化符号也解释出来。

4)其他未知的一些问题,反正,就觉得用POI来解释word是件很坚苦的事情,如果全是文本还好,如果里面包含图片,表格,公式等这些对象的时候,POI就显得太弱了。




附:

[url=]1.       wmf[/url]文件:

MicrosoftOffice 的剪贴画使用的就是这个格式。

Wmf是WindowsMetafile 的缩写,简称图元文件,它是微软公司定义的一种Windows平台下的图形文件格式。

wmf格式文件的特点如下:

1)                 wmf格式文件是MicrosoftWindows操作平台所支持的一种图形格式文件,目前,其它操作系统尚不支持这种格式,如Unix、Linux等。

2)                 与bmp格式不同,wmf格式文件是和设备无关的,即它的输出特性不依赖于具体的输出设备。

3)                 其图象完全由Win32 API所拥有的GDI函数来完成。

4)                 wmf格式文件所占的磁盘空间比其它任何格式的图形文件都要小得多。

5)                 在建立图元文件时,不能实现即画即得,而是将GDI调用记录在图元文件中,之后,在GDI环境中重新执行,才可显示图象。

6)                 显示图元文件的速度要比显示其它格式的图象文件慢,但是它形成图元文件的速度要远大于其它格式。

2.      Batik介绍

Batik是使用svg格式图片来实现各种功能的应用程序以及Applet提供的一个基于java的工具包。

通过Batik,你可以在JAVA可以使用的地方操作SVG文档,您还可以在你的应用程序使用Batik模块来生成, 处理和转码SVG图像。Batik很容易让基于Java的应用程序或小程序来处理SVG内容。 例如,使用Batik的SVG的发生器模块 ,Java应用程序或小程序可以很轻松地导出SVG格式的图形到。用Batik的SVG的查看组件,应用程序或小程序可以很容易地集成SVG的浏览和交互功能。另一种可能性是使用Batik的模块转换成各种格式SVG的通过,如光栅图像(JPEG,PNG或TIFF格式)或其它矢量格式(EPS或PDF格式,后两者由于转码器由Apache FOP提供)。 Batik工程创建的目的是为开发者提供一系列可以结合或单独使用来支持特殊的svg解决方案的核心模块。模块主要有SVGParser,SVGGernerator,SVGDOM。Batik工程的其他目的是使它具有高度的扩展性。

(SVG的规范:可缩放矢量图形(SVG),是一个W3C的推荐标准。 它定义了丰富的2D图形的XML语法,其中包括诸如透明度功能,几何形状,滤镜效果(阴影,灯光效果等),脚本和动画)

3.本实例相关的项目文件:点击打开链接


收藏回复 只看该作者 道具 举报

高级模式
B Color Image Link Quote Code Smilies



QQ|小黑屋| 码途山海.智隐长卷 渝ICP备15002301号-2   渝公网安备50011202504426

GMT+8, 2025-5-18 05:18 , Processed in 0.050589 second(s), 24 queries .

©Copyright 程序人生!

©2012-2015重庆纽新

快速回复 返回顶部 返回列表