Page 1 of 1

replace text with paragraph

PostPosted: Tue Nov 08, 2011 5:40 am
by fachhoch
I want to modify my word by replacing place holders with actual text , in my case I created a placeholder and would like to replace this with a paragraph , I tried the example of replacing text , but can I replace a simple text with whole paragraph ?

Code: Select all
         @Override
         public List<Object> apply(Object object) {
            if (object instanceof org.docx4j.wml.Text){
               Text  wText=(org.docx4j.wml.Text) object;
               if(wText.getValue().equals("formattedAuditNumber")){
                  wText.setValue("A-123-456-9876");
               }
            }
            return null;
         }




I tried playing with OpenMainDocumentAndTraverse.java, this is what I tried and it worked , now I want to create a new paragraph and replace it if text is formattedAuditNumber , please advice me how to.
Thanks a lot.

Re: replace text with paragraph

PostPosted: Tue Nov 08, 2011 11:14 am
by lucasfgc
Do you want to replace a single word by a paragraph, is this ?

Re: replace text with paragraph

PostPosted: Tue Nov 08, 2011 11:04 pm
by fachhoch
Yes. Its a place holder for a paragraph.
Please advice me hot to.

Re: replace text with paragraph

PostPosted: Tue Nov 08, 2011 11:17 pm
by lucasfgc
I'm just taking some parts from
http://www.docx4java.org/svn/docx4j/tru ... arted.html
_____________________________________________
Selecting your insertion/editing point;
accessing JAXB nodes via XPath

Sometimes, XPath is a succinct way to select the things you need to change.

Happily, from docx4j 2.5.0, you can do use XPath to select JAXB nodes:

MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();

String xpath = "//w:p";

List<Object> list = documentPart.getJAXBNodesViaXPath(xpath, false);

These JAXB nodes are live, in the sense that if you change them, your document changes.

There is a limitation however: the xpath expressions are evaluated against the XML document as it was when first opened in docx4j. You can update the associated XML document once only, by passing true into getJAXBNodesViaXPath. Updating it again (with current JAXB 2.1.x or 2.2.x) will cause an error.
_____________________________________________

I think that this is enough...

Re: replace text with paragraph

PostPosted: Tue Nov 08, 2011 11:48 pm
by fachhoch
I tried this

Code: Select all

                    WordprocessingMLPackage wordMLPackage =
         WordprocessingMLPackage .load(new java.io.File("e://dev//java2word//word2java//ADL.docx"));
      MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();

               String xpath = "//w:r[w:t[contains(text(),'auditFindings')]]";
      List<Object> list = documentPart.getJAXBNodesViaXPath(xpath, true);
      list.clear();
      list.add(getFindingText());
      list.add(getAuditFinding());
      
       wordMLPackage.save(new File("e://dev//java2word//word2java//ADL-new-2.docx"));



but nothing was updated in the document can you please tell me whats wrong with my code ?

I debug this and documentPart.getJAXBNodesViaXPath(xpath, true); returns a list , I am just calling clear list and adding more to the list , why is it not changing the document?

Re: replace text with paragraph

PostPosted: Wed Nov 09, 2011 12:00 am
by lucasfgc
Just try it...
Remember, i'm using "getJAXBNodesViaXPath"

Code: Select all
WordprocessingMLPackage wordMLPackage =
WordprocessingMLPackage .load(new java.io.File("e://dev//java2word//word2java//ADL.docx"));
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();

String xpath = "//w:r[w:t[contains(text(),'auditFindings')]]";
List<Object> list = documentPart.getJAXBNodesViaXPath(xpath, true);

for (Object obj : list) {

list = (Text) ((JAXBElement) obj).getValue();
String textValue = this.list.getValue();

//now you have a String - textValue... just modify it
textValue = "your own string";

list.setValue(this.textValue);

}

wordMLPackage.save(new File("e://dev//java2word//word2java//ADL-new-2.docx"));


I hope that it helps...
Cheers.

Re: replace text with paragraph

