當導出的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;}