简体   繁体   中英

For Image, appending is not happening in Word Doc(.docx) in Java

I have tried following code:

   File f=new File("stackover.docx");
   XWPFDocument doc=new XWPFDocument(OPCPackage.open(new FileInputStream(f)));
  List<XWPFParagraph>  paragraphs = doc.getParagraphs();
  XWPFParagraph para =  paragraphs.get(paragraphs.size() - 1);
  org.apache.poi.xwpf.usermodel.XWPFRun run=para.createRun();
    XWPFTable table=doc.createTable();
    XWPFTableRow row=table.getRow(0);
    FileOutputStream fos=new FileOutputStream(f);
    File fileName=new File("stackOverImage.jpeg");
    FileInputStream fis=new FileInputStream(fileName);
    File fileName1=new File("stackOverImage2.jpeg");
    FileInputStream fis1=new FileInputStream(fileName1);

    run.addBreak();

    run.setText("Append The value please");
    run.addBreak();
    run.addPicture(fis, XWPFDocument.PICTURE_TYPE_JPEG, fileName.toString(),        Units.toEMU(320), Units.toEMU(210));
    fis.close();
    run.addBreak(BreakType.PAGE);
    run.setText("Append The value please 12");
    run.addBreak();
    run.addPicture(fis1, XWPFDocument.PICTURE_TYPE_JPEG, fileName1.toString(),  Units.toEMU(320), Units.toEMU(210));
    fis1.close();
    doc.write(fos);
    fos.flush();
    fos.close();

Note: The document is already saved & has header & footer.

If I try to append an image in a document which doesn't have header & footer, the above code works great. Although, size of file is increased after the execution, but while I try to open the file, it says We're sorry. We can't open the file. We found a problem with its content . Can you please explain the reason why this happening & solution? Thanks in advance.

I am using following jars: 1. Poi 3.12
2. Poi -ooxml-3.10.1
3. Poi-scratchpad-3.15
4. Ooxml-schemas-1.1
5. Xmlbeans-2.3.0
6. Dom4j-1.1

Error is like below: 在此处输入图片说明 在此处输入图片说明

First problem is that your jars are all from different versions of POI.

Before you do anything else, replace your jars with a single version of POI. I see you mixing at least versions 3.10, 3.12, and 3.15. The POI jars are not developed independently of one another, and mixing and matching does not work. Next, you do not need the scratchpad jar for XWPF documents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM