Search in sources :

Example 1 with WordprocessingMLPackage

use of org.docx4j.openpackaging.packages.WordprocessingMLPackage in project Java-Tutorial by gpcodervn.

the class ReportFromTemplate method main.

public static void main(String[] args) {
    final String XPATH_TO_SELECT_TEXT_NODES = "//w:t";
    String fileName = "";
    try {
        // Populate the Strings that will replace the template text
        Map<String, String> map = new HashMap<String, String>();
        map.put("Project", "BP Mount");
        map.put("Date", "21-Mar-2011");
        // C:\\test\\template1.docx is the template file
        WordprocessingMLPackage template = WordprocessingMLPackage.load(new File("resources/Template1.docx"));
        Parts parts = template.getParts();
        HashMap<PartName, Part> partsMap = parts.getParts();
        PartName partName = null;
        Part part = null;
        Set<PartName> set = partsMap.keySet();
        for (Iterator<PartName> iterator = set.iterator(); iterator.hasNext(); ) {
            PartName name = (PartName) iterator.next();
            if (name.getName().equalsIgnoreCase("/word/media/image1.png")) {
                part = partsMap.get(name);
                partName = name;
            }
        }
        if (part != null && partName != null) {
            part = partsMap.get(partName);
            BinaryPart binaryPart = (BinaryPart) part;
            binaryPart.setBinaryData(fileToBytes(fileToReplace));
        }
        List<Object> texts = template.getMainDocumentPart().getJAXBNodesViaXPath(XPATH_TO_SELECT_TEXT_NODES, true);
        for (Object obj : texts) {
            Text text = (Text) ((JAXBElement) obj).getValue();
            String textValue = text.getValue();
            for (Object key : map.keySet()) {
                // textValue = textValue.replaceAll("\\$\\{" + key + "\\}", (String) map.get(key));
                textValue = textValue.trim().replace("${" + key + "}", (String) map.get(key));
            }
            text.setValue(textValue);
        }
        /*
			 * Add the other contents here
			 */
        template.save(new File("output/ReportFromTemplate.docx"));
        System.out.println("Done");
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println("Errors");
    }
}
Also used : BinaryPart(org.docx4j.openpackaging.parts.WordprocessingML.BinaryPart) HashMap(java.util.HashMap) Text(org.docx4j.wml.Text) WordprocessingMLPackage(org.docx4j.openpackaging.packages.WordprocessingMLPackage) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) PartName(org.docx4j.openpackaging.parts.PartName) Parts(org.docx4j.openpackaging.parts.Parts) Part(org.docx4j.openpackaging.parts.Part) BinaryPart(org.docx4j.openpackaging.parts.WordprocessingML.BinaryPart) File(java.io.File)

Example 2 with WordprocessingMLPackage

use of org.docx4j.openpackaging.packages.WordprocessingMLPackage in project Java-Tutorial by gpcodervn.

the class Write_Image method main.

public static void main(String[] args) throws Exception {
    WordprocessingMLPackage wordPackage = WordprocessingMLPackage.createPackage();
    MainDocumentPart mainDocumentPart = wordPackage.getMainDocumentPart();
    mainDocumentPart.addStyledParagraphOfText("Title", "Hello World!");
    mainDocumentPart.addParagraphOfText("Welcome To Baeldung");
    File image = new File("resources/image.png");
    byte[] fileContent = Files.readAllBytes(image.toPath());
    BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordPackage, fileContent);
    Inline inline = imagePart.createImageInline("Baeldung Image (filename hint)", "Alt Text", 1, 2, false);
    P Imageparagraph = addImageToParagraph(inline);
    mainDocumentPart.getContent().add(Imageparagraph);
    File exportFile = new File("output/welcome3.docx");
    wordPackage.save(exportFile);
    System.out.println("Done!");
}
Also used : P(org.docx4j.wml.P) MainDocumentPart(org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart) Inline(org.docx4j.dml.wordprocessingDrawing.Inline) WordprocessingMLPackage(org.docx4j.openpackaging.packages.WordprocessingMLPackage) BinaryPartAbstractImage(org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage) File(java.io.File)

Example 3 with WordprocessingMLPackage

use of org.docx4j.openpackaging.packages.WordprocessingMLPackage in project Java-Tutorial by gpcodervn.

the class ContentControlBindingExtensions method reverter.

