FreeMark對導出Word中圖片的處理


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM