javadocx转换成html_java doc/docx 转HTML

doc 和 docx 略有不同,对于doc,可以用下面这种方式:

HWPFDocument wordDocument = new HWPFDocument(is);

WordToHtmlConverter converter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());

//对HWPFDocument进行转换

converter.setPicturesManager(new PicturesManager() {

@Override

public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {

String type = pictureType.name();

return "data:image/" + type + ";base64," + new String(Base64.encodeBase64(content));

}

});

converter.processDocument(wordDocument);

Transformer transformer = TransformerFactory.newInstance().newTransformer();

transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");

//是否添加空格

transformer.setOutputProperty(OutputKeys.INDENT, "yes");

transformer.setOutputProperty(OutputKeys.METHOD, "html");

transformer.transform(

new DOMSource(converter.getDocument()),

new StreamResult(response.getWriter()));

response.getWriter().flush();

wordDocument.close();

需要导入以下的类:

import org.apache.poi.hwpf.HWPFDocument;

import org.apache.poi.hwpf.converter.PicturesManager;

import org.apache.poi.hwpf.converter.WordToHtmlConverter;

import org.apache.poi.hwpf.usermodel.PictureType;

由于我做的是doc转HTML在线预览,所以为了方便图片都转成了base64编码。

下面是docx的情况:

XWPFDocument document = new XWPFDocument(is);

List list = document.getAllPictures();

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

XHTMLConverter.getInstance().convert(document, outputStream, null);

String s = new String(outputStream.toByteArray());

s = setImg(s, list);

response.getWriter().write(s);

response.getWriter().flush();

document.close();

这个需要另外的setImg方法来修改生成的HTML,使用jsoup解析:

private String setImg(String html, List list){

Document doc = Jsoup.parse(html);

Elements elements = doc.getElementsByTag("img");

if (elements != null && elements.size() > 0 && list != null){

for(Element element : elements){

String src = element.attr("src");

for (XWPFPictureData data: list){

if (src.contains(data.getFileName())){

String type = src.substring(src.lastIndexOf(".") + 1);

String base64 = "data:image/" + type + ";base64," + new String(Base64.encodeBase64(data.getData()));

element.attr("src", base64);

break;

}

}

}

}

return doc.toString();

}

需要导入:

import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;

import org.apache.poi.xwpf.usermodel.XWPFDocument;

import org.apache.poi.xwpf.usermodel.XWPFPictureData;

import org.jsoup.Jsoup;

import org.jsoup.nodes.Document;

import org.jsoup.nodes.Element;

import org.jsoup.select.Elements;

以上

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值