0

I´m making a program that´s supposed to get a docx file and adding whatever the user adds into some textfields. But the template already has a watermark and a preset header.

I was trying to make it using Apache POI, but when I created the new file all the template was lost. It only saved the text. Then I learned about "docx4j" but the page is down and I cannot find anyware else to download that library.

public static void main(String[] args) throws Exception {
    int count = 0;
    XWPFDocument document = new XWPFDocument();
    XWPFDocument docx = new XWPFDocument(new FileInputStream("Plantilla.docx"));
    XWPFWordExtractor we = new XWPFWordExtractor(docx);
    String text = we.getText() ;
    if(text.contains("Cambio")){
        text = text.replace("Cambio", "cambio");
        System.out.println(text);
    }
    char[] c = text.toCharArray();
    for(int i= 0; i < c.length;i++){

        if(c[i] == '\n'){
            count ++;
        }
    }
    System.out.println(c[0]);
    StringTokenizer st = new StringTokenizer(text,"\n");

    XWPFParagraph para = document.createParagraph();
    para.setAlignment(ParagraphAlignment.CENTER);
    XWPFRun run = para.createRun();

    List<XWPFParagraph>paragraphs = new ArrayList<XWPFParagraph>();
    List<XWPFRun>runs = new ArrayList<XWPFRun>();
    int k = 0;
    for(k=0;k<count+1;k++){
        paragraphs.add(document.createParagraph());
    }
    k=0;
    while(st.hasMoreElements()){
        paragraphs.get(k).setAlignment(ParagraphAlignment.LEFT);
        paragraphs.get(k).setSpacingAfter(0);
        paragraphs.get(k).setSpacingBefore(0);
        run = paragraphs.get(k).createRun();
        run.setText(st.nextElement().toString());
        k++;
    }

    document.write(new FileOutputStream("test3.docx"));
}          

}

EOT
  • 1
  • 2
  • 2
    "I was trying to make it using Apache POI, but when I created the new file all the template was lost.": Then you did something wrong. But since you do not show what you did, no one can help. – Axel Richter Sep 11 '19 at 16:45
  • Ok, my mistake, sorry. I was on a hurry when I write it. I've added the code. – EOT Sep 11 '19 at 20:41
  • The `XWPFWordExtractor` of course only gets the text out of the `Plantilla.docx`. But why not creatie a `XWPFDocument` from that file, then process that `XWPFDocument` in memory and writie it out to a different file `test3.docx` after that? Something along the lines of https://stackoverflow.com/questions/56409262/problem-with-processing-word-document-java/56412311#56412311. – Axel Richter Sep 12 '19 at 03:41
  • https://www.docx4java.org/downloads.html works for me. – JasonPlutext Sep 12 '19 at 19:42
  • When you say template, do you mean a dotx, or simply a docx you want to clone and add stuff to? – JasonPlutext Sep 12 '19 at 19:42
  • A docx I want to clone and add stuff to – EOT Sep 14 '19 at 19:39

0 Answers0