在开发过程中,我们可能会遇到需要生成word,或者通过模板word替换相应内容的需求。但在文档中插入图片时,如果段落格式设置不对,就会导致图片只显示一点点或者不显示。接下来就介绍一下java编辑word和插入图片需怎么处理。

1.引入依赖

首先我们在项目中引入Apache POI,用于读取和操作word,这里我使用的版本是4.1.2,版本可以根据项目需求自己选择。

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>    

2.编辑word

这里是通过模板加入占位符,然后替换占位符的内容

首先我们打开word模板文件

String path = "***.docx";
File file = new File(path);
try {
    XWPFDocument template = new XWPFDocument(new FileInputStream(file));
    // 替换内容
    XWPFDocument outWord = PoiWordUtil.replaceWithPlaceholder(template, list);
    return outWord;
} catch (IOException e) {
    log.error("读取模板文件失败", e);
}

替换相应内容

// 这里我定义了Placeholder来封装替换数据public static XWPFDocument replaceTextAndImage(XWPFDocument document, List<Placeholder> list) {    for (XWPFParagraph xwpfParagraph : document.getParagraphs()) {        String paragraphText = xwpfParagraph.getText(        if (StringUtils.isEmpty(paragraphText)) contin        for (Placeholder placeholder : list) {            String key = placeholder.getKey();
            if (paragraphText.contains(key)) {
for (XWPFRun cellRun : xwpfParagraph.getRuns()) {
String text = cellRun.getText(0);
if (text != null && text.contains(key)) {
//获取占位符类型
String type = placeholder.getType();
//获取对应key的value
String value = placeholder.getValue();
if("0".equals(type)){
//把文本的内容,key替换为value
text = text.replace(key, value);
//把替换好的文本内容,保存到当前这个文本对象
cellRun.setText(text, 0);
}else {
text = text.replace(key, "");
cellRun.setText(text, 0);
if (StringUtils.isEmpty(value))
continue;
                            try {
                   // 获取段落行距模式
int rule = xwpfParagraph.getSpacingLineRule().getValue();
// 如果段落行距为固定值,会导致图片显示不全,所以需要改成其他模式
if (LineSpacingRule.EXACT.getValue() == rule) {
// 设置段落行距为单倍行距
xwpfParagraph.setSpacingBetween(1);
}
                   // 获取文件流
                   InputStream imageStream = ImageUtils.getFile(value);
                                if (imageStream == null) continue;
// 通过BufferedImage获取图片信息
BufferedImage bufferedImage = ImageIO.read(imageStream);
int height = bufferedImage.getHeight();
int width = bufferedImage.getWidth();
// 这里需要重新获取流,之前的流已经被BufferedImage使用掉了
cellRun.addPicture(ImageUtils.getFile(value), XWPFDocument.PICTURE_TYPE_JPEG, "", Units.toEMU(width), Units.toEMU(height));
                            } catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
}
return document;
}

在插入图片时,如果段落的行距设置成了固定值,那么在显示图片时只能显示行距大小的部分,所以当插入图片的段落行距为固定值时,我们需要修改为其他模式,这样图片就能正常大小显示。

然后我们使用cellRun.addPicture()来插入图片,这里我们可以通过BufferedImage来获取图片的尺寸大小。

这样就解决了插入图片显示异常的问题了。