public static void reverter(String inputfilepath, String instancePath) throws Docx4JException {
    WordprocessingMLPackage instancePkg = WordprocessingMLPackage.load(new java.io.File(instancePath));
    OpenDoPEReverter reverter = new OpenDoPEReverter(WordprocessingMLPackage.load(new java.io.File(inputfilepath)), instancePkg);
    System.out.println("reverted? " + reverter.revert());
    SaveToZipFile saver = new SaveToZipFile(instancePkg);
    saver.save(filepathprefix + "_5_reverted.docx");
    System.out.println("Saved: " + filepathprefix + "_5_reverted.docx");
}
Also used : SaveToZipFile(org.docx4j.openpackaging.io.SaveToZipFile) WordprocessingMLPackage(org.docx4j.openpackaging.packages.WordprocessingMLPackage) File(java.io.File) SaveToZipFile(org.docx4j.openpackaging.io.SaveToZipFile) File(java.io.File) OpenDoPEReverter(org.docx4j.model.datastorage.OpenDoPEReverter)

Example 4 with WordprocessingMLPackage

use of org.docx4j.openpackaging.packages.WordprocessingMLPackage in project Java-Tutorial by gpcodervn.

the class ContentControlBindingExtensions method main.

/**
 * @param args
 */
public static void main(String[] args) throws Exception {
    String inputfilepath = System.getProperty("user.dir") + "/sample-docs/word/databinding/invoice.docx";
    String data = System.getProperty("user.dir") + "/sample-docs/word/databinding/invoice-data.xml";
    WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));
    filepathprefix = inputfilepath.substring(0, inputfilepath.lastIndexOf("."));
    System.out.println(filepathprefix);
    StringBuilder timingSummary = new StringBuilder();
    // Find custom xml item id and inject data_file.xml
    long startTime = System.currentTimeMillis();
    CustomXmlDataStoragePart customXmlDataStoragePart = CustomXmlDataStoragePartSelector.getCustomXmlDataStoragePart(wordMLPackage);
    if (customXmlDataStoragePart == null) {
        throw new RuntimeException("no xml");
    }
    customXmlDataStoragePart.getData().setDocument(new FileInputStream(new File(data)));
    long endTime = System.currentTimeMillis();
    timingSummary.append("\nmerge data: " + (endTime - startTime));
    System.out.println("data merged");
    SaveToZipFile saver = new SaveToZipFile(wordMLPackage);
    saver.save(new File(System.getProperty("user.dir") + "/OUT_injected.docx"));
    // Process conditionals and repeats
    startTime = System.currentTimeMillis();
    OpenDoPEHandler odh = new OpenDoPEHandler(wordMLPackage);
    odh.preprocess();
    endTime = System.currentTimeMillis();
    timingSummary.append("OpenDoPEHandler: " + (endTime - startTime));
    // System.out.println(
    // XmlUtils.marshaltoString(wordMLPackage.getMainDocumentPart().getJaxbElement(), true, true)
    // );
    saver.save(filepathprefix + "_1_preprocessed.docx");
    System.out.println("Saved: " + filepathprefix + "_1_preprocessed.docx");
    startTime = System.currentTimeMillis();
    OpenDoPEIntegrity odi = new OpenDoPEIntegrity();
    odi.process(wordMLPackage);
    endTime = System.currentTimeMillis();
    timingSummary.append("\nOpenDoPEIntegrity: " + (endTime - startTime));
    // System.out.println(
    // XmlUtils.marshaltoString(wordMLPackage.getMainDocumentPart().getJaxbElement(), true, true)
    // );
    saver = new SaveToZipFile(wordMLPackage);
    saver.save(filepathprefix + "_2_integrity.docx");
    System.out.println("Saved: " + filepathprefix + "_2_integrity.docx");
    // Apply the bindings
    saver = new SaveToZipFile(wordMLPackage);
    BindingHandler.setHyperlinkStyle("Hyperlink");
    startTime = System.currentTimeMillis();
    // AtomicInteger bookmarkId = odh.getNextBookmarkId();
    AtomicInteger bookmarkId = new AtomicInteger();
    BindingHandler bh = new BindingHandler(wordMLPackage);
    bh.setStartingIdForNewBookmarks(bookmarkId);
    bh.applyBindings(wordMLPackage.getMainDocumentPart());
    endTime = System.currentTimeMillis();
    timingSummary.append("\nBindingHandler.applyBindings: " + (endTime - startTime));
    // System.out.println(
    // XmlUtils.marshaltoString(wordMLPackage.getMainDocumentPart().getJaxbElement(), true, true)
    // );
    saver.save(filepathprefix + "_3_bound.docx");
    System.out.println("Saved: " + filepathprefix + "_3_bound.docx");
    // Either demonstrate reverter, or stripping of controls;
    // you can't do both. So comment out one or the other.
    // reverter(inputfilepath, filepathprefix + "_bound.docx");
    // 
    // Strip content controls
    startTime = System.currentTimeMillis();
    RemovalHandler rh = new RemovalHandler();
    rh.removeSDTs(wordMLPackage, Quantifier.ALL);
    endTime = System.currentTimeMillis();
    timingSummary.append("\nRemovalHandler: " + (endTime - startTime));
    saver.save(filepathprefix + "_4_stripped.docx");
    System.out.println("Saved: " + filepathprefix + "_4_stripped.docx");
    System.out.println(timingSummary);
}
Also used : OpenDoPEIntegrity(org.docx4j.model.datastorage.OpenDoPEIntegrity) SaveToZipFile(org.docx4j.openpackaging.io.SaveToZipFile) RemovalHandler(org.docx4j.model.datastorage.RemovalHandler) WordprocessingMLPackage(org.docx4j.openpackaging.packages.WordprocessingMLPackage) File(java.io.File) FileInputStream(java.io.FileInputStream) OpenDoPEHandler(org.docx4j.model.datastorage.OpenDoPEHandler) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CustomXmlDataStoragePart(org.docx4j.openpackaging.parts.CustomXmlDataStoragePart) File(java.io.File) SaveToZipFile(org.docx4j.openpackaging.io.SaveToZipFile) BindingHandler(org.docx4j.model.datastorage.BindingHandler)