PostPosted: Wed Nov 09, 2011 12:08 am
by fachhoch
Thanks a lot for your quick reply ,
I was able to replce text value , no problem with that , what I am looking for is insert a new paragraph in the middle of the document ,
I created a place holder with a string auditFindings, this is a book mark to add a list of paragraphs with different styles , I wan to remove auditFindings and put list of new paragraphs, please help me.

Re: replace text with paragraph

PostPosted: Wed Nov 09, 2011 12:14 am
by fachhoch
here is my whole code

Code: Select all
   public static void testDoc() throws Exception{
      System.out.println("test");
      WordprocessingMLPackage wordMLPackage =
         WordprocessingMLPackage .load(new java.io.File("e://dev//java2word//word2java//ADL.docx"));
      MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
      org.docx4j.wml.Document wmlDocumentEl = (org.docx4j.wml.Document) documentPart.getJaxbElement();
      Body body = wmlDocumentEl.getBody();
      Callback  callback= new Callback() {
         String indent = "";
         @Override
         public void walkJAXBElements(Object parent) {
            indent += "    ";

            List children = getChildren(parent);
            if (children != null) {

               for (Object o : children) {

                  // if its wrapped in javax.xml.bind.JAXBElement, get its
                  // value
                  o = XmlUtils.unwrap(o);

                  this.apply(o);

                  if (this.shouldTraverse(o)) {
                     walkJAXBElements(o);
                  }
               }
            }
            indent = indent.substring(0, indent.length() - 4);
         }
         
         @Override
         public boolean shouldTraverse(Object object) {
            return true;
         }
         
         @Override
         public List<Object> getChildren(Object object) {
            return TraversalUtil.getChildrenImpl(object);
         }
         
         @Override
         public List<Object> apply(Object object) {
            if (object instanceof org.docx4j.wml.Text){
               Text  wText=(org.docx4j.wml.Text) object;
               if(wText.getValue().equals("formattedAuditNumber")){
                  wText.setValue("A-123-456-9876"); //  here this works , I can change text
               }
            }
            return null;
         }
      };
      new TraversalUtil(body, callback);
      
      String xpath = "//w:r[w:t[contains(text(),'auditFindings')]]";
      
      List<Object> list = documentPart.getJAXBNodesViaXPath(xpath, true);
      list.clear();
      list.add(getFindingText());
      list.add(getAuditFinding());
      
       wordMLPackage.save(new File("e://dev//java2word//word2java//ADL-new-2.docx"));
      
   }
I was able to change text but donot know how to replace a text with   list of Paragraps,
the methods getFindingText(),  getAuditFinding()  creates two new paragraph , I can add these two paragraph at the end  fo the doumenht but how can I  add in the middle somewhere ?


Code: Select all

   private static P getFindingText(){
      org.docx4j.wml.ObjectFactory factory = new org.docx4j.wml.ObjectFactory();
      org.docx4j.wml.P  p = factory.createP();
      org.docx4j.wml.Text  t = factory.createText();
      t.setValue("A manual reconciliation process has been instituted.  The current reconciliation process is at the fund center level. There are written procedures for preparing the PSC 272. .  The Financial Accountants reconcile the expends vs. allots spreadsheets to balances in FETS on a monthly basis. The DCS Controller or FSSA Director of Federal funding reveiw and certify the reports.");
      org.docx4j.wml.R  run = factory.createR();
      run.getContent().add(t);
      p.getContent().add(run);
      return p;
   }
   
   
   private static P  getAuditFinding(){
      org.docx4j.wml.ObjectFactory factory = new org.docx4j.wml.ObjectFactory();
      
      org.docx4j.wml.P  p = factory.createP();
      
      org.docx4j.wml.Text  t = factory.createText();
      t.setValue("Audit Finding");
      
      org.docx4j.wml.R  run = factory.createR();
      run.getContent().add(t);
      
      p.getContent().add(run);
      
      org.docx4j.wml.RPr rpr = factory.createRPr();      
      org.docx4j.wml.BooleanDefaultTrue b = new org.docx4j.wml.BooleanDefaultTrue();
       b.setVal(true);      
       rpr.setB(b);
      
       rpr.setU(new U(){
          {
             setVal(UnderlineEnumeration.THICK);
          }
       });
      
       run.setRPr(rpr);
       org.docx4j.wml.PPr ppr = factory.createPPr();      
       p.setPPr( ppr );
       org.docx4j.wml.ParaRPr paraRpr = factory.createParaRPr();
       ppr.setRPr(paraRpr);      
       rpr.setB(b);
       return p;
      
   }


