Pregunta

I found that people use docx4j to modify docx's. I went through 'getting started' and I believe I have basic knowledge of this lib works.

What I want to achieve is to add basic text to the beginning of document (before any other text). I managed to add text to the end of file. Here is the code:

    for(File file: folder.listFiles())
    {
        if(file.getName().contains("docx"))
        {
            try
            {
                WordprocessingMLPackage docx = WordprocessingMLPackage.load(file);
                docx.getMainDocumentPart().addParagraphOfText(toAppend);
                docx.save(new File(file.getAbsolutePath()));
            }
            catch (Docx4JException e)
            {
                e.printStackTrace();
            }
        }
    }

but It doesn't behave in the way that I expected. It appends text to the eof. How can I add text before MainDocumentPart, not after? Also I would like to keep code clean and simple to read.

¿Fue útil?

Solución

Here's a simple method which will do what you want:

    public org.docx4j.wml.P addParaAtIndex(MainDocumentPart mdp, String simpleText, int index) {

    org.docx4j.wml.ObjectFactory factory = Context.getWmlObjectFactory();
    org.docx4j.wml.P  para = factory.createP();

    if (simpleText!=null) {
        org.docx4j.wml.Text  t = factory.createText();
        t.setValue(simpleText);

        org.docx4j.wml.R  run = factory.createR();
        run.getContent().add(t); 

        para.getContent().add(run); 
    }

    mdp.getContent().add(index, para);

    return para;
}

I haven't bothered checking for IndexOutOfBoundsException in this example

Otros consejos

I'm not aware of a way to do that with docx4j, but I'm also not very familiar with that library. If you are up to trying a different library, then you can download Apache POI and do the following:

for(File file: folder.listFiles())
{
    if(file.getName().contains("docx"))
    {
        try
        {
            HWPFDocument docx= new HWPFDocument(new java.io.FileInputStream(file));
            docx.getRange().insertBefore(toAppend);
            FileOutputStream fileOut = new FileOutputStream(file);
            docx.write(fileOut);
            fileOut.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top