【已解决】使用POI操作word文档的时候,怎么在一页A4纸中竖着插入2张图片
- 工作小总结
- 时间:2023-10-04 11:51
- 2248人已阅读
简介
在工作中,有时候,我们需要使用Java操作POI来生产word文档,可能会遇到这种情况:在一张A4纸中竖着插入2张图片,也就是一张A4纸正好放两张图片,或者是多种图片,那么这个需求怎么实现呢?下面凯哥(个人公众号:凯哥Java)来讲讲怎么实现。我们先来回顾下,使用ApachePOI库来操作Word文档,在向word中插入图片的时候,需要哪些步骤?流程图如下:需要先创建文档对象,然后创建段落对象,再
🔔🔔好消息!好消息!🔔🔔
有需要的朋友👉:微信号
在工作中,有时候,我们需要使用Java操作POI来生产word文档,可能会遇到这种情况:在一张A4纸中竖着插入2张图片,也就是一张A4纸正好放两张图片,或者是多种图片,那么这个需求怎么实现呢?
下面凯哥(个人公众号:凯哥Java)来讲讲怎么实现。
我们先来回顾下,使用Apache POI库来操作Word文档,在向word中插入图片的时候,需要哪些步骤?流程图如下:

需要先创建文档对象,然后创建段落对象,再创建图片对象,将图片插入到段落中,将段落插入到word文档对象中,最后保存word文档既可以了。
那么,下面咱们就来看看代码:
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlCursor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class InsertTwoImagesInOnePage {
public static void main(String[] args) {
try {
// 创建一个新的Word文档
XWPFDocument document = new XWPFDocument();
//1个段落1个图片
double width=470.5;
double height=330.125;
insertImageInParagraph(document, "D:\\files\\test\\zipFile\\zip_picture\\202310041006522\\2d233778e74746538b2ea629435bc145\\cut\\1#施工图片-1.jpg",width,height);
width=470.5;
height=330.125;
insertImageInParagraph(document, "D:\\files\\test\\zipFile\\zip_picture\\202310041006522\\2d233778e74746538b2ea629435bc145\\cut\\1#施工图片-2.png",width,height);
// 保存文档
FileOutputStream out = new FileOutputStream("D:\\files\\test\\zipFile\\zip_picture\\"+"output1.docx");
document.write(out);
out.close();
System.out.println("Word文档已创建并图片已插入成功。");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 一个段落1个图片
* @param document doc文档对象
* @param imagePath 图片路径
* @throws Exception
*/
private static void insertImageInParagraph(XWPFDocument document, String imagePath,double width1, double height1) throws Exception {
XWPFParagraph paragraph = document.createParagraph();
// 插入图片
XWPFRun run = paragraph.createRun();
run.addPicture(new FileInputStream(imagePath), XWPFDocument.PICTURE_TYPE_JPEG, imagePath, Units.toEMU(width1), Units.toEMU(height1));
}
}需要注意:
1.将图片大小需要转换成Units.toEMU(height1)
来查看运行后的结果:
这样就实现了在一张A4纸中竖着插入2张图片了。