feiyu02
2024-11-19 752e00503f672ddfe2066afb6c235721a3a912b5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
/*
 *  Copyright 2007-2008, Plutext Pty Ltd.
 *   
 *  This file is part of docx4j.
 
    docx4j is licensed under the Apache License, Version 2.0 (the "License"); 
    you may not use this file except in compliance with the License. 
 
    You may obtain a copy of the License at 
 
        http://www.apache.org/licenses/LICENSE-2.0 
 
    Unless required by applicable law or agreed to in writing, software 
    distributed under the License is distributed on an "AS IS" BASIS, 
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
    See the License for the specific language governing permissions and 
    limitations under the License.
 
 */
 
package cn.flightfeather.supervision.docx4j.simpleDemo;
 
import org.docx4j.XmlUtils;
import org.docx4j.model.datastorage.*;
import org.docx4j.model.datastorage.RemovalHandler.Quantifier;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.io.SaveToZipFile;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
 
import javax.xml.bind.JAXBContext;
import java.lang.reflect.Method;
import java.util.concurrent.atomic.AtomicInteger;
 
 
/**
 * This sample demonstrates populating content controls
 * from a custom xml part (based on the xpaths given
 * in the content controls).
 * 
 * Word does this itself automatically, for if there is
 * a w:databinding element in the sdtPr.
 * 
 * However, out of the box, Word doesn't allow for
 * repeating things (table rows, paragraphs etc), nor
 * conditional inclusion/exclusion.
 * 
 * The OpenDoPE conventions support that; and this sample 
 * demonstrates docx4j's implementation of that.
 * 
 * In practice you'll want the XML part to be injected at runtime.  
 * For that, see the sample: ContentControlsMergeXML
*/
public class ContentControlBindingExtensionsOld {
    
    public static JAXBContext context = org.docx4j.jaxb.Context.jc; 
 
    static String filepathprefix;
    
    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        
        String inputfilepath = System.getProperty("user.dir") + "/sample-docs/word/databinding/invoice.docx";
//        String inputfilepath = System.getProperty("user.dir") + "/sample-docs/word/databinding/CountryRegions.xml";
        
        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));        
        
        filepathprefix = inputfilepath.substring(0, inputfilepath.lastIndexOf("."));
        System.out.println(filepathprefix);
        
        StringBuilder timingSummary = new StringBuilder();
        
 
        // Process conditionals and repeats
        long startTime = System.currentTimeMillis();
        OpenDoPEHandler odh = new OpenDoPEHandler(wordMLPackage);
        odh.preprocess();
        long endTime = System.currentTimeMillis();
        timingSummary.append("OpenDoPEHandler: " + (endTime-startTime));
 
        System.out.println(
                XmlUtils.marshaltoString(wordMLPackage.getMainDocumentPart().getJaxbElement(), true, true)
                );        
        
        startTime = System.currentTimeMillis();
        OpenDoPEIntegrity odi = new OpenDoPEIntegrity();
        odi.process(wordMLPackage);
        endTime = System.currentTimeMillis();
        timingSummary.append("\nOpenDoPEIntegrity: " + (endTime-startTime));
        
        System.out.println(
                XmlUtils.marshaltoString(wordMLPackage.getMainDocumentPart().getJaxbElement(), true, true)
                );        
        SaveToZipFile saver = new SaveToZipFile(wordMLPackage);
        saver.save(filepathprefix + "_preprocessed.docx");
        System.out.println("Saved: " + filepathprefix + "_preprocessed.docx");
        
        // Apply the bindings
        BindingHandler.setHyperlinkStyle("Hyperlink");                        
        startTime = System.currentTimeMillis();
        
        AtomicInteger bookmarkId = odh.getNextBookmarkId();
        BindingHandler bh = new BindingHandler(wordMLPackage);
        bh.setStartingIdForNewBookmarks(bookmarkId);
        bh.applyBindings(wordMLPackage.getMainDocumentPart());
        
        endTime = System.currentTimeMillis();
        timingSummary.append("\nBindingHandler.applyBindings: " + (endTime-startTime));
        String bound = XmlUtils.marshaltoString(wordMLPackage.getMainDocumentPart().getJaxbElement(), true, true);
        System.out.println(
                );
        saver.save(filepathprefix + "_bound.docx");
        System.out.println("Saved: " + filepathprefix + "_bound.docx");
        
        // process altChunk
        if (bound.contains("altChunk")) {
            try {
                // Use reflection, so docx4j can be built
                // by users who don't have the MergeDocx utility
                Class<?> documentBuilder = Class
                        .forName("com.plutext.merge.ProcessAltChunk");
                // Method method = documentBuilder.getMethod("merge",
                // wmlPkgList.getClass());
                Method[] methods = documentBuilder.getMethods();
                Method processMethod = null;
                for (int j = 0; j < methods.length; j++) {
    //                log.debug(methods[j].getName());
                    if (methods[j].getName().equals("process")) {
                        processMethod = methods[j];
                    }
                }
                if (processMethod == null )
                    throw new NoSuchMethodException();
                
                startTime = System.currentTimeMillis();
                
                wordMLPackage = (WordprocessingMLPackage) processMethod.invoke(null,
                        wordMLPackage);
    
                endTime = System.currentTimeMillis();
                timingSummary.append("\nBindingHandler.applyBindings: " + (endTime-startTime));
                System.out.println(
                        XmlUtils.marshaltoString(wordMLPackage.getMainDocumentPart().getJaxbElement(), true, true)
                        );
                saver.save(filepathprefix + "_altChunksMerged.docx");
                System.out.println("Saved: " + filepathprefix + "_altChunksMerged.docx");
    
                
            } catch (ClassNotFoundException e) {
            } catch (NoSuchMethodException e) {
            } catch (Exception e) {
                throw new Docx4JException("Problem processing w:altChunk", e);
            }    
        }
        
        // Either demonstrate reverter, or stripping of controls;
        // you can't do both. So comment out one or the other.
//        reverter(inputfilepath, filepathprefix + "_bound.docx");
//        
        // Strip content controls
        startTime = System.currentTimeMillis();
        RemovalHandler rh = new RemovalHandler();
        rh.removeSDTs(wordMLPackage, Quantifier.ALL);
        endTime = System.currentTimeMillis();
        timingSummary.append("\nRemovalHandler: " + (endTime-startTime));
 
        saver.save(filepathprefix + "_stripped.docx");
        System.out.println("Saved: " + filepathprefix + "_stripped.docx");
        
        System.out.println(timingSummary);
    }    
    
    public static void reverter(String inputfilepath, String instancePath) throws Docx4JException {
        
        WordprocessingMLPackage instancePkg = WordprocessingMLPackage.load(new java.io.File(instancePath));        
        
        OpenDoPEReverter reverter = new OpenDoPEReverter(
                WordprocessingMLPackage.load(new java.io.File(inputfilepath)), 
                instancePkg);
        
        System.out.println("reverted? " + reverter.revert() );
        
        SaveToZipFile saver = new SaveToZipFile(instancePkg);
        saver.save(filepathprefix + "_reverted.docx");
        System.out.println("Saved: " + filepathprefix + "_reverted.docx");
        
    }
                
    public void extensionMissing(Exception e) {
        System.out.println("\n" + e.getClass().getName() + ": " + e.getMessage() + "\n");
        System.out.println("* You don't appear to have the MergeDocx paid extension,");
        System.out.println("* which is necessary to merge docx, or process altChunk.");
        System.out.println("* Purchases of this extension support the docx4j project.");
        System.out.println("* Please visit www.plutext.com if you want to buy it.");
    }
    
 
}