如何使用apache poi并排添加word文档图像

时间:2019-11-12 13:44:56

标签: java apache-poi

我想使用apache poi在我的Word文档中并排添加图像。我试图使其成为表方法,并为此编写了代码。

XWPFTable imgTable;
            XWPFTableRow rows=null;
            XWPFTableCell cells=null;
            imgTable=document.createTable(20,2);
            imgTable.getCTTbl().getTblPr().unsetTblBorders();
            rows=imgTable.getRow(1);
            cells=rows.getCell(0);
            XWPFParagraph imgPara = document.createParagraph();
            XWPFRun img = imgPara.createRun();
            for(int z=0;z<imgPaths.size();z++)
            {

                if(imgPaths.get(z).contains("-"))
                {

                }
                else
                {
                    System.out.println(imgPaths.get(z));
                    try {
                        is2 = new FileInputStream(imgPaths.get(z));
                        is3=new FileInputStream(imgPaths.get(z+1));
                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    try {
                        img.addPicture(is2, XWPFDocument.PICTURE_TYPE_JPEG, "", Units.toEMU(450), Units.toEMU(200));
                    } catch (InvalidFormatException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

我的imgPaths数组列表中正在加载数据的文件路径来自Access数据库。在我的数据库中,有一些文件路径。如果没有文件路径,则将-放入我的数据库单元中。例如,我有20个单元格用于图像路径,但是我添加了7个文件路径,所以我将其余的13个放置在此-中。因此,当我运行代码时,没有错误,但是图像未显示Word文档。我究竟做错了什么?

1 个答案:

答案 0 :(得分:1)

您的XWPFParagraph imgParaXWPFRun img不在表格内。他们在桌子外面。

您的代码还将所有图片添加到同一XWPFRun中。但是它应该将图片添加到XWPFTableCell的不同运行中。为此,您需要获取XWPFTableCell的第一段,然后在该段中运行第一段文本。

以下完整代码显示了如何完成此操作。它使用来自公共可访问互联网资源的图片。因此,无需在本地存储图片文件就可以使用它。

import java.io.*;

import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.util.Units;

import java.util.List;
import java.util.ArrayList;

import java.net.URL;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.Dimension;

public class CreateWordPicturesInTable {

 public static void main(String[] args) throws Exception {

  List<String> pictureURLs = new ArrayList<String>();
  pictureURLs.add("https://www.eastcottvets.co.uk/uploads/Animals/gingerkitten.jpg");
  pictureURLs.add("https://www.catster.com/wp-content/uploads/2017/12/A-kitten-meowing.jpg");
  pictureURLs.add("-");
  pictureURLs.add("https://www.animalfriends.co.uk/app/uploads/2014/08/06110347/Kitten-small.jpg");
  pictureURLs.add("https://d27ucmmhxk51xv.cloudfront.net/media/english/illustration/kitten.jpg");
  pictureURLs.add("-");
  pictureURLs.add("-");

  int picturesCount = pictureURLs.size();
  int tableRows = (int)Math.round(picturesCount/2d);

  XWPFDocument document= new XWPFDocument();
  XWPFParagraph paragraph = document.createParagraph();
  XWPFRun run = paragraph.createRun();
  run.setText("The kitten pictures: ");

  XWPFTable imgTable = document.createTable(tableRows,2);
  XWPFTableCell cell;

  URL url;
  BufferedImage image;
  Dimension dim;
  ByteArrayOutputStream bout;
  ByteArrayInputStream bin;
  int tableRow = 0;
  int tableCell = 0;
  for (String pictureURL : pictureURLs) {
   cell = imgTable.getRow(tableRow).getCell(tableCell++);
   if (tableCell == 2) {
    tableCell = 0;
    tableRow++;
   }

   if (!"-".equals(pictureURL)) {
    url = new URL(pictureURL);
    image = ImageIO.read(url);
    dim = new Dimension(image.getWidth(), image.getHeight());
    double width = dim.getWidth();
    double height = dim.getHeight();
    double scaling = 1.0;
    if (width > 72*3) scaling = (72*3)/width; //scale width not to be greater than 3 inches
    bout = new ByteArrayOutputStream();
    ImageIO.write(image, "jpeg", bout);
    bout.flush();
    bin = new ByteArrayInputStream(bout.toByteArray());

    if (cell.getParagraphs().size() > 0) paragraph = cell.getParagraphs().get(0); else paragraph = cell.addParagraph();
    if (paragraph.getRuns().size() > 0) run = paragraph.getRuns().get(0); else run = paragraph.createRun();
    run.addPicture(bin, XWPFDocument.PICTURE_TYPE_JPEG, "kitten", 
     Units.toEMU(width*scaling), Units.toEMU(height*scaling));

    //lock aspect ratio
    run.getCTR().getDrawingArray(0).getInlineArray(0).addNewCNvGraphicFramePr().addNewGraphicFrameLocks().setNoChangeAspect(true);
   }
  }

  FileOutputStream out = new FileOutputStream("CreateWordPicturesInTable.docx");
  document.write(out);
  out.close();
  document.close();

 }
}