利用POI将word转换成html实现在线阅读

利用POI将word转换成html实现在线阅读

一、分析

通过网上找资料,发现用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+JodConverter将word2003转换成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.      代码实现

[java] view plain copy
  1. package com;  
  2.   
  3. import java.awt.image.BufferedImage;  
  4. import java.io.BufferedWriter;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.FileNotFoundException;  
  8. import java.io.FileOutputStream;  
  9. import java.io.IOException;  
  10. import java.io.OutputStream;  
  11. import java.io.OutputStreamWriter;  
  12.   
  13. import javax.imageio.ImageIO;  
  14.   
  15. import org.apache.poi.hwpf.HWPFDocument;  
  16. import org.apache.poi.hwpf.model.PicturesTable;  
  17. import org.apache.poi.hwpf.usermodel.CharacterRun;  
  18. import org.apache.poi.hwpf.usermodel.Paragraph;  
  19. import org.apache.poi.hwpf.usermodel.Picture;  
  20. import org.apache.poi.hwpf.usermodel.Range;  
  21. import org.apache.poi.hwpf.usermodel.Table;  
  22. import org.apache.poi.hwpf.usermodel.TableCell;  
  23. import org.apache.poi.hwpf.usermodel.TableIterator;  
  24. import org.apache.poi.hwpf.usermodel.TableRow;  
  25. import org.apache.xmlbeans.impl.piccolo.io.FileFormatException;  
  26.   
  27.   
  28. /** 
  29.  * @Description: 利用poi将word简单的转换成html文件 
  30.  * @author 柯颖波 
  31.  * @date 2013-12-20 上午09:32:44 
  32.  * @version v1.0 
  33.  */  
  34. public class Word2Html {  
  35.     /** 
  36.      * 回车符ASCII码 
  37.      */  
  38.     private static final short ENTER_ASCII = 13;  
  39.   
  40.     /** 
  41.      * 空格符ASCII码 
  42.      */  
  43.     private static final short SPACE_ASCII = 32;  
  44.   
  45.     /** 
  46.      * 水平制表符ASCII码 
  47.      */  
  48.     private static final short TABULATION_ASCII = 9;  
  49.   
  50.     private static String htmlText = "";  
  51.     private static String htmlTextTbl = "";  
  52.     private static int counter = 0;  
  53.     private static int beginPosi = 0;  
  54.     private static int endPosi = 0;  
  55.     private static int beginArray[];  
  56.     private static int endArray[];  
  57.     private static String htmlTextArray[];  
  58.     private static boolean tblExist = false;  
  59.   
  60.     /** 
  61.      * 项目路径 
  62.      */  
  63.     private static String projectRealPath = "";  
  64.     /** 
  65.      * 临时文件路径 
  66.      */  
  67.     private static String tempPath = "/upfile/" + File.separator + "transferFile" + File.separator;  
  68.     /** 
  69.      * word文档名称 
  70.      */  
  71.     private static String wordName = "";  
  72.   
  73.     public static void main(String argv[]) {  
  74.         try {  
  75.             wordToHtml("F:\\SVN\\BobUtil\\web\\", "2012年高考广东数学(文)试卷解析(精析word版)(学生版).doc");  
  76.         } catch (Exception e) {  
  77.             e.printStackTrace();  
  78.         }  
  79.     }  
  80.   
  81.     /** 
  82.      * 读取每个文字样式 
  83.      *  
  84.      * @param fileName 
  85.      * @throws Exception 
  86.      */  
  87.   
  88.     private static void getWordAndStyle(String fileName) throws Exception {  
  89.         FileInputStream in = new FileInputStream(new File(fileName));  
  90.         HWPFDocument doc = new HWPFDocument(in);  
  91.   
  92.         Range rangetbl = doc.getRange();// 得到文档的读取范围  
  93.         TableIterator it = new TableIterator(rangetbl);  
  94.   
  95.         int num = 100;  
  96.   
  97.         beginArray = new int[num];  
  98.         endArray = new int[num];  
  99.         htmlTextArray = new String[num];  
  100.         tblExist = false;  
  101.   
  102.         // 取得文档中字符的总数  
  103.         int length = doc.characterLength();  
  104.         // 创建图片容器  
  105.         PicturesTable pTable = doc.getPicturesTable();  
  106.         // 创建段落容器  
  107.   
  108.         htmlText = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><title>"  
  109.                 + doc.getSummaryInformation().getTitle()  
  110.                 + "</title></head><body><div style='margin:60px;text-align:center;'><div style='width:620px;text-align:left;line-height:24px;'>";  
  111.         // 创建临时字符串,好加以判断一串字符是否存在相同格式  
  112.   
  113.         if (it.hasNext()) {  
  114.             readTable(it, rangetbl);  
  115.         }  
  116.   
  117.         int cur = 0;  
  118.         String tempString = "";  
  119.         for (int i = 0; i < length - 1; i++) {  
  120.             // 整篇<span class="wp_keywordlink"><a target=_blank href="http://www.it-crazy.com/" title="文章" target="_blank">文章</a></span>的字符通过一个个字符的来判断,range为得到文档的范围  
  121.             Range range = new Range(i, i + 1, doc);  
  122.             CharacterRun cr = range.getCharacterRun(0);  
  123.             // beginArray=new int[num];  
  124.             // endArray=new int[num];  
  125.             // htmlTextArray=new String[num];  
  126.             if (tblExist) {  
  127.                 if (i == beginArray[cur]) {  
  128.                     htmlText += tempString + htmlTextArray[cur];  
  129.                     tempString = "";  
  130.                     i = endArray[cur] - 1;  
  131.                     cur++;  
  132.                     continue;  
  133.                 }  
  134.             }  
  135.             if (pTable.hasPicture(cr)) {  
  136.                 htmlText += tempString;  
  137.                 // 读写图片  
  138.                 try {  
  139.                     readPicture(pTable, cr);  
  140.                 } catch (Exception e) {  
  141.                     e.printStackTrace();  
  142.                 }  
  143.                 tempString = "";  
  144.             } else {  
  145.   
  146.                 Range range2 = new Range(i + 1, i + 2, doc);  
  147.                 // 第二个字符  
  148.                 CharacterRun cr2 = range2.getCharacterRun(0);  
  149.                 char c = cr.text().charAt(0);  
  150.                 // System.out.println(c);  
  151.                 // /System.out.println(i+"::"+range.getEndOffset()+"::"+range.getStartOffset()+"::"+c);  
  152.   
  153.                 // 判断是否为回车符  
  154.                 if (c == ENTER_ASCII) {  
  155.                     tempString += "<br/>";  
  156.                 }  
  157.                 // 判断是否为空格符  
  158.                 else if (c == SPACE_ASCII)  
  159.                     tempString += " ";  
  160.                 // 判断是否为水平制表符  
  161.                 else if (c == TABULATION_ASCII)  
  162.                     tempString += "    ";  
  163.                 // 比较前后2个字符是否具有相同的格式  
  164.                 boolean flag = compareCharStyle(cr, cr2);  
  165.                 if (flag)  
  166.                     tempString += cr.text();  
  167.                 else {  
  168.                     String fontStyle = "<span style=\"font-family:" + cr.getFontName() + ";font-size:"  
  169.                             + cr.getFontSize() / 2 + "pt;";  
  170.   
  171.                     if (cr.isBold())  
  172.                         fontStyle += "font-weight:bold;";  
  173.                     if (cr.isItalic())  
  174.                         fontStyle += "font-style:italic;";  
  175.                     if (cr.isStrikeThrough())  
  176.                         fontStyle += "text-decoration:line-through;";  
  177.   
  178.                     int fontcolor = cr.getIco24();  
  179.                     int[] rgb = new int[3];  
  180.                     if (fontcolor != -1) {  
  181.                         rgb[0] = (fontcolor >> 0) & 0xff// red;  
  182.                         rgb[1] = (fontcolor >> 8) & 0xff// green  
  183.                         rgb[2] = (fontcolor >> 16) & 0xff// blue  
  184.                     }  
  185.                     fontStyle += "color: rgb(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + ");";  
  186.                     htmlText += fontStyle + "\">" + tempString + cr.text() + "</span>";  
  187.                     tempString = "";  
  188.                 }  
  189.             }  
  190.         }  
  191.   
  192.         htmlText += tempString + "</div></div></body></html>";  
  193.         // System.out.println(htmlText);  
  194.     }  
  195.   
  196.     /** 
  197.      * 读写文档中的表格 
  198.      *  
  199.      * @param pTable 
  200.      * @param cr 
  201.      * @throws Exception 
  202.      */  
  203.     private static void readTable(TableIterator it, Range rangetbl) throws Exception {  
  204.   
  205.         htmlTextTbl = "";  
  206.         // 迭代文档中的表格  
  207.   
  208.         counter = -1;  
  209.         while (it.hasNext()) {  
  210.             tblExist = true;  
  211.             htmlTextTbl = "";  
  212.             Table tb = (Table) it.next();  
  213.             beginPosi = tb.getStartOffset();  
  214.             endPosi = tb.getEndOffset();  
  215.   
  216.             // System.out.println("............"+beginPosi+"...."+endPosi);  
  217.             counter = counter + 1;  
  218.             // 迭代行,默认从0开始  
  219.             beginArray[counter] = beginPosi;  
  220.             endArray[counter] = endPosi;  
  221.   
  222.             htmlTextTbl += "<table border='1' cellpadding='0' cellspacing='0' >";  
  223.             for (int i = 0; i < tb.numRows(); i++) {  
  224.                 TableRow tr = tb.getRow(i);  
  225.   
  226.                 htmlTextTbl += "<tr align='center'>";  
  227.                 // 迭代列,默认从0开始  
  228.                 for (int j = 0; j < tr.numCells(); j++) {  
  229.                     TableCell td = tr.getCell(j);// 取得单元格  
  230.                     int cellWidth = td.getWidth();  
  231.   
  232.                     // 取得单元格的内容  
  233.                     for (int k = 0; k < td.numParagraphs(); k++) {  
  234.                         Paragraph para = td.getParagraph(k);  
  235.                         CharacterRun crTemp = para.getCharacterRun(0);  
  236.                         String fontStyle = "<span style=\"font-family:" + crTemp.getFontName() + ";font-size:"  
  237.                                 + crTemp.getFontSize() / 2 + "pt;color:" + crTemp.getColor() + ";";  
  238.   
  239.                         if (crTemp.isBold())  
  240.                             fontStyle += "font-weight:bold;";  
  241.                         if (crTemp.isItalic())  
  242.                             fontStyle += "font-style:italic;";  
  243.   
  244.                         String s = fontStyle + "\">" + para.text().toString().trim() + "</span>";  
  245.                         if (s == "") {  
  246.                             s = " ";  
  247.                         }  
  248.                         // System.out.println(s);  
  249.                         htmlTextTbl += "<td width=" + cellWidth + ">" + s + "</td>";  
  250.                         // System.out.println(i + ":" + j + ":" + cellWidth + ":" + s);  
  251.                     } // end for  
  252.                 } // end for  
  253.             } // end for  
  254.             htmlTextTbl += "</table>";  
  255.             htmlTextArray[counter] = htmlTextTbl;  
  256.   
  257.         } // end while  
  258.     }  
  259.   
  260.     /** 
  261.      * 读写文档中的图片 
  262.      *  
  263.      * @param pTable 
  264.      * @param cr 
  265.      * @throws Exception 
  266.      */  
  267.     private static void readPicture(PicturesTable pTable, CharacterRun cr) throws Exception {  
  268.         // 提取图片  
  269.         Picture pic = pTable.extractPicture(cr, false);  
  270.         BufferedImage image = null;// 图片对象  
  271.         // 获取图片样式  
  272.         int picHeight = pic.getHeight() * pic.getAspectRatioY() / 100;  
  273.         int picWidth = pic.getAspectRatioX() * pic.getWidth() / 100;  
  274.         if (picWidth > 500) {  
  275.             picHeight = 500 * picHeight / picWidth;  
  276.             picWidth = 500;  
  277.         }  
  278.         String style = " style='height:" + picHeight + "px;width:" + picWidth + "px'";  
  279.   
  280.         // 返回POI建议的图片文件名  
  281.         String afileName = pic.suggestFullFileName();  
  282.         //单元测试路径  
  283.         String directory = "images/" + wordName + "/";  
  284.         //项目路径  
  285.         //String directory = tempPath + "images/" + wordName + "/";  
  286.         makeDir(projectRealPath, directory);// 创建文件夹  
  287.   
  288.         int picSize = cr.getFontSize();  
  289.         int myHeight = 0;  
  290.   
  291.         if (afileName.indexOf(".wmf") > 0) {  
  292.             OutputStream out = new FileOutputStream(new File(projectRealPath + directory + afileName));  
  293.             out.write(pic.getContent());  
  294.             out.close();  
  295.             afileName = Wmf2Png.convert(projectRealPath + directory + afileName);  
  296.   
  297.             File file = new File(projectRealPath + directory + afileName);  
  298.   
  299.             try {  
  300.                 image = ImageIO.read(file);  
  301.             } catch (Exception e) {  
  302.                 e.printStackTrace();  
  303.             }  
  304.   
  305.             int pheight = image.getHeight();  
  306.             int pwidth = image.getWidth();  
  307.             if (pwidth > 500) {  
  308.                 htmlText += "<img style='width:" + pwidth + "px;height:" + myHeight + "px'" + " src=\"" + directory  
  309.                         + afileName + "\"/>";  
  310.             } else {  
  311.                 myHeight = (int) (pheight / (pwidth / (picSize * 1.0)) * 1.5);  
  312.                 htmlText += "<img style='vertical-align:middle;width:" + picSize * 1.5 + "px;height:" + myHeight  
  313.                         + "px'" + " src=\"" + directory + afileName + "\"/>";  
  314.             }  
  315.   
  316.         } else {  
  317.             OutputStream out = new FileOutputStream(new File(projectRealPath + directory + afileName));  
  318.             // pic.writeImageContent(out);  
  319.             out.write(pic.getContent());  
  320.             out.close();  
  321.             // 处理jpg或其他(即除png外)  
  322.             if (afileName.indexOf(".png") == -1) {  
  323.                 try {  
  324.                     File file = new File(projectRealPath + directory + afileName);  
  325.                     image = ImageIO.read(file);  
  326.                     picHeight = image.getHeight();  
  327.                     picWidth = image.getWidth();  
  328.                     if (picWidth > 500) {  
  329.                         picHeight = 500 * picHeight / picWidth;  
  330.                         picWidth = 500;  
  331.                     }  
  332.                     style = " style='height:" + picHeight + "px;width:" + picWidth + "px'";  
  333.                 } catch (Exception e) {  
  334.                     // e.printStackTrace();  
  335.                 }  
  336.             }  
  337.             htmlText += "<img " + style + " src=\"" + directory + afileName + "\"/>";  
  338.         }  
  339.         if (pic.getWidth() > 450) {  
  340.             htmlText += "<br/>";  
  341.         }  
  342.     }  
  343.   
  344.     private static boolean compareCharStyle(CharacterRun cr1, CharacterRun cr2) {  
  345.         boolean flag = false;  
  346.         if (cr1.isBold() == cr2.isBold() && cr1.isItalic() == cr2.isItalic()  
  347.                 && cr1.getFontName().equals(cr2.getFontName()) && cr1.getFontSize() == cr2.getFontSize()) {  
  348.             flag = true;  
  349.         }  
  350.         return flag;  
  351.     }  
  352.   
  353.     /** 
  354.      * 写文件(成功返回true,失败则返回false) 
  355.      *  
  356.      * @param s 
  357.      *            要写入的内容 
  358.      * @param filePath 
  359.      *            文件 
  360.      */  
  361.     private static boolean writeFile(String s, String filePath) {  
  362.         FileOutputStream fos = null;  
  363.         BufferedWriter bw = null;  
  364.         s = s.replaceAll("EMBED""").replaceAll("Equation.DSMT4""");  
  365.         try {  
  366.             makeDir(projectRealPath, tempPath);// 创建文件夹  
  367.             File file = new File(filePath);  
  368.             if (file.exists()) {  
  369.                 return false;  
  370.             }  
  371.             fos = new FileOutputStream(file);  
  372.             bw = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"));  
  373.             bw.write(s);  
  374.             // System.out.println(filePath + "文件写入成功!");  
  375.         } catch (FileNotFoundException fnfe) {  
  376.             fnfe.printStackTrace();  
  377.         } catch (IOException ioe) {  
  378.             ioe.printStackTrace();  
  379.         } finally {  
  380.             try {  
  381.                 if (bw != null)  
  382.                     bw.close();  
  383.                 if (fos != null)  
  384.                     fos.close();  
  385.             } catch (IOException ie) {  
  386.                 ie.printStackTrace();  
  387.             }  
  388.         }  
  389.         return true;  
  390.     }  
  391.   
  392.     /** 
  393.      * 根据路径名生成多级路径 
  394.      *  
  395.      * @param url 
  396.      *            参数要以"\classes\cn\qtone\"或者"/classes/cn/qtone/" 
  397.      */  
  398.     private static String makeDir(String root, String url) {  
  399.         String[] sub;  
  400.         url = url.replaceAll("\\/""\\\\");  
  401.         if (url.indexOf("\\") > -1) {  
  402.             sub = url.split("\\\\");  
  403.         } else {  
  404.             return "-1";  
  405.         }  
  406.   
  407.         File dir = null;  
  408.         try {  
  409.             dir = new File(root);  
  410.             for (int i = 0; i < sub.length; i++) {  
  411.                 if (!dir.exists() && !sub[i].equals("")) {  
  412.                     dir.mkdir();  
  413.                 }  
  414.                 File dir2 = new File(dir + File.separator + sub[i]);  
  415.                 if (!dir2.exists()) {  
  416.                     dir2.mkdir();  
  417.                 }  
  418.                 dir = dir2;  
  419.             }  
  420.         } catch (Exception e) {  
  421.             e.printStackTrace();  
  422.             return "-1";  
  423.         }  
  424.         return dir.toString();  
  425.     }  
  426.   
  427.     /** 
  428.      * 将word文档转化,返回转化后的文件路径 
  429.      *  
  430.      * @param projectPath 
  431.      *            项目路径 
  432.      * @param relativeFilePath 
  433.      *            文件相对路径 
  434.      * @return 返回生成的htm路径(如果出错,则返回null) 
  435.      */  
  436.     public static String wordToHtml(String projectPath, String relativeFilePath) {  
  437.         String resultPath = null;  
  438.         projectRealPath = projectPath;// 项目路径  
  439.         String filePath = "";  
  440.         // System.out.println(projectRealPath + tempPath);  
  441.         // System.out.println(makeDir(projectRealPath, tempPath));  
  442.         try {  
  443.             File file = new File(projectPath + relativeFilePath);  
  444.             if (file.exists()) {  
  445.                 if (file.getName().indexOf(".doc") == -1 || file.getName().indexOf(".docx") > 0) {  
  446.                     throw new FileFormatException("请确认文件格式为doc!");  
  447.                 } else {  
  448.                     wordName = file.getName();  
  449.                     wordName = wordName.substring(0, wordName.indexOf("."));  
  450.   
  451.                     filePath = projectRealPath + tempPath + wordName + ".htm";  
  452.                     synchronized (relativeFilePath) {// 处理线程同步问题  
  453.                         File ff = new File(filePath);  
  454.                         if (!ff.exists()) {// 如果不存在则进行转换  
  455.                             getWordAndStyle(projectPath + relativeFilePath);  
  456.                             writeFile(htmlText, filePath);  
  457.                         }  
  458.                     }  
  459.                     resultPath = tempPath + wordName + ".htm";  
  460.                 }  
  461.             } else {  
  462.                 throw new FileNotFoundException("没找到相关文件!");  
  463.             }  
  464.         } catch (NullPointerException e) {  
  465.             e.printStackTrace();  
  466.         } catch (FileNotFoundException e) {  
  467.             e.printStackTrace();  
  468.         } catch (Exception e) {  
  469.             e.printStackTrace();  
  470.         }  
  471.         return resultPath;  
  472.     }  
  473. }  

