/// <summary>
 /// Create an OpenXML SDK WordprocessingDocument object
 /// from a docx4j WordprocessingMLPackage
 /// </summary>
 /// <param name="wordPkg"></param>
 /// <param name="isEditable"></param>
 /// <param name="openSettings"></param>
 /// <returns></returns>
 public static WordprocessingDocument createWordprocessingDocument(
     WordprocessingMLPackage wordPkg, 
     bool isEditable, OpenSettings openSettings)
 {
     return WordprocessingDocument.Open(
         new MemoryStream(SaveFromJavaUtils.toBytes(wordPkg)), 
         isEditable, openSettings);
 }
        public static byte[] toBytes(WordprocessingMLPackage wordPkg)
        {
            SaveToZipFile saver = new SaveToZipFile(wordPkg);
            java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
            saver.save(baos);

            return baos.toByteArray();
        }
 /// <summary>
 /// Create an OpenXML SDK WordprocessingDocument object
 /// from a docx4j WordprocessingMLPackage
 /// </summary>
 /// <param name="wordPkg"></param>
 /// <param name="isEditable"></param>
 /// <param name="openSettings"></param>
 /// <returns></returns>
 public static WordprocessingDocument createWordprocessingDocument(
     WordprocessingMLPackage wordPkg,
     bool isEditable, OpenSettings openSettings)
 {
     return(WordprocessingDocument.Open(
                new MemoryStream(SaveFromJavaUtils.toBytes(wordPkg)),
                isEditable, openSettings));
 }
        public static byte[] toBytes(WordprocessingMLPackage wordPkg)
        {
            SaveToZipFile saver = new SaveToZipFile(wordPkg);

            java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
            saver.save(baos);

            return(baos.toByteArray());
        }
Esempio n. 5
0
        static void Main(string[] args)
        {
            // set up logging
            clog = LoggingConfigurator.configureLogging();
            clog.Info("Hello from Common Logging");

            // create a dir to save the output docx
            string projectDir = System.IO.Directory.GetParent(
                System.IO.Directory.GetParent(
                    Environment.CurrentDirectory.ToString()).ToString()).ToString() + "\\";

            System.IO.Directory.CreateDirectory(projectDir + "OUT");

            string fileIN  = projectDir + @"src\samples\resources\sample-docx.docx";
            string fileOUT = projectDir + @"OUT\Anon.docx";

            WordprocessingMLPackage pkg = Docx4J.load(new java.io.File(fileIN));
            // or
            // WordprocessingMLPackage pkg = Plutext.Docx4NET.WordprocessingMLPackageFactory.createWordprocessingMLPackage(fileIN);


            // Anonymize/densensitize it
            Anonymize       anon   = new Anonymize(pkg);
            AnonymizeResult result = anon.go();


            // Report
            clog.Info("\n\n REPORT for " + fileIN + "\n\n");
            if (result.isOK())
            {
                clog.Info("document successfully anonymised.");
            }
            else
            {
                clog.Info("document partially anonymised; please check " + fileOUT);

                if (result.getUnsafeParts().size() > 0)
                {
                    clog.Info("The following parts may leak info:");
                    foreach (Part p in result.getUnsafeParts())
                    {
                        clog.Info(p.getPartName().getName() + ", of type " + p.getClass().getName());
                    }
                }

                // unsafe objects
                clog.Info(result.reportUnsafeObjects());
            }

            clog.Info("\n\n .. end REPORT for " + fileIN + "\n\n");


            // save result to file
            Docx4J.save(pkg, new java.io.File(fileOUT));
            clog.Info("\n\n saved " + fileOUT + "\n\n");
        }
