Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
     Licensed to Plutext Pty Ltd under one or more contributor license agreements.  
     
   *  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 org.docx4j;
 
 import java.io.File;
 import java.util.List;
 import java.util.Set;
 
 
This is a facade for some typical uses of Docx4J:
  • Loading a document
  • Saving a document
  • Binding xml to content controls in a document
  • Exporting the document (to HTML, or PDF and other formats supported by the FO renderer)
 
 public class Docx4J {
 	public static final String MIME_PDF = .;
 	public static final String MIME_FO = .;

No flags passed, do the default
 
 	public static final int FLAG_NONE = 0;

If available export the document using a xsl transformation
 
 	public static final int FLAG_EXPORT_PREFER_XSL = 1;

If available export the document using a visitor
 
 	public static final int FLAG_EXPORT_PREFER_NONXSL = 2;

Save the document in a zip container (default docx)
	public static final int FLAG_SAVE_ZIP_FILE = 1;

Save the document as a flat xml document
	public static final int FLAG_SAVE_FLAT_XML = 2;

inject the passed xml into the document if you don't do this step, then the xml in the document will be used.
	public static final int FLAG_BIND_INSERT_XML = 1;

Insert the data of the xml in the content controls Not needed, if the document will only be opened in word and not converted to other formats.
	public static final int FLAG_BIND_BIND_XML = 2;

Remove the content controls of the document
	public static final int FLAG_BIND_REMOVE_SDT = 4;

Remove any xml parts from the document that are used with the content controls.
	public static final int FLAG_BIND_REMOVE_XML = 8;
	protected static class FindContentControlsVisitor extends TraversalUtilVisitor<SdtElement> {
		public static class BreakException extends RuntimeException {
		}
		protected Set<StringdefinedStoreItemIds = null;
		protected String storeItemId = null;
		public FindContentControlsVisitor(Set<StringdefinedStoreItemIds) {
			this. = definedStoreItemIds;
		}
		public void apply(SdtElement element) {
		SdtPr sdtPr = element.getSdtPr();
			if ((sdtPr.getDataBinding() != null) &&
				(sdtPr.getDataBinding().getStoreItemID() != null)) {
					 = tmp;
					throw new BreakException();
				}
			}
		}
			return ;
		}
	}
	protected static final String NS_CONDITIONS = "http://opendope.org/conditions";
	protected static final String NS_XPATHS = "http://opendope.org/xpaths";
	protected static final String NS_QUESTIONS = "http://opendope.org/questions";
	protected static final String NS_COMPONENTS = "http://opendope.org/components";
	protected static final Set<StringPART_TO_REMOVE_SCHEMA_TYPES = new TreeSet<String>();
	static {
	}