[java] view plain copy
  1. package com;  
  2.   
  3. import java.io.ByteArrayInputStream;  
  4. import java.io.ByteArrayOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.FileOutputStream;  
  8. import java.io.InputStream;  
  9. import java.io.OutputStream;  
  10. import java.util.Scanner;  
  11. import java.util.zip.GZIPOutputStream;  
  12.   
  13. import javax.xml.parsers.DocumentBuilder;  
  14. import javax.xml.parsers.DocumentBuilderFactory;  
  15. import javax.xml.transform.OutputKeys;  
  16. import javax.xml.transform.Transformer;  
  17. import javax.xml.transform.TransformerFactory;  
  18. import javax.xml.transform.dom.DOMSource;  
  19. import javax.xml.transform.stream.StreamResult;  
  20.   
  21. import net.arnx.wmf2svg.gdi.svg.SvgGdi;  
  22. import net.arnx.wmf2svg.gdi.wmf.WmfParser;  
  23.   
  24. import org.apache.batik.transcoder.TranscoderInput;  
  25. import org.apache.batik.transcoder.TranscoderOutput;  
  26. import org.apache.batik.transcoder.TranscodingHints;  
  27. import org.apache.batik.transcoder.image.PNGTranscoder;  
  28. import org.apache.batik.transcoder.wmf.tosvg.WMFTranscoder;  
  29. import org.apache.commons.lang.StringUtils;  
  30. import org.w3c.dom.Document;  
  31. import org.w3c.dom.Element;  
  32.   
  33. public class Wmf2Png {  
  34.     public static void main(String[] args) throws Exception {  
  35.         // convert("F:\\SVN\\BobUtil\\web\\25177.wmf");  
  36.         // System.out.println((20 / (21 * 1.0)));  
  37.         // svgToPng("F:\\SVN\\BobUtil\\web\\25177.svg", "F:\\SVN\\BobUtil\\web\\25177.png");  
  38.     }  
  39.   
  40.     /** 
  41.      * @Description: 进行转换 
  42.      * @param filePath 
  43.      *            文件路径 
  44.      * @return 设定文件 
  45.      */  
  46.     public static String convert(String filePath) {  
  47.         String pngFile = "";  
  48.         File wmfFile = new File(filePath);  
  49.         try {  
  50.             if (!wmfFile.getName().contains(".wmf")) {  
  51.                 throw new Exception("请确认输入的文件类型是wmf");  
  52.             }  
  53.             // wmf -> svg  
  54.             String svgFile = filePath.replace("wmf""svg");  
  55.             wmfToSvg(filePath, svgFile);  
  56.             // 对svg做预出理  
  57.             PreprocessSvgFile(svgFile);  
  58.             // svg -> png  
  59.             pngFile = filePath.replace("wmf""png");  
  60.             svgToPng(svgFile, pngFile);  
  61.             // 删除 svg  
  62.             File file = new File(svgFile);  
  63.             if (file.exists()) {  
  64.                 file.delete();  
  65.             }  
  66.             // 删除 wmf  
  67.             if (wmfFile.exists()) {  
  68.                 wmfFile.delete();  
  69.             }  
  70.   
  71.         } catch (Exception e) {  
  72.             try {  
  73.                 e.printStackTrace();  
  74.                 wmfToJpg(filePath);  
  75.             } catch (Exception e1) {  
  76.                 e1.printStackTrace();  
  77.             }  
  78.         }  
  79.         return wmfFile.getName().replace("wmf""png");  
  80.     }  
  81.   
  82.     /** 
  83.      * 将wmf转换为svg 
  84.      *  
  85.      * @param src 
  86.      * @param dest 
  87.      */  
  88.     public static void wmfToSvg(String src, String dest) throws Exception {  
  89.         boolean compatible = false;  
  90.         try {  
  91.             InputStream in = new FileInputStream(src);  
  92.             WmfParser parser = new WmfParser();  
  93.             final SvgGdi gdi = new SvgGdi(compatible);  
  94.             parser.parse(in, gdi);  
  95.   
  96.             Document doc = gdi.getDocument();  
  97.             OutputStream out = new FileOutputStream(dest);  
  98.             if (dest.endsWith(".svgz")) {  
  99.                 out = new GZIPOutputStream(out);  
  100.             }  
  101.   
  102.             output(doc, out);  
  103.         } catch (Exception e) {  
  104.             throw e;  
  105.         }  
  106.     }  
  107.   
  108.     /** 
  109.      * @Description: 输出svg文件 
  110.      * @param doc 
  111.      * @param out 
  112.      * @throws Exception 
  113.      *             设定文件 
  114.      */  
  115.     private static void output(Document doc, OutputStream out) throws Exception {  
  116.         TransformerFactory factory = TransformerFactory.newInstance();  
  117.         Transformer transformer = factory.newTransformer();  
  118.         transformer.setOutputProperty(OutputKeys.METHOD, "xml");  
  119.         transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");  
  120.         transformer.setOutputProperty(OutputKeys.INDENT, "yes");  
  121.         transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//W3C//DTD SVG 1.0//EN");  
  122.         transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,  
  123.                 "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd");  
  124.         transformer.transform(new DOMSource(doc), new StreamResult(out));  
  125.         out.flush();  
  126.         out.close();  
  127.         out = null;  
  128.     }  
  129.   
  130.     /** 
  131.      * @Description:对svg文件做预处理(这里主要是调整大小,先缩小10倍,如果还大于默认值,则按比例缩小) 
  132.      * @param svgFile 
  133.      * @throws Exception 
  134.      *             设定文件 
  135.      */  
  136.     private static void PreprocessSvgFile(String svgFile) throws Exception {  
  137.         int defaultWeight = 500;// 默认宽度  
  138.         FileInputStream inputs = new FileInputStream(svgFile);  
  139.         Scanner sc = new Scanner(inputs, "UTF-8");  
  140.         ByteArrayOutputStream os = new ByteArrayOutputStream();  
  141.         while (sc.hasNextLine()) {  
  142.             String ln = sc.nextLine();  
  143.             if (!ln.startsWith("<!DOCTYPE")) {  
  144.                 os.write((ln + "\r\n").getBytes());  
  145.             }  
  146.         }  
  147.         os.flush();  
  148.           
  149.         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
  150.         DocumentBuilder builder;  
  151.         builder = factory.newDocumentBuilder();  
  152.         Document doc = null;  
  153.         try {  
  154.             doc = builder.parse(new ByteArrayInputStream(os.toByteArray()));  
  155.         } catch (Exception e) {  
  156.             inputs = new FileInputStream(svgFile);  
  157.             os = new ByteArrayOutputStream();  
  158.             int noOfByteRead = 0;  
  159.             while ((noOfByteRead = inputs.read()) != -1) {  
  160.                 os.write(noOfByteRead);  
  161.             }  
  162.             os.flush();  
  163.             doc = builder.parse(new ByteArrayInputStream(os.toByteArray()));  
  164.         } finally {  
  165.             os.close();  
  166.             inputs.close();  
  167.         }  
  168.           
  169.         int height = Integer.parseInt(((Element) doc.getElementsByTagName("svg").item(0)).getAttribute("height"));  
  170.         int width = Integer.parseInt(((Element) doc.getElementsByTagName("svg").item(0)).getAttribute("width"));  
  171.         int newHeight = 0;// 新高  
  172.         int newWidth = 0;// 新宽  
  173.         newHeight = height / 10;// 高缩小10倍  
  174.         newWidth = width / 10// 宽缩小10倍  
  175.         // 如果缩小10倍后宽度还比defaultHeight大,则进行调整  
  176.         if (newWidth > defaultWeight) {  
  177.             newWidth = defaultWeight;  
  178.             newHeight = defaultWeight * height / width;  
  179.         }  
  180.   
  181.         ((Element) doc.getElementsByTagName("svg").item(0)).setAttribute("width", String.valueOf(newWidth));  
  182.         ((Element) doc.getElementsByTagName("svg").item(0)).setAttribute("height", String.valueOf(newHeight));  
  183.         OutputStream out = new FileOutputStream(svgFile);  
  184.         output(doc, out);  
  185.     }  
  186.   
  187.     /** 
  188.      * 将svg图片转成png图片 
  189.      *  
  190.      * @param filePath 
  191.      * @throws Exception 
  192.      */  
  193.     public static void svgToPng(String svgPath, String pngFile) throws Exception {  
  194.         File svg = new File(svgPath);  
  195.         FileInputStream wmfStream = new FileInputStream(svg);  
  196.         ByteArrayOutputStream imageOut = new ByteArrayOutputStream();  
  197.         int noOfByteRead = 0;  
  198.         while ((noOfByteRead = wmfStream.read()) != -1) {  
  199.             imageOut.write(noOfByteRead);  
  200.         }  
  201.         imageOut.flush();  
  202.         imageOut.close();  
  203.         wmfStream.close();  
  204.   
  205.         ByteArrayOutputStream jpg = new ByteArrayOutputStream();  
  206.         FileOutputStream jpgOut = new FileOutputStream(pngFile);  
  207.   
  208.         byte[] bytes = imageOut.toByteArray();  
  209.         PNGTranscoder t = new PNGTranscoder();  
  210.         TranscoderInput in = new TranscoderInput(new ByteArrayInputStream(bytes));  
  211.         TranscoderOutput out = new TranscoderOutput(jpg);  
  212.         t.transcode(in, out);  
  213.         jpgOut.write(jpg.toByteArray());  
  214.         jpgOut.flush();  
  215.         jpgOut.close();  
  216.         imageOut = null;  
  217.         jpgOut = null;  
  218.     }  
  219.   
  220.     /** 
  221.      * 将wmf图片转成png图片(备用方法,即当上面的转换失败时用这个) 
  222.      *  
  223.      * @param filePath 
  224.      * @throws Exception 
  225.      */  
  226.     public static String wmfToJpg(String wmfPath) throws Exception {  
  227.         //先wmf-->svg  
  228.         File wmf = new File(wmfPath);  
  229.         FileInputStream wmfStream = new FileInputStream(wmf);  
  230.         ByteArrayOutputStream imageOut = new ByteArrayOutputStream();  
  231.         int noOfByteRead = 0;  
  232.         while ((noOfByteRead = wmfStream.read()) != -1) {  
  233.             imageOut.write(noOfByteRead);  
  234.         }  
  235.         imageOut.flush();  
  236.         imageOut.close();  
  237.         wmfStream.close();  
  238.   
  239.         // WMFHeaderProperties prop = new WMFHeaderProperties(wmf);  
  240.         WMFTranscoder transcoder = new WMFTranscoder();  
  241.         TranscodingHints hints = new TranscodingHints();  
  242.         transcoder.setTranscodingHints(hints);  
  243.         TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(imageOut.toByteArray()));  
  244.         ByteArrayOutputStream svg = new ByteArrayOutputStream();  
  245.         TranscoderOutput output = new TranscoderOutput(svg);  
  246.         transcoder.transcode(input, output);  
  247.           
  248.         //再svg-->png  
  249.         ByteArrayOutputStream jpg = new ByteArrayOutputStream();  
  250.         String jpgFile = StringUtils.replace(wmfPath, "wmf""png");  
  251.         FileOutputStream jpgOut = new FileOutputStream(jpgFile);  
  252.   
  253.         byte[] bytes = svg.toByteArray();  
  254.         PNGTranscoder t = new PNGTranscoder();  
  255.         TranscoderInput in = new TranscoderInput(new ByteArrayInputStream(bytes));  
  256.         TranscoderOutput out = new TranscoderOutput(jpg);  
  257.         t.transcode(in, out);  
  258.         jpgOut.write(jpg.toByteArray());  
  259.         jpgOut.flush();  
  260.         jpgOut.close();  
  261.         return jpgFile;  
  262.     }  
  263. }  

重点难点解释探讨:

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,再用batiksvg转换为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文本的<img />标签的width与height问题。

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

[java] view plain copy
  1. // 获取图片样式  
  2.  intpicHeight = pic.getHeight() * pic.getAspectRatioY() / 100;  
[java] view plain copy
  1. intpicWidth = pic.getAspectRatioX() * pic.getWidth() / 100;  

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

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

[java] view plain copy
  1. BufferedImage  image = ImageIO.read(file);  
  2. int pheight = image.getHeight();  
  3. int pwidth = image.getWidth();  

Ø  如果转换生成的png宽度小于500,则认为是一般的公式,则应该与它旁边的字体宽度相近,这里设成字体的1.5倍宽度,高度为:

[java] view plain copy
  1. myHeight= (int) (pheight / (pwidth / (picSize * 1.0)) * 1.5);  

如果图片即非wmf与非png(如jpg)的情况下,上面获取高与宽的方法不起作用,不知道是不是POI的bug。只能按以下方式处理:

[java] view plain copy
  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就显得太弱了。


 

 

附:

1.       wmf文件:

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语法,其中包括诸如透明度功能,几何形状,滤镜效果(阴影,灯光效果等),脚本和动画)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值