Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package org.docx4j.model.datastorage.migration;
  
  import java.util.HashMap;
  import java.util.List;
  import java.util.Map;
  import java.util.UUID;
  
 
This class will help you to migrate from a string replacement approach, to use of content control data bindings. After migrating, you'll be able to use the OpenDoPE authoring tool to add repeats, conditionals, and other OpenDoPE features, if you need them. It assumes your magic strings take the form ${--}. If they don't, you'll need to modify this class, or use Word to search/replace to change them so they take that form. We'd be happy to accept a patch which specifies a regex the magic string must match. Limitations: this first version operates only on the main document part (ie it won't process variables in headers/footers, footnotes/endnotes, or comments)

Author(s):
jharrop
Since:
3.0.0
 
 public class FromVariableReplacement extends AbstractMigrator {
 	
 	private static Logger log = LoggerFactory.getLogger(FromVariableReplacement.class);
 		
 		
 		// TODO - test that OpenDoPE parts aren't already present
 		// or if they are, that this docx is using our answer format
 		// (since only that format is supported here)
 		
 		// Clone it
 		
 		// Run the cleaner first
 		VariablePrepare.prepare(pkgOut);		
 		
 		// Create the CustomXML parts
 		createParts(pkgOut);
 		
 		// Operate at the p level
		PFinder pFinder = new PFinder();
        new TraversalUtil(pkgOut.getMainDocumentPart().getContent(), pFinder);
        for ( P p : pFinder.pList) { 
        	
        	List<ObjectreplacementContent = new ArrayList<Object>(); 
        	
        	for (Object o : p.getContent() ) {
        		
        		o = XmlUtils.unwrap(o);
        		
        		if ( o instanceof R) {
        			
        			for (Object o2 : ((R)o).getContent() ) {
                		o2 = XmlUtils.unwrap(o2);
        				
        				if ( o2 instanceof Text ) {
        					handle((R)o, ((Text)o2).getValue(), 0, replacementContent);
        				} else {
        					// Just add this bit
        					R rnew = new R();
        					rnew.setRPr( ((R)o).getRPr() ); // point at old rPr, if any
        					rnew.getContent().add(o2);
        					replacementContent.add(rnew);
        				}        				
        			}
        		} else {
        			replacementContent.add(o);
        		}
        	}
        	
        	p.getContent().clear();
        	p.getContent().addAll(replacementContent);
        	
        }
		return pkgOut;
	}
	private void handle(R rString sint offset,
			List<ObjectreplacementContent) {
		int startKey = s.indexOf("${"offset);
		if (startKey == -1) {
			addTextRun(rs.substring(offset), replacementContent);
			return;
else {
			addTextRun(rs.substring(offsetstartKey), replacementContent);
			int keyEnd = s.indexOf('}'startKey);
			String key = s.substring(startKey + 2, keyEnd);
			createContentControl(r.getRPr(), replacementContentkey);
			handle(rskeyEnd + 1, replacementContent);
		}
	}
	 private void addTextRun(R rString valList<ObjectreplacementContent) {
		 
			R rnew = new R();
			rnew.setRPrr.getRPr() ); // point at old rPr, if any
			Text text = Context.getWmlObjectFactory().createText();
			text.setValue(val);
			if (val.startsWith(" ")
					|| val.endsWith(" ") ) {
				text.setSpace("preserve");
			}
			rnew.getContent().add(text);
			replacementContent.add(rnew);
		 
	 }
	 
	public String addPropertiesPart(JaxbCustomXmlDataStoragePart<?> customXmlDataStoragePartString ns)
		String newItemId = "{" + UUID.randomUUID().toString().toUpperCase() + "}";
		dsi.setItemID(newItemId);
		dsi.setSchemaRefs(srefs);
		sref.setUri(ns);
		srefs.getSchemaRef().add(sref);
		part.setJaxbElement(dsi);
		customXmlDataStoragePart.addTargetPart(part.);
		return newItemId;
	}
	  static class PFinder extends CallbackImpl {
          List<PpList = new ArrayList<P>();  
          @Override
          public List<Objectapply(Object o) {
              if (o instanceof P ) {
            	  .add((P)o);
              }                      
              return null;
          }
	  }



Parameters:
args
Throws:
java.lang.Exception
	public static void main(String[] argsthrows Exception {
		String inputfilepath = System.getProperty("user.dir") + "/sample-docs/word/unmarshallFromTemplateExample.docx";
		String outputfilepath = System.getProperty("user.dir")
"/OUT_VariableReplace.docx";
		WordprocessingMLPackage pkgIn = WordprocessingMLPackage.load(new java.io.File(inputfilepath));
		WordprocessingMLPackage pkgOut = migrator.migrate(pkgIn);
		SaveToZipFile saver = new SaveToZipFile(pkgOut);
		saver.save(outputfilepath);
	}
New to GrepCode? Check out our FAQ X