解決 Java poi 3.8等版本操作word插入圖片不成功的問題
問題:
最近有一個需求是將Excel中的數據轉換到word中,其中包括了文字和圖片,
在使用 poi 3.8 向word中寫入圖片的時候發現怎麼都不成功,具體過程如下:
使用 poi 寫入圖片到word,我用戶鼠標點擊文檔中插入圖片的表格發現裏面是有內容的,是一個圖片的框,但是框裏面看不見任何東西,將這個圖片框 右鍵 —— 另存爲,發現裏面不是沒有圖片,而是插入了一張透明的png 圖片,所以看不見。
我經過了各種艱苦的思想鬥爭、各種猜測、各種測試,最後一一落敗 。。。 。。。
解決思路:
後來在網上看到有人說 poi 本身就存在BUG,我當時是不信的,網址是 https://www.xuebuyuan.com/577192.html
但是沒辦法了,既然他說解決了那就試試看吧,
來一波複製粘貼,DeBug 運行 還真就把圖片完美的加進去了,好吧,那你說的對,咱也不知道,咱也不敢問。
據這篇博客介紹,問題在於 在\word\document.xml文件中關於圖片的一大串XML內容沒有被正確地生成,而圖片本身被添加到正確的位置\word\media\xxxx.xxx,而且引用關係也正確添加。
word2007以後文件的默認存儲格式不再是二進制文件格式,而是Microsoft Office Word XML格式(Word XML格式)。這種格式基於開放打包約定(Open Packaging Conventions),Microsoft Office 97到Microsoft Office 2003中使用的二進制文件格式仍然可以作爲一種保存格式來使用,但是它不是保存新文檔時的默認文檔。
那麼,上面的問題應該就是在插入圖片時部分XML沒有正確生成(\word\document.xml中)。
而且這位高手在第15樓也給出了變通方案:就是自定義一個XWPFDocument來完成缺陷XML內容的添加。
https://issues.apache.org/bugzilla/show_bug.cgi?id=49765#c15
這位前輩解決了在 XWPFDocument 層面直接添加圖片的問題,但是並不是我需要的,我需要在表格中添加圖片。
那就按照這個思路看看怎麼解決我的問題。
效果:
準備一個文檔 一張圖片
最後出來的結果:
代碼:
奉勸各位不要在使用 poi 3.8 這些低版本 ,抓緊換高版本,因爲我還發現了一些BUG,傷不起啊。。。。
package com.soft.word;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlToken;
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;
public class MyRun {
public static final String filePath = "F:\\demo.docx";
public static final String imgPath = "F:\\demo.jpg";
public static void main(String[] args) throws Exception {
InputStream inStream = new FileInputStream(new File(filePath));
XWPFDocument doc = new XWPFDocument(inStream);
List<XWPFTable> xwpfTables = doc.getTables();
XWPFTable xwpfTable = xwpfTables.get(0);
List<XWPFTableRow> rows = xwpfTable.getRows();
XWPFTableRow xwpfTableRow = rows.get(0);
List<XWPFTableCell> tableCells = xwpfTableRow.getTableCells();
XWPFTableCell xwpfTableCell = tableCells.get(0);
List<XWPFParagraph> paragraphs = xwpfTableCell.getParagraphs();
XWPFParagraph xwpfParagraph = paragraphs.get(0);
String picId = doc.addPictureData(new FileInputStream(new File(imgPath)), XWPFDocument.PICTURE_TYPE_JPEG);
addPictureToRun(xwpfParagraph.createRun(), picId, XWPFDocument.PICTURE_TYPE_JPEG, 100, 100);
OutputStream outputStream = new FileOutputStream(filePath);
doc.write(outputStream);
outputStream.flush();
outputStream.close();
inStream.close();
}
/**因POI 3.8自帶的BUG 導致添加進的圖片不顯示,只有一個圖片框,將圖片另存爲發現裏面的圖片是一個PNG格式的透明圖片
* 這裏自定義添加圖片的方法
* 往Run中插入圖片(解決在word中不顯示的問題)
* @param run
* @param blipId 圖片的id
* @param id 圖片的類型
* @param width 圖片的寬
* @param height 圖片的高
* @author lgj
*/
public static void addPictureToRun(XWPFRun run,String blipId,int id,int width, int height){
final int EMU = 9525;
width *= EMU;
height *= EMU;
CTInline inline =run.getCTR().addNewDrawing().addNewInline();
String picXml = "" +
"<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">" +
" <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
" <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
" <pic:nvPicPr>" +
" <pic:cNvPr id=\"" + id + "\" name=\"Generated\"/>" +
" <pic:cNvPicPr/>" +
" </pic:nvPicPr>" +
" <pic:blipFill>" +
" <a:blip r:embed=\"" + blipId + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>" +
" <a:stretch>" +
" <a:fillRect/>" +
" </a:stretch>" +
" </pic:blipFill>" +
" <pic:spPr>" +
" <a:xfrm>" +
" <a:off x=\"0\" y=\"0\"/>" +
" <a:ext cx=\"" + width + "\" cy=\"" + height + "\"/>" +
" </a:xfrm>" +
" <a:prstGeom prst=\"rect\">" +
" <a:avLst/>" +
" </a:prstGeom>" +
" </pic:spPr>" +
" </pic:pic>" +
" </a:graphicData>" +
"</a:graphic>";
//CTGraphicalObjectData graphicData = inline.addNewGraphic().addNewGraphicData();
XmlToken xmlToken = null;
try {
xmlToken = XmlToken.Factory.parse(picXml);
} catch(XmlException xe) {
xe.printStackTrace();
}
inline.set(xmlToken);
//graphicData.set(xmlToken);
inline.setDistT(0);
inline.setDistB(0);
inline.setDistL(0);
inline.setDistR(0);
CTPositiveSize2D extent = inline.addNewExtent();
extent.setCx(width);
extent.setCy(height);
CTNonVisualDrawingProps docPr = inline.addNewDocPr();
docPr.setId(id);
docPr.setName("Picture " + id);
docPr.setDescr("Generated");
}
}
另外粘一下直接用 document對象添加圖片的
package com.soft.word;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlToken;
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;
/**
* 以爲POI 3.8 自帶的BUG,導致添加圖片無法正確顯示,這裏重寫POI添加圖片的方法
* @author 十年飲冰,難涼熱血 !!!
*
*/
public class CustomXWPFDocument extends XWPFDocument {
public static final String filePath = "F:\\demo.docx";
public static final String imgPath = "F:\\demo.jpg";
public static void main(String[] args) {
CustomXWPFDocument document = new CustomXWPFDocument();
try {
String picId = document.addPictureData(new FileInputStream(imgPath), XWPFDocument.PICTURE_TYPE_PNG);
document.createPicture(picId, document.getNextPicNameNumber(XWPFDocument.PICTURE_TYPE_PNG), 200, 150);
FileOutputStream fos = new FileOutputStream(new File(filePath));
document.write(fos);
fos.close();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public CustomXWPFDocument() {
super();
}
public CustomXWPFDocument(OPCPackage opcPackage) throws IOException {
super(opcPackage);
}
public CustomXWPFDocument(InputStream in) throws IOException {
super(in);
}
public void createPicture(String blipId,int id, int width, int height) {
final int EMU = 9525;
width *= EMU;
height *= EMU;
//String blipId = getAllPictures().get(id).getPackageRelationship().getId();
CTInline inline = createParagraph().createRun().getCTR().addNewDrawing().addNewInline();
String picXml = "" +
"<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">" +
" <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
" <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
" <pic:nvPicPr>" +
" <pic:cNvPr id=\"" + id + "\" name=\"Generated\"/>" +
" <pic:cNvPicPr/>" +
" </pic:nvPicPr>" +
" <pic:blipFill>" +
" <a:blip r:embed=\"" + blipId + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>" +
" <a:stretch>" +
" <a:fillRect/>" +
" </a:stretch>" +
" </pic:blipFill>" +
" <pic:spPr>" +
" <a:xfrm>" +
" <a:off x=\"0\" y=\"0\"/>" +
" <a:ext cx=\"" + width + "\" cy=\"" + height + "\"/>" +
" </a:xfrm>" +
" <a:prstGeom prst=\"rect\">" +
" <a:avLst/>" +
" </a:prstGeom>" +
" </pic:spPr>" +
" </pic:pic>" +
" </a:graphicData>" +
"</a:graphic>";
//CTGraphicalObjectData graphicData = inline.addNewGraphic().addNewGraphicData();
XmlToken xmlToken = null;
try {
xmlToken = XmlToken.Factory.parse(picXml);
} catch(XmlException xe) {
xe.printStackTrace();
}
inline.set(xmlToken);
//graphicData.set(xmlToken);
inline.setDistT(0);
inline.setDistB(0);
inline.setDistL(0);
inline.setDistR(0);
CTPositiveSize2D extent = inline.addNewExtent();
extent.setCx(width);
extent.setCy(height);
CTNonVisualDrawingProps docPr = inline.addNewDocPr();
docPr.setId(id);
docPr.setName("Picture " + id);
docPr.setDescr("Generated");
}
}