1

I'm facing the following situation and problem:

I have to retrieve an existing .doc/.docx file and modify it by adding a footer for every page of the document containing an image and some text. I've been trying to achieve this by using Apache POI API, but I've had no luck so far. Even though I've searched a lot for examples and guides, the ones I've found could only lead me to more disappointment.

I gave up Aspose due the expensive price, so I believe POI API would be the only way to achieve this goal.

I believe the closest I got from doing it using .doc was doing this piece of code, but it only creates the footer section with no text, and crashes the images in the document:

POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("C:/testeF.doc"));
HWPFDocument doc = new HWPFDocument(fs);
//WordExtractor we = new WordExtractor(doc);
HeaderStories headerStories = new HeaderStories(doc);
Range rangeO = headerStories.getOddFooterSubrange();
if(rangeO == null)
    rangeO = headerStories.getRange();
rangeO.insertAfter("Footer text from POI");
FileOutputStream newdoc = new FileOutputStream("C:/output.doc");
doc.write(newdoc);
newdoc.close();

Could any of you give any piece of advice for fixing these problems, please?

Kara
  • 6,115
  • 16
  • 50
  • 57
eBergamo
  • 101
  • 3
  • 6

1 Answers1

0

Some update regarding the .docx files(XWPF, not HWPF), I can now create a footer with some text or insert some text to an existing footer, but if the footer already exists, I just append the new text to existing one, I can't find a way to overwrite it.

Ex: Existing footer = "Test"

Footer after executing the following code = "TestTest"

Wanted result = "Test"(overwrote the first "Test" footer text

String text = "Test";
    File docxFile = new File("C:/testeXWPF.docx");
    FileInputStream finStream = new FileInputStream(docxFile.getAbsolutePath());
    XWPFDocument doc = new XWPFDocument(finStream);

    XWPFHeaderFooterPolicy policy = doc.getHeaderFooterPolicy();
    if (policy == null) {
        policy = new XWPFHeaderFooterPolicy(doc);
    }

    CTP ctP1 = CTP.Factory.newInstance();
    CTR ctR1 = ctP1.addNewR();
    CTText t = ctR1.addNewT();
    t.setStringValue(text);
    XWPFParagraph codePara = new XWPFParagraph(ctP1);

    XWPFParagraph[] newparagraphs = new XWPFParagraph[1];
    newparagraphs[0] = codePara;

    policy.createFooter(policy.DEFAULT, newparagraphs);

    FileOutputStream fileOut = new FileOutputStream(docxFile);

    doc.write(fileOut);

    fileOut.close();

For now, this applies only to docx files(XWPF), but I'll have to find some way to do the same thing to doc files(HWPF).

Any hints?

eBergamo
  • 101
  • 3
  • 6
  • the above example is not working, when I modified code using above code then getting error that some problem in xml content. – asifaftab87 Oct 07 '14 at 09:27