码迷,mamicode.com
首页 > 其他好文 > 详细

FreeMark对导出Word中图片的处理

时间:2016-03-11 11:39:19      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:

当导出的Word中带有图片时,我们可以创建一个带有图片的word模板,并将其保存成xml文档。此时我们能看到这样一段代码:
<w:binData w:name="wordml://03000001.png" xml:space="preserve">iVBORw0KGgo...此处省略base64编码...AASUVORK5CYIJ=</w:binData>  <#--用于声明图片的base64编码,并对其命名 -->
<v:shape id="图片 0" o:spid="_x0000_i1028" type="#_x0000_t75" alt="logo.png" style="width:128.25pt;height:33.75pt;rotation:180;visibility:visible;mso-wrap-style:square">
<v:imagedata src=
"wordml://03000001.png" o:title="logo"/> <#--根据图片的命名显示图片 -->
</v:shape>
此时我们将需要动态展示的数据换成变量占位符,如下:
<w:binData w:name="${"wordml://logo_"+nameplate_index+".png"}" xml:space="preserve">${logoUrl!}</w:binData>          
<v:shape id="图片 0" o:spid="_x0000_i1028" type="#_x0000_t75" alt="logo.png" style="width:128.25pt;height:33.75pt;rotation:180;visibility:visible;mso-wrap-style:square">
<v:imagedata src="${"wordml://logo_"+nameplate_index+".png"}" o:title="logo"/>
</v:shape>

注意:此处的${logoUrl!}存放的是图片的base64编码。且<w:binData>与</binData>标签之间除了该变量外不可添加其他字符,即使是一个空格或者换位符等。另外如果word中存在多张不同的图片,那么图片之间的<w:binData>标签中的v:name必须和<v:imagedata>中的src的值要不一致。单个图片内部两个属性值要保持一致。


后台获取图片的base64编码方法:

public String getImageStr(String imgFile) {

InputStream in = null;
byte[] data = null;
try {
if(imgFile.startsWith("http")){ //获取在线图片
URL url = new URL(imgFile);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
in = conn.getInputStream();
}else{ //获取线下图片
in = new FileInputStream(imgFile);
}
/*
     //使用此种方式在获取在线图片时下载word中图片可能显示不全,其原因就是网络通讯往往是间断性的,一串字节往往分几批进行发送。本地程序调用available()方法有时得到0,这可能是对方还没有响应,也可能是对方已经响 应了,但是数据还没有送达本地。对方发送了1000个字节给你,也许分成3批到达,这你就要调用3次available()方法才能将数据总数全部得到。
     int count = 0;
while (count == 0) {
count = in.available();
}
data = new byte[count];*/
int c;
ByteArrayOutputStream buff = new ByteArrayOutputStream();
while((c = in.read()) >= 0){
buff.write(c);
}
data = buff.toByteArray();
buff.close();
in.read(data);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
if(data!=null && data.length>0){
return encoder.encode(data);
}
return null;
}
 
 

FreeMark对导出Word中图片的处理

标签:

原文地址:http://www.cnblogs.com/Sara-shi/p/5264703.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!