开发者

how to append data in docx file using docx4j

Please tell me how to append data in docx file using java and docx4j.

What I'm doing is, I am using a template in docx format in which some field are dilled by java at run time,

My problem is for every group of data it creates a new file and i just want to append the new file into 1 file. and this is not done using java streams

String outputfilepath = "e:\\Practice/DOC/output/generatedLatterOUTPUT.docx";
String outputfilepath1 = "e:\\Practice/DOC/output/generatedLatterOUTPUT1.docx";
WordprocessingMLPackage wordMLPackage;

public void templetsubtitution(String name, String age, String gender, Document document)
        throws Exception {

    // input file name
    String inputfilepath = "e:\\Practice/DOC/profile.docx";
    // out put file name

    // id of Xml file
    String itemId1 = "{A5D3A327-5613-4B97-98A9-FF42A2BA0F74}".toLowerCase();
    String itemId2 = "{A5D3A327-5613-4B97-98A9-FF42A2BA0F74}".toLowerCase();
    String itemId3 = "{A5D3A327-5613-4B97-98A9-FF42A2BA0F74}".toLowerCase();
    // Load the Package

    if (inputfilepath.endsWith(".xml")) {

        JAXBContext jc = Context.jcXmlPackage;
        Unmarshaller u = jc.createUnmarshaller();
        u.setEventHandler(new org.docx4j.jaxb.JaxbValidationEventHandler());

        org.docx4j.xmlPackage.Package wmlPackageEl = (org.docx4j.xmlPackage.Package) ((JAXBElement) u
                .unmarshal(new javax.xml.transform.stream.StreamSource(
                        new FileInputStream(inputfilepath)))).getValue();

        org.docx4j.convert.in.FlatOpcXmlImporter xmlPackage = new org.docx4j.convert.in.FlatOpcXmlImporter(
                wmlPackageEl);

        wordMLPackage = (WordprocessingMLPackage) xmlPackage.get();

    } else {
        wordMLPackage = WordprocessingMLPackage
                .load(new File(inputfilepath));
    }

    CustomXmlDataStoragePart customXmlDataStoragePart = wordMLPackage
            .getCustomXmlDataStorageParts().get(itemId1);
    // Get the contents
    CustomXmlDataStorage customXmlDataStorage = customXmlDataStoragePart
            .getData();
    // Change its contents
    ((CustomXmlDataStorageImpl) customXmlDataStorage).setNodeValueAtXPath(
            "/ns0:orderForm[1]/ns0:record[1]/ns0:name[1]", name,
            "xmlns:ns0='EasyForm'");

    customXmlDataStoragePart = wordMLPackage.getCustomXmlDataStorageParts()
            .get(itemId2);
    // Get the contents
    customXmlDataStorage = customXmlDataStoragePart.getData();
    // Change its contents
    ((CustomXmlDataStorageImpl) customXmlDataStorage).setNodeValueAtXPath(
            "/ns0:orderForm[1]/ns0:record[1]/ns0:age[1]", age,
            "xmlns:ns0='EasyForm'");

    customXmlDataStoragePart = wordMLPackage.getCustomXmlDataStorageParts()
            .get(itemId3);
    // Get the contents
    customXmlDataStorage = customXmlDataStoragePart.getData();
    // Change its contents
    ((CustomXmlDataStorageImpl) customXmlDataStorage).setNodeValueAtXPath(
            "/ns0:orderForm[1]/ns0:record[1]/ns0:gender[1]", gender,
            "xmlns:ns0='EasyForm'");

    // Apply the bindings
    BindingHandler.applyBindings(wordMLPackage.getMainDocumentPart());
    File f = new File(outputfilepath);
    wordMLPackage.save(f);
    FileInputStream fis = new FileInputStream(f);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];
    try {
        for (int readNum; (readNum = fis.read(buf)) != -1;) {
            bos.write(buf, 0, readNum);
        }
        // System.out.println( buf.length);

    } catch (IOException ex) {
    }
    byte[] bytes = bos.toByteArray();
    FileOutputStream file = new FileOutputStream(outputfilepath1, true);
    DataOutputStream out = new DataOutputStream(file);
    out.write开发者_运维知识库(bytes);
    out.flush();
    out.close();

    System.out.println("..done");
}

public static void main(String[] args) {
  utility u = new utility();
  u.templetsubtitution("aditya",24,mohan);
}

thanks in advance


If I understand you correctly, you're essentially talking about merging documents. There are two very simple approaches that you can use, and their effectiveness really depends on the structure and onward use of your data:

  1. PhilippeAuriach describes one approach in his answer, which entails appending all components within a MaindocumentPart instance to another. In terms of the final docx file, this means the content that appears in document.xml -- it won't take into account headers and footers ( for example), but that may be fine for you.

  2. You can insert multiple documents into a single docx file by inserting them as AltChunk elements (see the docx4j documentation). This will bring everything from one Word file into another, headers and all. The downside of this is that your final document won't be a proper flowing Word file until you open it and save it in MS Word itself (the imported components remain as standalone files within the docx bundle). This will cause you issues if you want to generated 'merged' files and then do something with them like render PDFs -- the merged content will simply be ignored.

The more complete (and complex) approach is to perform a "deep merge". This updates and maintains all references held within a document. Imported content becomes part of the main "flow" of the document (i.e. it is not stored as separate references), so the end result is a properly-merged file which can be rendered to PDF or whatever.

The downside to this is you need a good knowledge of docx structure and the API, and you will be writing a fair amount of code (I would recommend buying a license to Plutext's MergeDocx instead).


I had to deal with similar things, and here is what I did (probably not the most efficient, but working) :

  • create a finalDoc loading the template, and emptying it (so you have the styles in this doc)
  • for each data row, create a new doc loading the template, then replace your fields with your values
  • use the function below to append the doc filled with the datas to the finalDoc :

    public static void append(WordprocessingMLPackage docDest, WordprocessingMLPackage docSource) {
    List<Object> objects = docSource.getMainDocumentPart().getContent();
        for(Object o : objects){
            docDest.getMainDocumentPart().getContent().add(o);
        }
    }
    

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