【问题标题】:how to add images side by side word document using apache poi如何使用apache poi并排添加图像
【发布时间】:2019-11-12 13:44:56
【问题描述】:

我想使用 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文档。我究竟做错了什么?

【问题讨论】:

    标签: java apache-poi


    【解决方案1】:

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

    您的代码还将所有图片添加到同一个XWPFRun。但它应该将图片添加到XWPFTableCells 中的不同运行中。为此,您需要获取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();
    
     }
    }
    

    【讨论】:

    • 我试过这个代码,它给了我这个错误 java.net.MalformedURLException: no protocol: \\ptrisf02\group\Corrolog\EVM\Pictures\EV12080-01\DSCF7270.JPG.
    • @mustafa53:我的代码是完整的并且可以正常工作。它使用HTTPHTTPS 资源作为图片资源。如果你使用文件资源而不是HTTPHTTPS作为图片资源,那么你需要使用FileInputStream而不是URLs。但是您已经在问题中显示的代码中完成了这一点。
    • 好的。我使用了 FileInputSteam 并且它有效。有一些速度问题,但现在已经足够了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多