Re: replace text with paragraph

PostPosted: Wed Nov 09, 2011 12:22 am
by lucasfgc
At Getting Started Guide, you can find the session

"Adding a paragraph of text"

You ought to read it and i think that you'll be able to do whatever you want!
It's clearly enough...

Re: replace text with paragraph

PostPosted: Wed Nov 09, 2011 12:28 am
by fachhoch
I was able to adda new paragraph , but not at the place I want to add ,when I call

Code: Select all
documentPart.addObject(o)



it always add at the bottom , but I want to add in the middle of the document , all I am asking is how to add a paragraph in the middle of the document ?

Re: replace text with paragraph

PostPosted: Wed Nov 09, 2011 1:47 am
by lucasfgc
Ok, here we go...

Try it!

Code: Select all
    public static void testDoc() throws Exception {
        System.out.println("test");
        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File("teste.docx"));
        MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
        org.docx4j.wml.Document wmlDocumentEl = (org.docx4j.wml.Document) documentPart.getJaxbElement();

        String xpath = "//w:r[w:t[contains(text(),'auditFindings')]]";

        System.out.println("XPATH " + xpath);
        List<Object> list = documentPart.getJAXBNodesViaXPath(xpath, true);


        for (Object obj : list) {
            org.docx4j.wml.ObjectFactory factory = new org.docx4j.wml.ObjectFactory();
            org.docx4j.wml.Text t = factory.createText();
            t.setValue("A manual reconciliation process has been instituted.  The current reconciliation process is at the fund center level. There are written procedures for preparing the PSC 272. .  The Financial Accountants reconcile the expends vs. allots spreadsheets to balances in FETS on a monthly basis. The DCS Controller or FSSA Director of Federal funding reveiw and certify the reports.");
            ((R) obj).getContent().add(t);
        }

        wordMLPackage.save(new File("test.docx"));

    }


edit:
is better if you clear your content before add
i'll not do it into the code...

Re: replace text with paragraph

PostPosted: Wed Nov 09, 2011 2:47 am
by fachhoch
Thanks a lot your code worked , I am able to add content in place holders , here a new issue,
I will generating the document and pdf at the same time , I update the document saving this I see all the new content , but If I pass this to PdfConversion its not showing the new added paragraph.

Code: Select all
      WordprocessingMLPackage wordMLPackage =
         WordprocessingMLPackage .load(new java.io.File("e://dev//java2word//word2java//ADL.docx"));
      MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();

      String xpath = "//w:r[w:t[contains(text(),'auditFindings')]]";
      
      List<Object> list = documentPart.getJAXBNodesViaXPath(xpath, true);
      for(Object obj : list){
         List<Object>  objContent=((R)obj).getContent();
         objContent.clear();   
         objContent.add(getAuditFinding());
         objContent.add(getFindingText());
      }
       wordMLPackage.save(new File("e://dev//java2word//word2java//ADL-new-2.docx"));
      
      org.docx4j.convert.out.pdf.PdfConversion c= new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(wordMLPackage);
       OutputStream os = new java.io.FileOutputStream("e://dev//java2word//word2java//ADL-new-2.pdf");
      c.output(os, new PdfSettings() );


Re: replace text with paragraph

PostPosted: Wed Nov 09, 2011 4:19 am
by lucasfgc
after saving your new document, try to load your package again and check if it works...

Re: replace text with paragraph

PostPosted: Wed Nov 09, 2011 4:23 am
by fachhoch
I just posted a new topic with this issue , I tried loading the document and call pdf conversion it did not work , alos I opened in openoffice it did not work.