java 使用poi将word、excel转成html最完美的方法

java | 2019-09-13 10:02:39

java 使用poi将word、excel转成html最完美的方法wordToHtml,包含了生成html,word中的图片,宏定义的公式等转换成图片的所有一整套方法。需要的poi jar包我就不多说了,本站jar包下载区都有的。

此java代码用于把word、excel转成html用于在互联网上显示的最完美兼容方法:


//测试方法
public static void main(String argv[]) {  
       InputStream in = new FileInputStream("d:/abc.doc"); 
            System.out.println(convert2Html(in,"d:/img/abc/","/img/abc/"));
}



//word转html
public static String convert2Html(InputStream is,String realPath,final String imgPath){  
            String returnStr="";
        try {
                        HWPFDocument wordDocument = new HWPFDocument(is);//WordToHtmlUtils.loadDoc(new FileInputStream(inputFile));  
                        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 )  
                             {  
                                     
                                     if(suggestedName.contains("wmf")){
                                             return imgPath+suggestedName+".png";
                                     }else{
                                             return imgPath+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 {
                                        File file = new File(realPath);
                                        if(!file.exists())file.mkdir();
                                        FileOutputStream onePic=new FileOutputStream(realPath+ pic.suggestFullFileName());
                                    pic.writeImageContent(onePic);
                                    onePic.flush();
                                    onePic.close();
                                    if(pic.suggestFullFileName().contains("wmf")){
                                    wmfToSvg(realPath+ pic.suggestFullFileName(), realPath+ pic.suggestFullFileName()+".svg");
                                    svgToPng(realPath+ pic.suggestFullFileName());
                                    }
                                } catch (FileNotFoundException e) {  
                                    e.printStackTrace();  
                                }    
                            }  
                        }  
                        Document htmlDocument = wordToHtmlConverter.getDocument(); 
                        
                        ByteArrayOutputStream out = new ByteArrayOutputStream();  
                        DOMSource domSource = new DOMSource(htmlDocument);  
                        StreamResult streamResult = new StreamResult(out);  
  
                        TransformerFactory tf = TransformerFactory.newInstance();  
                        Transformer serializer = tf.newTransformer();  
                        serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");  
                        serializer.setOutputProperty(OutputKeys.INDENT, "no");  
                        serializer.setOutputProperty(OutputKeys.METHOD, "html");
                        serializer.setOutputProperty(OutputKeys.METHOD, "html");
                        
                        serializer.transform(domSource, streamResult);  
                        out.close();  
                        returnStr=new String(out.toByteArray(),"utf-8");
                } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                } catch (TransformerConfigurationException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                } catch (IllegalArgumentException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                } catch (ParserConfigurationException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                } catch (TransformerFactoryConfigurationError e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                } catch (TransformerException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }  
        return returnStr;
    }


        


        

//svg图片转png图片
        public static String svgToPng(String fileName){
                try {
//注释掉的这段代码是wmf转svg的另外一种方法
//                           WMFTranscoder wmfTranscoder = new WMFTranscoder();
//                           TranscoderInput wmfInput = new TranscoderInput(new File(fileName).toURI().toString());
//                           FileOutputStream svgFos = new FileOutputStream(fileName+".svg");
//                           TranscoderOutput svgOutput = new TranscoderOutput(new OutputStreamWriter(svgFos,"utf-8"));
//                           wmfTranscoder.addTranscodingHint(WMFTranscoder.KEY_WIDTH, new Float(1000));
//                           wmfTranscoder.transcode(wmfInput, svgOutput);
//                           svgFos.flush();
//                           svgFos.close();
                   
                        String svgStr=replaceTxtByStr(fileName+".svg");
                        byte[] bytes = svgStr.getBytes("utf-8");
                                PNGTranscoder pngTranscoder = new PNGTranscoder();
                                
                                TranscoderInput svgInput = new TranscoderInput(new ByteArrayInputStream(bytes));//new TranscoderInput(new File(fileName+".svg").toURI().toString());
                                FileOutputStream pngFos = new FileOutputStream(fileName+".png");
                                
                                TranscoderOutput pngOutput = new TranscoderOutput(pngFos);
                                pngTranscoder.transcode(svgInput, pngOutput);
                                
                                pngFos.flush();
                                pngFos.close();
                                
                
                } catch (IOException e){
                   try {
                                throw new TranscoderException(e);
                        } catch (TranscoderException e1) {
                                // TODO Auto-generated catch block
                                e1.printStackTrace();
                        }
                } catch (TranscoderException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                return fileName+".png";
    }


    

//获取svg图片的内容并替换一些不兼容的字符
    public static String replaceTxtByStr(String filePath) {
            String resultFileString="";
        try {
                  File myFile=new File(filePath);
              if(!myFile.exists()){ 
                  System.err.println("Can't Find " + filePath);
              }
              StringBuffer  returnString=new StringBuffer();
              InputStream inputStream=new FileInputStream(myFile);
              InputStreamReader isr = new InputStreamReader(inputStream, "utf-8");
              BufferedReader in = new BufferedReader(isr);
              String str=null;
              while ((str = in.readLine()) != null) 
              {
                      returnString.append(str);
              }
              resultFileString=returnString.toString().replaceAll("′", "x").replaceAll("3", ">=").replaceAll("£", "<=");
              in.close();
              isr.close();
              inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultFileString;
    }
        
        
        public static void wmfToSvg(String src, String dest) {  
        boolean compatible = false;  
            try {
                                InputStream in = new FileInputStream(src);  
                                WmfParser parser = new WmfParser();  
                                final SvgGdi gdi = new SvgGdi(compatible);  
                                parser.parse(in, gdi);  
  
                                Document doc = gdi.getDocument();  
                                OutputStream out = new FileOutputStream(dest);  
                                if (dest.endsWith(".svgz")) {  
                                    out = new GZIPOutputStream(out);  
                                } 
                                
                                doc.getFirstChild().getAttributes().removeNamedItem("height");
                                doc.getFirstChild().getAttributes().removeNamedItem("width");
                                
                                output(doc, out);
                                
                                in.close();
                        } catch (FileNotFoundException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        } catch (SvgGdiException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        } catch (DOMException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        } catch (WmfParseException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }  
        
    }


  


    private static void output(Document doc, OutputStream out) throws Exception {  
        TransformerFactory factory = TransformerFactory.newInstance();  
        Transformer transformer = factory.newTransformer();  
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");  
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");  
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");  
        transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//W3C//DTD SVG 1.0//EN");  
        transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,  
                "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd");  
        transformer.transform(new DOMSource(doc), new StreamResult(out));  
        out.flush();  
        out.close();  
        out = null;  
    }


登录后即可回复 登录 | 注册
    
关注编程学问公众号