Load a Docx Document from a File
	public static WordprocessingMLPackage load(File inFilethrows Docx4JException {
		return WordprocessingMLPackage.load(inFile);
	}

Load a Docx Document from an InputStream
	public static WordprocessingMLPackage load(InputStream inStreamthrows Docx4JException {
		return WordprocessingMLPackage.load(inStream);
	}

Save a Docx Document to a File
	public static void save(WordprocessingMLPackage wmlPackageFile outFileint flagsthrows Docx4JException {
	OutputStream outStream = null;
		try {
			outStream = new FileOutputStream(outFile);
			save(wmlPackageoutStreamflags);
catch (FileNotFoundException e) {
			throw new Docx4JException("Exception creating output stream: " + e.getMessage(), e);
		}
		finally {
			if (outStream != null) {
				try {
					outStream.close();
catch (IOException e) {}
				outStream = null;
			}
		}
	}

Save a Docx Document to an OutputStream
	public static void save(WordprocessingMLPackage wmlPackageOutputStream outStreamint flagsthrows Docx4JException {
		if (flags == ) {
			FlatOpcXmlCreator opcXmlCreator = new FlatOpcXmlCreator(wmlPackage);
			org.docx4j.xmlPackage.Package pkg = opcXmlCreator.get();
			Marshaller marshaller;
			try {
				marshaller = jc.createMarshaller();
				NamespacePrefixMapperUtils.setProperty(marshaller
						NamespacePrefixMapperUtils.getPrefixMapper());			
				marshaller.marshal(pkgoutStream);				
catch (JAXBException e) {
				throw new Docx4JException("Exception marshalling document for output: " + e.getMessage(), e);
			}
		}
		else {
			SaveToZipFile saver = new SaveToZipFile(wmlPackage);
			saver.save(outStream);
		}
	}

Bind the content controls of the passed document to the xml.
	public static void bind(WordprocessingMLPackage wmlPackageString xmlDocumentint flagsthrows Docx4JException {
		ByteArrayInputStream xmlStream = null;
		if (flags == ) {
			//do everything
		}
			try {
				xmlStream = new ByteArrayInputStream(xmlDocument.getBytes("UTF-8"));
				xmlStream = new ByteArrayInputStream(xmlDocument.getBytes());
			}
		}
        bind(wmlPackagexmlStreamflags);
	}

Bind the content controls of the passed document to the xml.
	public static void bind(WordprocessingMLPackage wmlPackageInputStream xmlDocumentint flagsthrows Docx4JException {
		if (flags == ) {
			//do everything
		}
	    Document xmlDoc = null;
		    DocumentBuilder documentBuilder = null
				try {
		            documentBuilder = XmlUtils.getDocumentBuilderFactory().newDocumentBuilder(); 
		            xmlDoc = documentBuilder.parse(xmlDocument);
catch (Exception e) {
					throw new Docx4JException("Problems creating a org.w3c.dom.Document for the passed input stream."e);
				}
		}
        bind(wmlPackagexmlDocflags);
	}

Bind the content controls of the passed document to the xml.
	public static void bind(WordprocessingMLPackage wmlPackageDocument xmlDocumentint flagsthrows Docx4JException {
	OpenDoPEHandler	openDoPEHandler = null;
	CustomXmlDataStoragePart customXmlDataStoragePart = null;
	RemovalHandler removalHandler = null;
	String xpathStorageItemId = null;
		if (flags == ) {
			//do everything
		}
		xpathStorageItemId = findXPathStorageItemIdInXPathsPart(wmlPackage);
		if ((xpathStorageItemId == null) && (flags == )) {
			//If no XPathsPart found and the user only wants to inject the XML 
			//then search for a storageItemId via the content controls.
			//If the user wants to do more, then it won't work as the BindingHandler
			//relies on the XPathsPart
			xpathStorageItemId = findXPathStorageItemIdInContentControls(wmlPackage);
		}
		if (xpathStorageItemId == null) {
			throw new Docx4JException("No xpathStorageItemId found, does the document contain content controls that are bound?");
		}
			insertXMLData(wmlPackagexpathStorageItemIdxmlDocument);
		}
		if ((flags & ) == ) {
			openDoPEHandler = new OpenDoPEHandler(wmlPackage);
			openDoPEHandler.preprocess();
			BindingHandler.applyBindings(wmlPackage);
		}
			removeSDTs(wmlPackage);
		}
			removeDefinedCustomXmlParts(wmlPackagexpathStorageItemId);
		}
	}
	protected static void insertXMLData(WordprocessingMLPackage wmlPackage
										String storageIdDocument xmlDocumentthrows Docx4JException {
	CustomXmlDataStorage customXmlDataStorage = null;
	CustomXmlDataStoragePart customXmlDataStoragePart = null;
		customXmlDataStoragePart = (CustomXmlDataStoragePart)wmlPackage.getCustomXmlDataStorageParts().get(storageId.toLowerCase());
		customXmlDataStoragePart.getData().setDocument(xmlDocument);
	}
	String ret = null;
	List<XpathxpathList = null;
	Xpath xpath = null;
		try {
			if ((wmlPackage.getMainDocumentPart().getXPathsPart() != null) &&
				(wmlPackage.getMainDocumentPart().getXPathsPart().getJaxbElement() != null) &&
				(wmlPackage.getMainDocumentPart().getXPathsPart().getJaxbElement().getXpath() != null)) {
				xpathList = wmlPackage.getMainDocumentPart().getXPathsPart().getJaxbElement().getXpath();
			}
		}
		catch (NullPointerException npe) {
			//noop
		}
		if ((xpathList != null) && (xpathList.size() > 0)) {
			for (int i=0; (ret == null) && (i<xpathList.size()); i++) {
				xpath = xpathList.get(i);
				if (xpath.getDataBinding() != null) {
					ret = xpath.getDataBinding().getStoreItemID();
				}
			}
		}
		return ret;
	}
	FindContentControlsVisitor visitor = null;
		if ((wmlPackage.getCustomXmlDataStorageParts() != null) && 
			try {
				TraversalUtil.visit(wmlPackagefalsevisitor);
			}
			}
		}
		return (visitor != null ? visitor.getdefinedStoreItemId() : null);
	}
	protected static void removeSDTs(WordprocessingMLPackage wmlPackage)throws Docx4JException {
	RemovalHandler removalHandler;
	removalHandler = new RemovalHandler();
	removalHandler.removeSDTs(wmlPackage.getMainDocumentPart(), .., (String[])null);
		for (Part part:wmlPackage.getParts().getParts().values()) {
			if (part instanceof HeaderPart) {
				removalHandler.removeSDTs((HeaderPart)part.., (String[])null);
			}
			else if (part instanceof FooterPart) {
				removalHandler.removeSDTs((FooterPart)part.., (String[])null);
			}
		}
	}
	protected static void removeDefinedCustomXmlParts(WordprocessingMLPackage wmlPackageString xpathStorageItemId) {
	List<PartNamepartsToRemove = new ArrayList<PartName>();
	RelationshipsPart relationshipsPart = wmlPackage.getMainDocumentPart().getRelationshipsPart();
	List<RelationshiprelationshipsList = ((relationshipsPart != null) && 
										    (relationshipsPart.getRelationships() != null) ?
										    relationshipsPart.getRelationships().getRelationship() : null);
	Part part = null;
	CustomXmlDataStoragePart dataPart = null;
		if (relationshipsList != null) {
			for (Relationship relationship : relationshipsList) {
					part = relationshipsPart.getPart(relationship);
					if (IsPartToRemove(partxpathStorageItemId)) {
						partsToRemove.add(part.getPartName());
					}
				}
			}
		}
		if (!partsToRemove.isEmpty()) {
			for (int i=0; i<partsToRemove.size(); i++) {
				relationshipsPart.removePart(partsToRemove.get(i));
			}
		}
	}
	protected static boolean IsPartToRemove(Part partString xpathStorageItemId) {
	boolean ret = false;
	RelationshipsPart relationshipsPart = part.getRelationshipsPart();
	List<RelationshiprelationshipsList = ((relationshipsPart != null) && 
										    (relationshipsPart.getRelationships() != null) ?
										    relationshipsPart.getRelationships().getRelationship() : null);
	CustomXmlDataStoragePropertiesPart propertiesPart = null;
	DatastoreItem datastoreItem = null;
		if ((relationshipsList != null) && (!relationshipsList.isEmpty())) {
			for (Relationship relationship : relationshipsList) {
					propertiesPart = (CustomXmlDataStoragePropertiesPart)relationshipsPart.getPart(relationship);
					break;
				}
			}
		}
		if (propertiesPart != null)  {
			datastoreItem = propertiesPart.getJaxbElement();
		}
		if (datastoreItem != null) {
			if ((datastoreItem.getItemID() != null) && (datastoreItem.getItemID().length() > 0)) {
				ret = datastoreItem.getItemID().equals(xpathStorageItemId);
			}
			if ((!ret) && 
				(datastoreItem.getSchemaRefs() != null) && 
				(datastoreItem.getSchemaRefs().getSchemaRef() != null) &&
				(!datastoreItem.getSchemaRefs().getSchemaRef().isEmpty())) {
				for (SchemaRef ref : datastoreItem.getSchemaRefs().getSchemaRef()) {
						ret = true;
						break;
					}
				}
			}
		}
		return ret;
	}

Duplicate the document
	public static WordprocessingMLPackage clone(WordprocessingMLPackage wmlPackagethrows Docx4JException {
		//Using the PartialDeepCopy is probably faster than serializing and deserializing the complete document.
		return (WordprocessingMLPackage)PartialDeepCopy.process(wmlPackagenull);
	}

Create the configuration object for conversions that are done via xsl-fo
	public static FOSettings createFOSettings() {
		return new FOSettings();
	}

Convert the document via xsl-fo
	public static void toFO(FOSettings settingsOutputStream outputStreamint flagsthrows Docx4JException {
	Exporter<FOSettingsexporter = getFOExporter(flags);
		exporter.export(settingsoutputStream);
	}

Convenience method to convert the document to PDF
	public static void toPDF(WordprocessingMLPackage wmlPackageOutputStream outputStreamthrows Docx4JException {
		settings.setWmlPackage(wmlPackage);
		settings.setApacheFopMime("application/pdf");
		toFO(settingsoutputStream);
	}
	protected static Exporter<FOSettingsgetFOExporter(int flags) {
		switch (flags) {
				return FOExporterVisitor.getInstance();
			default:
				return FOExporterXslt.getInstance();
		}
	}

Create the configuration object for conversions to html
	public static HTMLSettings createHTMLSettings() {
		return new HTMLSettings();
	}

Convert the document to HTML
	public static void toHTML(HTMLSettings settingsOutputStream outputStreamint flagsthrows Docx4JException {
	Exporter<HTMLSettingsexporter = getHTMLExporter(flags);
		exporter.export(settingsoutputStream);
	}

Convert the document to HTML
	public static void toHTML(WordprocessingMLPackage wmlPackageString imageDirPathString imageTargetUriOutputStream outputStreamthrows Docx4JException {
		settings.setWmlPackage(wmlPackage);
		if (imageDirPath != null) {
			settings.setImageDirPath(imageDirPath);
		}
		if (imageTargetUri != null) {
			settings.setImageTargetUri(imageTargetUri);
		}
		toHTML(settingsoutputStream);
	}
	protected static Exporter<HTMLSettingsgetHTMLExporter(int flags) {
		switch (flags) {
				return HTMLExporterVisitor.getInstance();
			default:
				return HTMLExporterXslt.getInstance();
		}
	}
New to GrepCode? Check out our FAQ X