700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > java word 添加图片_java – 在word文档中插入图片

java word 添加图片_java – 在word文档中插入图片

时间:2023-08-28 17:52:56

相关推荐

java word 添加图片_java – 在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.x.main.CTNonVisualDrawingProps;

import org.openxmlformats.schemas.drawingml.x.main.CTPositiveSize2D;

import org.openxmlformats.schemas.drawingml.x.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-模式

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。