word转html (包含doc和docx),亲测有用

    
			org.apache.poi
			poi
			3.15
		
		  
            org.apache.poi
            ooxml-schemas
            1.4
        
		
			org.apache.poi
			poi-ooxml
			3.15
		
		
			org.apache.poi
			poi-scratchpad
			3.15
		
		 
            org.apache.poi
            poi-ooxml-schemas
            3.15
        
		
            fr.opensagres.xdocreport
            xdocreport
            2.0.2
        
		
		    fr.opensagres.xdocreport
		    org.apache.poi.xwpf.converter.xhtml
		    1.0.6
		

首先导入上面的jar包   测试4.1.0  docx转html是会报错的 但是doc不会报错,3.17也一样  但是poi3.15不会报错 ,所以就导入3.15版本

 

	public static void docToHtml(final String path,final String file) throws Exception{
		InputStream input = new FileInputStream(path + file);
		HWPFDocument wordDocument = new HWPFDocument(input);
		WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
				DocumentBuilderFactory.newInstance().newDocumentBuilder()
				.newDocument());
		wordToHtmlConverter.setPicturesManager(new PicturesManager() {
			public String savePicture(byte[] content, PictureType pictureType,
					String suggestedName, float widthInches, float heightInches) {
				return suggestedName;
			}
		});
		wordToHtmlConverter.processDocument(wordDocument);
		List pics = wordDocument.getPicturesTable().getAllPictures();
		if (pics != null) {
			for (int i = 0; i < pics.size(); i++) {
				Picture pic = (Picture) pics.get(i);
					pic.writeImageContent(new FileOutputStream(path
							+ pic.suggestFullFileName()));
			}
		}
		Document htmlDocument = wordToHtmlConverter.getDocument();
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		DOMSource domSource = new DOMSource(htmlDocument);
		StreamResult streamResult = new StreamResult(outStream);
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer serializer = tf.newTransformer();
		serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
		serializer.setOutputProperty(OutputKeys.METHOD, "html");
		serializer.transform(domSource, streamResult);
		outStream.close();
		String content = new String(outStream.toByteArray());
		FileUtils.writeStringToFile(new File(path, "11.html"), content, "utf-8");
	}
	
    
	public static void docx2Html(String tempPath,String fileName, String outPutFile) throws Exception {
		XWPFDocument document = new XWPFDocument(new FileInputStream(fileName));
		XHTMLOptions options = XHTMLOptions.create().indent(4);
		// 导出图片
		if(!Strings.isNullOrEmpty(tempPath)){
			File imageFolder = new File(tempPath);
			options.setExtractor(new FileImageExtractor(imageFolder));
			// URI resolver
			options.URIResolver(new FileURIResolver(imageFolder));
		}
		
		File outFile = new File(outPutFile);
		outFile.getParentFile().mkdirs();
		OutputStream out = new FileOutputStream(outFile);
		XHTMLConverter.getInstance().convert(document, out, options);
	}

 

 

 

你可能感兴趣的:(解决方案)