Insert piece of .doc .docx file to another by using the Apache POI HWPF or XWPF

4.5k views Asked by At

Can somebody help me to integrate some MS Word document to another. I can open, edit and save, but only with one MS Word document.

My simple code only creates, edits and saves .docx:

import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;

public class SimpleDocument {

public  void SimpleDocument() throws Exception {
    XWPFDocument doc = new XWPFDocument();

    XWPFParagraph p1 = doc.createParagraph();
    p1.setAlignment(ParagraphAlignment.CENTER);
    p1.setAlignment(ParagraphAlignment.LEFT);//setVerticalAlignment(TextAlignment.TOP);

    XWPFRun r1 = p1.createRun();
    r1.setBold(true);
    r1.setText("The quick brown fox");
    r1.setFontFamily("Courier");
    r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH);

    XWPFParagraph p2 = doc.createParagraph();
    p2.setAlignment(ParagraphAlignment.RIGHT);

    XWPFRun r2 = p2.createRun();
    r2.setText("jumped over the lazy dog");

    FileOutputStream out = new FileOutputStream("C:/simple.docx");
    doc.write(out);
    out.close();

}
}

How to combine two pieces of formatted text (RANGE, PARAGRAPH) ?

1

There are 1 answers

0
Michael Abdelsayed On

try the following code:

import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.*;

public class test {
    public static void main(String[] args) throws Exception {
        // POI apparently can't create a document from scratch,
        // so we need an existing empty dummy document
        HWPFDocument doc = new HWPFDocument(new FileInputStream("D:\\src.doc"));
        Range range = doc.getRange();
        CharacterRun run = range
                .insertAfter("Text After copied file contents!");
        run.setBold(true);
        OutputStream out = new FileOutputStream("D:\\result.doc");
        doc.write(out);
        out.flush();
        out.close();

    }
}