feiyu02
2022-11-15 23bd719cebe5feeff4e48fde925b0b39755eea93
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
/*
 *  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.jaxb.Context;
import org.docx4j.openpackaging.contenttype.CTOverride;
import org.docx4j.openpackaging.contenttype.ContentTypeManager;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.DocumentSettingsPart;
import org.docx4j.openpackaging.parts.relationships.Namespaces;
import org.docx4j.openpackaging.parts.relationships.RelationshipsPart;
import org.docx4j.samples.AbstractSample;
import org.docx4j.wml.CTRel;
import org.docx4j.wml.CTSettings;
 
import java.io.File;
import java.net.URI;
 
/**
 * Creates a WordprocessingML document from the template (dotx file),
 * and optionally, attaches that template (for example, instead of Normal.dot)
 * 
 * Be sure to set String templatePath. 
 * 
 * In Flat OPC terms, aim is to produce:
 * 
  <pkg:part pkg:name="/word/settings.xml" pkg:contentType="application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml">
    <pkg:xmlData>
      <w:settings xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:sl="http://schemas.openxmlformats.org/schemaLibrary/2006/main">
        <w:attachedTemplate r:id="rId1"/>
      </w:settings>
    </pkg:xmlData>
  </pkg:part>
 *   <pkg:part pkg:name="/word/_rels/settings.xml.rels" pkg:contentType="application/vnd.openxmlformats-package.relationships+xml">
    <pkg:xmlData>
      <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
        <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate" Target="file:///C:\Users\jharrop\AppData\Roaming\Microsoft\Templates\fabdocx-release-20101002B.dotm" TargetMode="External"/>
      </Relationships>
    </pkg:xmlData>
  </pkg:part>
 
 * 
 * @author Jason Harrop
 */
public class TemplateAttach extends AbstractSample {
    
    static boolean attachTemplate = true; // whether to set w:attachedTemplate
 
    public static void main(String[] args) throws Exception {
        
        String dotx = "C:\\Users\\jharrop\\AppData\\Roaming\\Microsoft\\Templates\\mytemplate.dotx";
        String templatePath = "file:///" + dotx;
        
        try {
            getInputFilePath(args);
        } catch (IllegalArgumentException e) {
            inputfilepath = System.getProperty("user.dir") + "/OUT_TemplateAttach.docx";            
        }
        
        boolean save = 
            (inputfilepath == null ? false : true);
                
        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new File(dotx));
        // NB: clone here if your use case requires it
        
        // Replace dotx content type with docx
        ContentTypeManager ctm = wordMLPackage.getContentTypeManager();
        
        // Get <Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml"/>
        CTOverride override = ctm.getOverrideContentType().get(new URI("/word/document.xml")); // note this assumption
        if (dotx.endsWith("dotm")) // // macro enabled?            
        {
            override.setContentType(org.docx4j.openpackaging.contenttype.ContentTypes.WORDPROCESSINGML_DOCUMENT_MACROENABLED);  
        } else {
            override.setContentType(org.docx4j.openpackaging.contenttype.ContentTypes.WORDPROCESSINGML_DOCUMENT);  
        }
        
        
        if (attachTemplate) {
            // Create settings part, and init content
            DocumentSettingsPart dsp = new DocumentSettingsPart();
            CTSettings settings = Context.getWmlObjectFactory().createCTSettings();
            dsp.setJaxbElement(settings);
            wordMLPackage.getMainDocumentPart().addTargetPart(dsp);
            
            // Create external rel
            RelationshipsPart rp = RelationshipsPart.createRelationshipsPartForPart(dsp);         
            org.docx4j.relationships.Relationship rel = new org.docx4j.relationships.ObjectFactory().createRelationship();
            rel.setType( Namespaces.ATTACHED_TEMPLATE  );
            rel.setTarget(templatePath);
            rel.setTargetMode("External");          
            rp.addRelationship(rel); // addRelationship sets the rel's @Id
            
            settings.setAttachedTemplate(
                    (CTRel)XmlUtils.unmarshalString("<w:attachedTemplate xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\" r:id=\"" + rel.getId() + "\"/>", Context.jc, CTRel.class)
                    );
             
            // or (yuck)... 
    //        CTRel id = new CTRel();
    //        id.setId( rel.getId() );
    //        JAXBElement<CTRel> je = new JAXBElement<CTRel>(
    //                new QName("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "attachedTemplate"), 
    //                CTRel.class, null, id);
    //        settings.setAttachedTemplate(je.getValue());
        }
        
        // Now save it
        if (save) {
            wordMLPackage.save(new File(inputfilepath) );
        } 
    }
    
    
}