java word中插入图片_在Word文档中插入图片

小编典典

首先,我想指出apache poi-

Link提供的示例,即正确的方法是

doc.createParagraph().createRun().addPicture(new FileInputStream(imgFile), format, imgFile, Units.toEMU(200), Units.toEMU(200));

但是,仍然存在一个现有错误,在执行上述语句后,该.docx文件将变得不可读。可能很快会解决,在这种情况下,上述声明将起作用。同时,有一种解决方法。

首先,生成没有任何图片的docx文件。然后将此类添加CustomXWPFDocument到您的包中。

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;

import java.io.IOException;

import java.io.InputStream;

public class CustomXWPFDocument extends XWPFDocument

{

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 = "" +

"" +

" " +

" " +

" " +

" " +

" " +

" " +

" " +

" " +

" " +

" " +

" " +

" " +

" " +

" " +

" " +

" " +

" " +

" " +

" " +

" " +

" " +

" " +

" " +

"";

//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");

}

}

然后,通过添加图片来创建更新的文档,如下所示:-

CustomXWPFDocument document = new CustomXWPFDocument(new FileInputStream(new File("C:\\Users\\Avarice\\Desktop\\doc1.docx")));

FileOutputStream fos = new FileOutputStream(new File("C:\\Users\\Avarice\\Desktop\\doc2.docx"));

String id = document.addPictureData(new FileInputStream(new File("C:\\Users\\Avarice\\Desktop\\thumbnail.jpg")), Document.PICTURE_TYPE_JPEG);

document.createPicture(id,document.getNextPicNameNumber(Document.PICTURE_TYPE_JPEG), 64, 64);

document.write(fos);

fos.flush();

fos.close();

您还应该在构建路径中包含以下jar:

poi-ooxml-schemas

2020-09-16

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值