Wiki

Clone wiki

Aspose Java for Docx4j / Merge-Documents

Aspose.Words

Document doc1 = new Document(dataPath + "doc1.doc");
Document doc2 = new Document(dataPath + "doc2.doc");

doc1.appendDocument(doc2, ImportFormatMode.KEEP_SOURCE_FORMATTING);

Docx4j

final static String[] sourceDocxNames = { "doc1.docx", "doc2.docx"};  

static boolean save = true;
static String outputfilepath = dataPath +"OUT_MergeDocx.docx";      

/**
 * @param args
 * @throws Docx4JException 
 */
public static void main(String[] args) throws Docx4JException {

    // Create list of docx packages to merge
    List<WordprocessingMLPackage> wmlPkgList=new ArrayList<WordprocessingMLPackage>();
    for (int i=0; i<sourceDocxNames.length; i++){
        String filename = dataPath + sourceDocxNames[i] ;
        System.out.println("Loading " + filename); 
        wmlPkgList.add(WordprocessingMLPackage
                .load(new java.io.File(filename)));
    }

    try {
        // Use reflection, so docx4j can be built
        // by users who don't have the MergeDocx utility
        Class<?> documentBuilder = Class.forName("com.plutext.merge.DocumentBuilder");          
        //Method method = documentBuilder.getMethod("merge", wmlPkgList.getClass());            
        Method[] methods = documentBuilder.getMethods(); 
        Method method = null;
        for (int j=0; j<methods.length; j++) {
            System.out.println(methods[j].getName());
            if (methods[j].getName().equals("merge")) {
                method = methods[j];
                break;
            }
        }           
        if (method==null) throw new NoSuchMethodException();

        WordprocessingMLPackage resultPkg = (WordprocessingMLPackage)method.invoke(null, wmlPkgList);

        if (save) {     
            SaveToZipFile saver = new SaveToZipFile(resultPkg);
            saver.save(outputfilepath);
            System.out.println("Generated " + outputfilepath);
        } else {
            String result = XmlUtils.marshaltoString(resultPkg.getMainDocumentPart().getJaxbElement(), true, true);
            System.out.println(result);             
        }

    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        extensionMissing(e);
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        extensionMissing(e);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } 
}

Download Source Code

Updated