Example 5 with WordprocessingMLPackage

use of org.docx4j.openpackaging.packages.WordprocessingMLPackage in project Java-Tutorial by gpcodervn.

the class ContentControlsMergeXML method main.

public static void main(String[] args) throws Exception {
    // the docx 'template'
    String input_DOCX = System.getProperty("user.dir") + "/sample-docs/word/databinding/binding-simple.docx";
    // the instance data
    String input_XML = System.getProperty("user.dir") + "/sample-docs/word/databinding/binding-simple-data.xml";
    // resulting docx
    String OUTPUT_DOCX = System.getProperty("user.dir") + "/OUT_ContentControlsMergeXML.docx";
    // Load input_template.docx
    WordprocessingMLPackage wordMLPackage = Docx4J.load(new File(input_DOCX));
    // Open the xml stream
    FileInputStream xmlStream = new FileInputStream(new 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_NONE);
    // Save the document
    Docx4J.save(wordMLPackage, new File(OUTPUT_DOCX), Docx4J.FLAG_NONE);
    System.out.println("Saved: " + OUTPUT_DOCX);
}
Also used : WordprocessingMLPackage(org.docx4j.openpackaging.packages.WordprocessingMLPackage) File(java.io.File) FileInputStream(java.io.FileInputStream)

Aggregations

WordprocessingMLPackage (org.docx4j.openpackaging.packages.WordprocessingMLPackage)67 File (java.io.File)50 MainDocumentPart (org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart)22 Docx4JException (org.docx4j.openpackaging.exceptions.Docx4JException)11 XHTMLImporterImpl (org.docx4j.convert.in.xhtml.XHTMLImporterImpl)9 OutputStream (java.io.OutputStream)8 ObjectFactory (org.docx4j.wml.ObjectFactory)8 Test (org.junit.Test)8 P (org.docx4j.wml.P)7 Text (org.docx4j.wml.Text)7 FileOutputStream (java.io.FileOutputStream)6 FileInputStream (java.io.FileInputStream)5 Body (org.docx4j.wml.Body)5 Tbl (org.docx4j.wml.Tbl)5 TraversalUtil (org.docx4j.TraversalUtil)4 NumberingDefinitionsPart (org.docx4j.openpackaging.parts.WordprocessingML.NumberingDefinitionsPart)4 R (org.docx4j.wml.R)4 RPr (org.docx4j.wml.RPr)4 SpecExample (com.vladsch.flexmark.spec.SpecExample)3 IOException (java.io.IOException)3