istiti
istiti

Reputation: 139

refresh XWPFDocument changes

I need remove cover page from document

XWPFDocument document = ...;

if(document.getBodyElements().get(0) instanceof XWPFSDT) {
    document.removeBodyElement(0);
}

When debugging document the XWPFSDT element is correctly removed but on output cover page is still here.

Is there some way to update/refresh document xml, even if changes are happens from low level, how can we refresh docs to keep it uptodate

Upvotes: 0

Views: 841

Answers (1)

Axel Richter
Axel Richter

Reputation: 61862

Until apache poi version 3.17, the XWPFDocument.removeBodyElement removes only BodyElementType.TABLE or BodyElementType.PARAGRAPH properly. It lacks CTBody.removeSdt.

So we must do the low level stuff our self:

import java.io.FileInputStream;
import java.io.FileOutputStream;

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

public class WordRemoveCoverPage {

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

  XWPFDocument document = new XWPFDocument(new FileInputStream("WordDocumentWithCoverPage.docx"));

  if(document.getBodyElements().get(0) instanceof XWPFSDT) {
   System.out.println(document.removeBodyElement(0)); // true == success, but low level <w:sdt> is not removed from the XML
   document.getDocument().getBody().removeSdt(0);
  }

  document.write(new FileOutputStream("WordDocumentWithoutCoverPage.docx"));

  document.close();
 }
}

Upvotes: 2

Related Questions