解决 Java poi 3.8 等版本 操作 word 插入 图片 不成功的问题

            解决 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");
	    }
	 
}
发布了34 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_36623327/article/details/90762982