相关文章推荐
机灵的皮带  ·  c# ...·  1 年前    · 
呐喊的木耳  ·  如何在Microsoft ...·  1 年前    · 
冲动的消炎药  ·  NPM 7 ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I need to remove these tables and paragraphs. As you can see in the image, I need to remove Table 2 and its paragraph Table Parahgraph

Please help me how to do it. I tried using document.removeBodyElement(pos) , but it does not help.

int startIndex = 0;
int endIndex = 0;
startIndex = doc.getPosOfTable(doc.getTables().get(0));
startIndex++;
endIndex = doc.getPosOfTable(doc.getTables().get(1));
System.out.println("startIndex "+ startIndex);
System.out.println("endIndex "+ endIndex);
for(int i=startIndex; i<=endIndex; i++){
    doc.removeBodyElement(i);
                You can find a full code example in this question, which is a little bit similar to yours.
– DenisFLASH
                Jul 21, 2014 at 7:00

The problem is that using removeBodyElement shifts the rest of the elements and recalculates their indices. It means, that if you want to delete elements #4 to #6 (empty paragraph between two tables is included), then after deleting the element #4 (empty line), it is your second TABLE (and not its title paragraph) that will become the element #5, etc. Basically, this loop becomes jumping by two elements (i+=2 instead of i++), thus deleting only half of what you want, and even deleting something you don't want to delete.

Thus, you have just to reverse the order of your loop:

for ( int i = endIndex; i >= startIndex; i-- ) {
    System.out.println( "removing bodyElement #" + i );
    document.removeBodyElement( i );

I've tested it with a template, similar to your example, it works fine! Hope it helps.

Or you could also keep the order of the loop and always remove from startIndex instead of i. – Guga Feb 4, 2016 at 19:09

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.