Esempio n. 6
0
        static void Main(string[] args)
        {
            // set up logging
            clog = LoggingConfigurator.configureLogging();
            clog.Info("Hello from Common Logging");

            // create a dir to save the output docx
            string projectDir = System.IO.Directory.GetParent(
                System.IO.Directory.GetParent(
                    Environment.CurrentDirectory.ToString()).ToString()).ToString() + "\\";

            System.IO.Directory.CreateDirectory(projectDir + "OUT");

            // docx4j.properties .. add as URL the dir containing docx4j.properties
            Plutext.PropertiesConfigurator.setDocx4jPropertiesDir(projectDir + @"src\samples\resources\");


            // create WordprocessingMLPackage, representing the docx
            // and add some content to it
            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
            MainDocumentPart        documentPart  = wordMLPackage.getMainDocumentPart();

            populateWithContent(documentPart);

            // Now add a ToC
            TocGenerator tocGenerator = new TocGenerator(wordMLPackage);

            // you should install your own local instance, and point to that in docx4j.properties

            tocGenerator.generateToc(0, " TOC \\o \"1-3\" \\h \\z \\u ", false);

            // Save the docx
            string fileOUT = projectDir + @"OUT\TocSample_Generated.docx";

            Docx4J.save(wordMLPackage, new java.io.File(fileOUT), Docx4J.FLAG_SAVE_ZIP_FILE);


            if (update)
            {
                documentPart.addStyledParagraphOfText("Heading2", "Hello 12");
                fillPageWithContent(documentPart, "Hello 12");
                documentPart.addStyledParagraphOfText("Heading1", "Hello 21");
                fillPageWithContent(documentPart, "Hello 21");
                documentPart.addStyledParagraphOfText("Heading2", "Hello 22");
                fillPageWithContent(documentPart, "Hello 22");
                documentPart.addStyledParagraphOfText("Heading3", "Hello 23");
                fillPageWithContent(documentPart, "Hello 23");

                tocGenerator.updateToc(false);

                fileOUT = projectDir + @"OUT\TocSample_Updated.docx";
                Docx4J.save(wordMLPackage, new java.io.File(fileOUT), Docx4J.FLAG_SAVE_ZIP_FILE);
            }
        }
Esempio n. 7
0
        static void Main(string[] args)
        {
            string projectDir = System.IO.Directory.GetParent(
                System.IO.Directory.GetParent(
                    Environment.CurrentDirectory.ToString()).ToString()).ToString() + "\\";

            // Programmatically configure Common Logging
            // (alternatively, you could do it declaratively in app.config)
            NameValueCollection commonLoggingproperties = new NameValueCollection();

            commonLoggingproperties["showDateTime"] = "false";
            commonLoggingproperties["level"]        = "INFO";
            LogManager.Adapter = new Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter(commonLoggingproperties);


            ILog log = LogManager.GetCurrentClassLogger();

            log.Info("Hello from Common Logging");

            // Necessary, if slf4j-api and slf4j-NetCommonLogging are separate DLLs
            ikvm.runtime.Startup.addBootClassPathAssembly(
                System.Reflection.Assembly.GetAssembly(
                    typeof(org.slf4j.impl.StaticLoggerBinder)));

            // Configure to find docx4j.properties
            // .. add as URL the dir containing docx4j.properties (not the file itself!)
            Plutext.PropertiesConfigurator.setDocx4jPropertiesDir(projectDir + @"src\samples\resources\");


            // Create a docx4j docx
            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();

            org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
            documentPart.addParagraphOfText("Hello world");

            // .. or alternatively, load existing
            //string template = @"C:\Users\jharrop\Documents\tmp-test-docx\HelloWorld.docx";
            //WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
            //        .load(new java.io.File(template));

            Console.WriteLine(documentPart.getJaxbElement().GetType().FullName); // could use logging here and below, but this is better for demo purposes
            Console.WriteLine(documentPart.getXML());

            // Convert to Open XML SDK object
            WordprocessingDocument openXmlSdkObj = Plutext.Docx4NET.WordprocessingDocumentFactory.createWordprocessingDocument(wordMLPackage, true);

            Console.WriteLine(openXmlSdkObj.GetType().FullName);

            // Convert back to docx4j object
            WordprocessingMLPackage wordMLPackage2 = Plutext.Docx4NET.WordprocessingMLPackageFactory.createWordprocessingMLPackage(openXmlSdkObj);

            Console.WriteLine(wordMLPackage2.GetType().FullName);
            Console.WriteLine(wordMLPackage2.getMainDocumentPart().getXML());
        }
Esempio n. 8
0
        static void Main(string[] args)
        {
            // set up logging
            clog = LoggingConfigurator.configureLogging();
            clog.Info("Hello from Common Logging");

            // create a dir to save the output docx
            string projectDir = System.IO.Directory.GetParent(
                System.IO.Directory.GetParent(
                    Environment.CurrentDirectory.ToString()).ToString()).ToString() + "\\";
            string fileOUT = projectDir + @"OUT\HelloWorld.docx";

            System.IO.Directory.CreateDirectory(projectDir + "OUT");


            // docx4j.properties .. add as URL the dir containing docx4j.properties
            Plutext.PropertiesConfigurator.setDocx4jPropertiesDir(projectDir + @"src\samples\resources\");


            // create WordprocessingMLPackage, representing the docx
            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
            MainDocumentPart        mdp           = wordMLPackage.getMainDocumentPart();


            // add content
            mdp.addParagraphOfText("hello world");  // a convenience method

            // the more generic pattern is:

            org.docx4j.wml.ObjectFactory wmlObjectFactory = org.docx4j.jaxb.Context.getWmlObjectFactory();
            P p = wmlObjectFactory.createP();     // but you can just do = new P();

            mdp.getContent().add(p);
            // Create object for r
            R r = wmlObjectFactory.createR();

            p.getContent().add(r);

            // Create object for t (wrapped in JAXBElement)
            Text        text        = wmlObjectFactory.createText();
            JAXBElement textWrapped = wmlObjectFactory.createRT(text);     // instead of JAXBElement<org.docx4j.wml.Text>

            // here Text text = new Text() would actually have been fine.

            text.setValue("hello world 2");
            r.getContent().add(textWrapped);


            // save to file
            Docx4J.save(wordMLPackage, new java.io.File(fileOUT), Docx4J.FLAG_SAVE_ZIP_FILE);
        }
Esempio n. 9
0
        static void Main(string[] args)
        {
            string projectDir = System.IO.Directory.GetParent(
                System.IO.Directory.GetParent(
                    Environment.CurrentDirectory.ToString()).ToString()).ToString() + "\\";

            string fileIN = projectDir + @"src\samples\resources\sample-docx.docx";

            string fileOUT      = projectDir + @"OUT\sample-docx2.html";
            string imageDirPath = projectDir + @"OUT\sample-docx2_files";

            System.IO.Directory.CreateDirectory(projectDir + "OUT");
            System.IO.Directory.CreateDirectory(imageDirPath);

            string imageTargetUri = imageDirPath;

            // Programmatically configure Common Logging
            // (alternatively, you could do it declaratively in app.config)
            NameValueCollection commonLoggingproperties = new NameValueCollection();

            commonLoggingproperties["showDateTime"] = "false";
            commonLoggingproperties["level"]        = "INFO";
            LogManager.Adapter = new Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter(commonLoggingproperties);


            ILog log = LogManager.GetCurrentClassLogger();

            log.Info("Hello from Common Logging");

            // Necessary, if slf4j-api and slf4j-NetCommonLogging are separate DLLs
            ikvm.runtime.Startup.addBootClassPathAssembly(
                System.Reflection.Assembly.GetAssembly(
                    typeof(org.slf4j.impl.StaticLoggerBinder)));

            // Configure to find docx4j.properties
            // .. add as URL the dir containing docx4j.properties (not the file itself!)
            Plutext.PropertiesConfigurator.setDocx4jPropertiesDir(projectDir + @"src\samples\resources\");

            // OK, do it..
            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
                                                    .load(new java.io.File(fileIN));

            java.io.FileOutputStream fos = new java.io.FileOutputStream(new java.io.File(fileOUT));

            org.docx4j.Docx4J.toHTML(wordMLPackage, imageDirPath, imageTargetUri, fos);

            fos.close();

            Console.WriteLine("done!");
        }
Esempio n. 10
0
        static void Main(string[] args)
        {
            // set up logging
            clog = LoggingConfigurator.configureLogging();
            clog.Info("Hello from Common Logging");

            string projectDir = System.IO.Directory.GetParent(
                System.IO.Directory.GetParent(
                    Environment.CurrentDirectory.ToString()).ToString()).ToString() + "\\";

            // the docx 'template'
            String input_DOCX = projectDir + @"src\samples\resources\ContentControlBind\binding-simple.docx";

            // the instance data
            String input_XML = projectDir + @"src\samples\resources\ContentControlBind\binding-simple-data.xml";

            // resulting docx
            String OUTPUT_DOCX = projectDir + @"OUT_ContentControlsMergeXML.docx";

            // Configure to find docx4j.properties
            // .. add as URL the dir containing docx4j.properties (not the file itself!)
            Plutext.PropertiesConfigurator.setDocx4jPropertiesDir(projectDir + @"src\samples\resources\");

            // Load input_template.docx
            WordprocessingMLPackage wordMLPackage = org.docx4j.Docx4J.load(new java.io.File(input_DOCX));

            // Open the xml stream
            java.io.FileInputStream xmlStream = new java.io.FileInputStream(new java.io.File(input_XML));

            // Do the binding:
            // FLAG_NONE means that all the steps of the binding will be done,
            // otherwise you could pass a combination of the following flags:
            // FLAG_BIND_INSERT_XML: inject the passed XML into the document
            // FLAG_BIND_BIND_XML: bind the document and the xml (including any OpenDope handling)
            // FLAG_BIND_REMOVE_SDT: remove the content controls from the document (only the content remains)
            // FLAG_BIND_REMOVE_XML: remove the custom xml parts from the document

            //Docx4J.bind(wordMLPackage, xmlStream, Docx4J.FLAG_NONE);
            //If a document doesn't include the Opendope definitions, eg. the XPathPart,
            //then the only thing you can do is insert the xml
            //the example document binding-simple.docx doesn't have an XPathPart....
            Docx4J.bind(wordMLPackage, xmlStream, Docx4J.FLAG_BIND_INSERT_XML & Docx4J.FLAG_BIND_BIND_XML);

            //Save the document
            Docx4J.save(wordMLPackage, new java.io.File(OUTPUT_DOCX), Docx4J.FLAG_NONE);
            clog.Info("Saved: " + OUTPUT_DOCX);
        }
Esempio n. 11
0
        static void Main(string[] args)
        {
            // set up logging
            clog = LoggingConfigurator.configureLogging();
            clog.Info("Hello from Common Logging");

            string projectDir = System.IO.Directory.GetParent(
                System.IO.Directory.GetParent(
                Environment.CurrentDirectory.ToString()).ToString()).ToString() + "\\";

            string fileIN = projectDir + @"src\samples\resources\sample-docx.docx";

            string fileOUT = projectDir + @"OUT\sample-docx2.html";
            string imageDirPath = projectDir + @"OUT\sample-docx2_files";

            System.IO.Directory.CreateDirectory(projectDir + "OUT");
            System.IO.Directory.CreateDirectory(imageDirPath);

            string imageTargetUri = imageDirPath;

            // Configure to find docx4j.properties
            // .. add as URL the dir containing docx4j.properties (not the file itself!)
            Plutext.PropertiesConfigurator.setDocx4jPropertiesDir(projectDir +@"src\samples\resources\");

            // OK, do it..
            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
                    .load(new java.io.File(fileIN));

            java.io.FileOutputStream fos = new java.io.FileOutputStream(new java.io.File(fileOUT));

            org.docx4j.Docx4J.toHTML(wordMLPackage, imageDirPath, imageTargetUri, fos);

            fos.close();

            Console.WriteLine("done!");

        }
Esempio n. 12
0
        static void Main(string[] args)
        {
            // set up logging
            clog = LoggingConfigurator.configureLogging();
            clog.Info("Hello from Common Logging");

            bool mergedOutput = true;

            string projectDir = System.IO.Directory.GetParent(
                System.IO.Directory.GetParent(
                    Environment.CurrentDirectory.ToString()).ToString()).ToString() + "\\";

            string saveToPathPrefix = projectDir + @"OUT_MailMergeField";

            // Configure to find docx4j.properties
            // .. add as URL the dir containing docx4j.properties (not the file itself!)
            Plutext.PropertiesConfigurator.setDocx4jPropertiesDir(projectDir + @"src\samples\resources\");


            // Create a docx4j docx
            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();

            org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
            documentPart.addObject(addParagraphWithMergeField("Hallo, MERGEFORMAT: ", " MERGEFIELD  kundenname  \\* MERGEFORMAT ", "«Kundenname»"));
            documentPart.addObject(addParagraphWithMergeField("Hallo, lower: ", " MERGEFIELD  kundenname  \\* Lower ", "«Kundenname»"));
            documentPart.addObject(addParagraphWithMergeField("Hallo, firstcap: ", " MERGEFIELD  kundenname  \\* FirstCap MERGEFORMAT ", "«Kundenname»"));
            documentPart.addObject(addParagraphWithMergeField("Hallo, random case: ", " MERGEFIELD  KunDenName  \\* MERGEFORMAT ", "«Kundenname»"));
            documentPart.addObject(addParagraphWithMergeField("Hallo, all caps: ", " MERGEFIELD  KUNDENNAME  \\* Upper MERGEFORMAT ", "«Kundenname»"));
            // " MERGEFIELD  yourdate \@ &quot;dddd, MMMM dd, yyyy&quot; "
            //documentPart.addObject(addParagraphWithMergeField("Date example", " MERGEFIELD  yourdate \\@ 'dddd, MMMM dd, yyyy' ", "«Kundenname»")); // FIXME .. doesn't work via .NET.  Why?
            documentPart.addObject(addParagraphWithMergeField("Number example: ", " MERGEFIELD  yournumber \\# $#,###,###  ", "«Kundenname»"));

            // .. or alternatively, load existing
            //string template = @"C:\Users\jharrop\Documents\tmp-test-docx\HelloWorld.docx";
            //WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
            //        .load(new java.io.File(template));

            //Console.WriteLine(documentPart.getXML());

            java.util.List data = new java.util.ArrayList();
            // TODO: make more .NET friendly

            // Instance 1
            java.util.Map map = new java.util.HashMap();
            map.put(new DataFieldName("KundenNAme"), "Daffy duck");
            map.put(new DataFieldName("Kundenname"), "Plutext");
            map.put(new DataFieldName("Kundenstrasse"), "Bourke Street");
            // To get dates right, make sure you have docx4j property docx4j.Fields.Dates.DateFormatInferencer.USA
            // set to true or false as appropriate.  It defaults to non-US.
            map.put(new DataFieldName("yourdate"), "15/4/2013");
            map.put(new DataFieldName("yournumber"), "2456800");
            data.add(map);

            // Instance 2
            map = new java.util.HashMap();
            map.put(new DataFieldName("Kundenname"), "Jason");
            map.put(new DataFieldName("Kundenstrasse"), "Collins Street");
            map.put(new DataFieldName("yourdate"), "12/10/2013");
            map.put(new DataFieldName("yournumber"), "1234800");
            data.add(map);


            if (mergedOutput)
            {
                /*
                 * This is a "poor man's" merge, which generates the mail merge
                 * results as a single docx, and just hopes for the best.
                 * Images and hyperlinks should be ok. But numbering
                 * will continue, as will footnotes/endnotes.
                 *
                 * If your resulting documents aren't opening in Word, then
                 * you probably need MergeDocx to perform the merge.
                 */

                // How to treat the MERGEFIELD, in the output?
                org.docx4j.model.fields.merge.MailMerger.setMERGEFIELDInOutput(org.docx4j.model.fields.merge.MailMerger.OutputField.KEEP_MERGEFIELD);

//			log.Debug(XmlUtils.marshaltoString(wordMLPackage.getMainDocumentPart().getJaxbElement(), true, true));

                WordprocessingMLPackage output = org.docx4j.model.fields.merge.MailMerger.getConsolidatedResultCrude(wordMLPackage, data, true);

//			log.Info(XmlUtils.marshaltoString(output.getMainDocumentPart().getJaxbElement(), true, true));

                SaveFromJavaUtils.save(output, saveToPathPrefix + ".docx");
            }
            else
            {
                // Need to keep thane MERGEFIELDs. If you don't, you'd have to clone the docx, and perform the
                // merge on the clone.  For how to clone, see the MailMerger code, method getConsolidatedResultCrude
                org.docx4j.model.fields.merge.MailMerger.setMERGEFIELDInOutput(org.docx4j.model.fields.merge.MailMerger.OutputField.KEEP_MERGEFIELD);


                for (int i = 0; i < data.size(); i++)
                {
                    java.util.Map thismap = (java.util.Map)data.get(i);
                    org.docx4j.model.fields.merge.MailMerger.performMerge(wordMLPackage, thismap, true);
                    SaveFromJavaUtils.save(wordMLPackage, saveToPathPrefix + "_" + i + ".docx");
                }
            }
            clog.Info("Done! Saved to " + saveToPathPrefix);
        }
 /// <summary>
 /// Create an OpenXML SDK WordprocessingDocument object
 /// from a docx4j WordprocessingMLPackage
 /// </summary>
 /// <param name="wordPkg"></param>
 /// <param name="isEditable"></param>
 /// <returns></returns>
 public static WordprocessingDocument createWordprocessingDocument(
     WordprocessingMLPackage wordPkg,
     bool isEditable)
 {
     return(createWordprocessingDocument(wordPkg, isEditable, new OpenSettings()));
 }
 public static void save(WordprocessingMLPackage wordPkg, string path)
 {
     SaveToZipFile saver = new SaveToZipFile(wordPkg);
     saver.save(path);
 }
 /// <summary>
 /// Create an OpenXML SDK WordprocessingDocument object
 /// from a docx4j WordprocessingMLPackage
 /// </summary>
 /// <param name="wordPkg"></param>
 /// <param name="isEditable"></param>
 /// <returns></returns>
 public static WordprocessingDocument createWordprocessingDocument(
     WordprocessingMLPackage wordPkg,
     bool isEditable)
 {
     return createWordprocessingDocument(wordPkg, isEditable, new OpenSettings());
 }
 /// <summary>
 /// Create a docx4j WordprocessingMLPackage from the file at path
 /// </summary>
 /// <param name="path"></param>
 /// <returns></returns>
 /// <exception cref="Docx4JException">something went wrong</exception>
 public static WordprocessingMLPackage createWordprocessingMLPackage(string path)
 {
     return(WordprocessingMLPackage
            .load(new java.io.File(path)));
 }
Esempio n. 17
0
        static void Main(string[] args)
        {
            string projectDir = System.IO.Directory.GetParent(
                System.IO.Directory.GetParent(
                    Environment.CurrentDirectory.ToString()).ToString()).ToString() + "\\";

            // the docx 'template'
            String input_DOCX = projectDir + @"src\samples\resources\ContentControlBind\binding-simple.docx";

            // the instance data
            String input_XML = projectDir + @"src\samples\resources\ContentControlBind\binding-simple-data.xml";

            // resulting docx
            String OUTPUT_DOCX = projectDir + @"OUT_ContentControlsMergeXML.docx";


            // Programmatically configure Common Logging
            // (alternatively, you could do it declaratively in app.config)
            NameValueCollection commonLoggingproperties = new NameValueCollection();

            commonLoggingproperties["showDateTime"] = "false";
            commonLoggingproperties["level"]        = "INFO";
            LogManager.Adapter = new Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter(commonLoggingproperties);


            ILog log = LogManager.GetCurrentClassLogger();

            log.Info("Hello from Common Logging");

            // Necessary, if slf4j-api and slf4j-NetCommonLogging are separate DLLs
            ikvm.runtime.Startup.addBootClassPathAssembly(
                System.Reflection.Assembly.GetAssembly(
                    typeof(org.slf4j.impl.StaticLoggerBinder)));

            // Configure to find docx4j.properties
            // .. add as URL the dir containing docx4j.properties (not the file itself!)
            Plutext.PropertiesConfigurator.setDocx4jPropertiesDir(projectDir + @"src\samples\resources\");

            // Load input_template.docx
            WordprocessingMLPackage wordMLPackage = org.docx4j.Docx4J.load(new java.io.File(input_DOCX));

            // Open the xml stream
            java.io.FileInputStream xmlStream = new java.io.FileInputStream(new java.io.File(input_XML));

            // Do the binding:
            // FLAG_NONE means that all the steps of the binding will be done,
            // otherwise you could pass a combination of the following flags:
            // FLAG_BIND_INSERT_XML: inject the passed XML into the document
            // FLAG_BIND_BIND_XML: bind the document and the xml (including any OpenDope handling)
            // FLAG_BIND_REMOVE_SDT: remove the content controls from the document (only the content remains)
            // FLAG_BIND_REMOVE_XML: remove the custom xml parts from the document

            //Docx4J.bind(wordMLPackage, xmlStream, Docx4J.FLAG_NONE);
            //If a document doesn't include the Opendope definitions, eg. the XPathPart,
            //then the only thing you can do is insert the xml
            //the example document binding-simple.docx doesn't have an XPathPart....
            Docx4J.bind(wordMLPackage, xmlStream, Docx4J.FLAG_BIND_INSERT_XML & Docx4J.FLAG_BIND_BIND_XML);

            //Save the document
            Docx4J.save(wordMLPackage, new java.io.File(OUTPUT_DOCX), Docx4J.FLAG_NONE);
            log.Info("Saved: " + OUTPUT_DOCX);
        }
 /// <summary>
 /// Create a docx4j WordprocessingMLPackage from an IO stream
 /// </summary>
 /// <param name="path"></param>
 /// <returns></returns>
 /// <exception cref="Docx4JException">something went wrong</exception>
 public static WordprocessingMLPackage createWordprocessingMLPackage(Stream stream)
 {
     return(WordprocessingMLPackage
            .load(new ikvm.io.InputStreamWrapper(stream)));
 }
        public static void save(WordprocessingMLPackage wordPkg, string path)
        {
            SaveToZipFile saver = new SaveToZipFile(wordPkg);

            saver.save(path);
        }
Esempio n. 20
0
        static void Main(string[] args)
        {
            ILog log = configureLogging();

            log.Info("Hello from Common Logging");

            string projectDir = System.IO.Directory.GetParent(
                System.IO.Directory.GetParent(
                    Environment.CurrentDirectory.ToString()).ToString()).ToString() + "\\";

            // resulting docx
            String OUTPUT_DOCX = projectDir + @"OUT_XHTMLFragment.docx";


            // Programmatically configure Common Logging
            // (alternatively, you could do it declaratively in app.config)
            NameValueCollection commonLoggingproperties = new NameValueCollection();

            commonLoggingproperties["showDateTime"] = "false";
            commonLoggingproperties["level"]        = "INFO";
            LogManager.Adapter = new Common.Logging.Simple.ConsoleOutLoggerFactoryAdapter(commonLoggingproperties);

            ikvm.runtime.Startup.addBootClassPathAssembly(
                System.Reflection.Assembly.GetAssembly(
                    typeof([email protected])));

            // Configure to find docx4j.properties
            // .. add as URL the dir containing docx4j.properties (not the file itself!)
            // and docx4j-ImportXHTML.properties (assumed to be in the same dir)
            Plutext.PropertiesConfigurator.setDocx4jPropertiesDir(projectDir + @"src\samples\resources\");
            // Workaround  to prevent ClassNotFoundException,
            // at IKVM.NativeCode.java.lang.Class.forName0
            // caused by Class.forName("org.docx4j.convert.in.xhtml.FSColorToHexString")
            // in docx4j code.
            ikvm.runtime.Startup.addBootClassPathAssembly(
                System.Reflection.Assembly.GetAssembly(
                    typeof([email protected])));

            String xhtml = "<ul>" +
                           "<li>Outer 1 </li>" +
                           "<li>Outer 2 </li>" +
                           "<ul>" +
                           "<li>Inner 1 </li>" +
                           "<li>Inner 2 </li>" +
                           "</ul>" +
                           "<li>Outer 3 </li>" +
                           "</ul>";

            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();

            XHTMLImporterImpl XHTMLImporter = new XHTMLImporterImpl(wordMLPackage);

            wordMLPackage.getMainDocumentPart().getContent().addAll(
                XHTMLImporter.convert(xhtml, null));

            Console.WriteLine(
                org.docx4j.XmlUtils.marshaltoString(wordMLPackage.getMainDocumentPart().getJaxbElement(), true, true));

            //Save the document
            Docx4J.save(wordMLPackage, new java.io.File(OUTPUT_DOCX), Docx4J.FLAG_NONE);
            log.Info("Saved: " + OUTPUT_DOCX);
        }