Ejemplo n.º 1
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);
        }