在word文档中插入图片

时间:2013-07-19 11:53:25

标签: java apache-poi

这是我第一次使用Apache POI,我已经在本网站上提出了我要问的问题,但没有给出明确的答案,所以我别无选择,只能接受你的帮助。

我正在尝试编写一个java程序,它从一个文件夹中获取图像并将该图像插入到word文档中。我在这个程序中使用Apache POI。我在这里发布我的代码。

import java.io.*;
import java.util.*;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xwpf.usermodel.*;

public class ImagesDoc 
{
    public static void main(String[] args) throws IOException 
    {
        XWPFDocument docx = new XWPFDocument();
        XWPFParagraph par = docx.createParagraph();
        XWPFRun run = par.createRun();
        run.setText("Hello, World. This is my first java generated docx-file. Have fun.");
        run.setFontSize(13);
        InputStream pic = new FileInputStream("C:\\Users\\amitabh\\Pictures\\pics\\pool.jpg");
        byte [] picbytes = IOUtils.toByteArray(pic);
        docx.addPicture(picbytes, Document.PICTURE_TYPE_JPEG);

        FileOutputStream out = new FileOutputStream("C:\\Users\\amitabh\\Pictures\\pics\\simple1.docx"); 
        docx.write(out); 
        out.close(); 
        pic.close();
    }
}

我能够创建word文档文件,我也可以插入文本,但docx.addPicture(picbytes, Document.PICTURE_TYPE_JPEG);行给出了错误“add cast to docx”。我为这个程序添加了所有可能的罐子。对于这个错误,我在网上搜索,发现很多人都有类似的问题。 XWPFDocument引用的“addPicture”无法正常工作。请帮我解决这个问题。

2 个答案:

答案 0 :(得分:13)

首先,我想指出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.x2006.main.CTNonVisualDrawingProps;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.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 = "" +
                "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">" +
                "   <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
                "      <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
                "         <pic:nvPicPr>" +
                "            <pic:cNvPr id=\"" + id + "\" name=\"Generated\"/>" +
                "            <pic:cNvPicPr/>" +
                "         </pic:nvPicPr>" +
                "         <pic:blipFill>" +
                "            <a:blip r:embed=\"" + blipId + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>" +
                "            <a:stretch>" +
                "               <a:fillRect/>" +
                "            </a:stretch>" +
                "         </pic:blipFill>" +
                "         <pic:spPr>" +
                "            <a:xfrm>" +
                "               <a:off x=\"0\" y=\"0\"/>" +
                "               <a:ext cx=\"" + width + "\" cy=\"" + height + "\"/>" +
                "            </a:xfrm>" +
                "            <a:prstGeom prst=\"rect\">" +
                "               <a:avLst/>" +
                "            </a:prstGeom>" +
                "         </pic:spPr>" +
                "      </pic:pic>" +
                "   </a:graphicData>" +
                "</a:graphic>";

        //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-模式

xmlbeans

dom4j

答案 1 :(得分:4)

    I have used poi 3.10 to generate word doc and to insert a picture. you need 2 classes.. here is the example

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.List;

    import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
    import org.apache.poi.util.Units;
    import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
    import org.apache.poi.xwpf.usermodel.Document;
    import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
    import org.apache.poi.xwpf.usermodel.UnderlinePatterns;
    import org.apache.poi.xwpf.usermodel.XWPFDocument;
    import org.apache.poi.xwpf.usermodel.XWPFHeader;
    import org.apache.poi.xwpf.usermodel.XWPFParagraph;
    import org.apache.poi.xwpf.usermodel.XWPFRun;
    import org.apache.xmlbeans.XmlException;
    import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

    public class ImageAttachmentInDocument {
        /**
         * @param args
         * @throws IOException
         */
        public static void main(String[] args) throws IOException {

            DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
            Calendar cal = Calendar.getInstance();
            String date = dateFormat.format(cal.getTime());

            // Create a document file
            CustomXWPFDocument document = new CustomXWPFDocument();

            // Adding a file
            try {

                // Working addPicture Code below...
                XWPFParagraph paragraphX = document.createParagraph();
                paragraphX.setAlignment(ParagraphAlignment.CENTER);

                String blipId = paragraphX.getDocument().addPictureData(
                        new FileInputStream(new File("D://c2//WLB.jpg")),
                        Document.PICTURE_TYPE_JPEG);
                System.out.println("4" + blipId);
                System.out.println(document
                        .getNextPicNameNumber(Document.PICTURE_TYPE_JPEG));
                document.createPicture(blipId,
                        document.getNextPicNameNumber(Document.PICTURE_TYPE_JPEG),
                        200, 75);
                System.out.println("5");

            } catch (InvalidFormatException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            // insert doc details
            // Createa a para -1
            XWPFParagraph paragraphOne = document.createParagraph();
            paragraphOne.setAlignment(ParagraphAlignment.CENTER);
            XWPFRun paragraphOneRunOne = paragraphOne.createRun();
            paragraphOneRunOne.setBold(true);
            paragraphOneRunOne.setFontSize(20);
            paragraphOneRunOne.setFontFamily("Verdana");
            paragraphOneRunOne.setColor("000070");
            paragraphOneRunOne.setText("Daily Status Report");

            // Createa a para -2
            XWPFParagraph paragraphTwo = document.createParagraph();
            paragraphTwo.setAlignment(ParagraphAlignment.CENTER);
            XWPFRun paragraphTwoRunOne = paragraphTwo.createRun();
            paragraphTwoRunOne.setFontSize(12);
            paragraphTwoRunOne.setFontFamily("Verdana");
            paragraphTwoRunOne.setColor("000070");
            paragraphTwoRunOne.setText(date);
            paragraphTwoRunOne.addBreak();

            // Createa a para -3
            XWPFParagraph paragraphThree = document.createParagraph();
            paragraphThree.setAlignment(ParagraphAlignment.LEFT);
            XWPFRun paragraphThreeRunOne = paragraphThree.createRun();
            paragraphThreeRunOne.setFontSize(14);
            paragraphThreeRunOne.setFontFamily("Verdana");
            paragraphThreeRunOne.setColor("000070");
            paragraphThreeRunOne.setText("5.30 AM PST");
            paragraphThreeRunOne.addBreak();

            // Createa a para -4
            XWPFParagraph paragraphFour = document.createParagraph();
            paragraphFour.setAlignment(ParagraphAlignment.LEFT);
            XWPFRun paragraphFourRunOne = paragraphFour.createRun();
            paragraphFourRunOne.setBold(true);
            paragraphFourRunOne.setUnderline(UnderlinePatterns.SINGLE);
            paragraphFourRunOne.setFontSize(10);
            paragraphFourRunOne.setFontFamily("Verdana");
            paragraphFourRunOne.setColor("000070");
            paragraphFourRunOne.setText("ABCD");

            // insert doc details end

            XWPFParagraph paragraphFive = document.createParagraph();
            paragraphFive.setAlignment(ParagraphAlignment.RIGHT);
            XWPFRun paragraphFiveRunOne = paragraphFive.createRun();
            paragraphFiveRunOne.addBreak();
            paragraphFourRunOne.setBold(true);
            paragraphFourRunOne.setUnderline(UnderlinePatterns.SINGLE);
            paragraphFourRunOne.setFontSize(10);
            paragraphFourRunOne.setFontFamily("Verdana");
            paragraphFourRunOne.setColor("000070");
            paragraphFourRunOne.setText("ABCD00000000000");

            FileOutputStream outStream = null;
            try {
                double x = Math.random();
                String fileName = "D:\\c2\\" + String.valueOf(x) + ".docx";
                outStream = new FileOutputStream(fileName);
            } catch (FileNotFoundException e) {
                System.out.println("First Catch");
                e.printStackTrace();
            }
            try {
                document.write(outStream);
                outStream.close();
            } catch (FileNotFoundException e) {
                System.out.println("Second Catch");
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("Third Catch");
                e.printStackTrace();
            }
        }
    }

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlToken;
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;

import java.io.IOException;
import java.io.InputStream;

public class CustomXWPFDocument extends XWPFDocument
{
    public CustomXWPFDocument()    {
     super();
    }

    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 = "" +
                "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">" +
                "   <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
                "      <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">" +
                "         <pic:nvPicPr>" +
                "            <pic:cNvPr id=\"" + id + "\" name=\"Generated\"/>" +
                "            <pic:cNvPicPr/>" +
                "         </pic:nvPicPr>" +
                "         <pic:blipFill>" +
                "            <a:blip r:embed=\"" + blipId + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>" +
                "            <a:stretch>" +
                "               <a:fillRect/>" +
                "            </a:stretch>" +
                "         </pic:blipFill>" +
                "         <pic:spPr>" +
                "            <a:xfrm>" +
                "               <a:off x=\"0\" y=\"0\"/>" +
                "               <a:ext cx=\"" + width + "\" cy=\"" + height + "\"/>" +
                "            </a:xfrm>" +
                "            <a:prstGeom prst=\"rect\">" +
                "               <a:avLst/>" +
                "            </a:prstGeom>" +
                "         </pic:spPr>" +
                "      </pic:pic>" +
                "   </a:graphicData>" +
                "</a:graphic>";

        //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");
    }
}