Docx4j docx toPdf don't preserve whitespaces

75 Views Asked by At

i have a problem with docx4j. The output pdf is cutted and all spaces or tabs are now replaced with only one. For example if in the docx there is a string like " a a a" the output will be "a a a". Same with tabs. My code and my pom below. What am i doing wrong? Thank you.

           InputStream isNodo = new ByteArrayInputStream(contentNodoTempl);

            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(isNodo);
            VariablePrepare.prepare(wordMLPackage);

            // output file
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            Docx4J.toPDF(wordMLPackage, bos);
            bos.flush();
            isNodo.close();
            return bos.toByteArray();

With my pom looking like

      <dependency>
         <groupId>org.docx4j</groupId>
         <artifactId>docx4j-JAXB-ReferenceImpl</artifactId>
         <version>8.3.9</version>
      </dependency>
      <dependency>
         <groupId>org.docx4j</groupId>
         <artifactId>docx4j-export-fo</artifactId>
         <version>8.3.9</version>
      </dependency>

i have tried with t.setSpace("preserve") (code below) but the spaces are still cutted.

    public static void findAndReplace(WordprocessingMLPackage doc){
        List<Object> paragraphs = getAllElementFromObject(doc.getMainDocumentPart(), P.class);
        for(Object par : paragraphs){
            P p = (P) par;
            List<Object> texts = getAllElementFromObject(p, Text.class);
            for(Object text : texts){
                Text t = (Text)text;
                t.setSpace("preserve");
            }
        }
    }

    public static List<Object> getAllElementFromObject(Object obj, Class<?> toSearch) {
        List<Object> result = new ArrayList<Object>();
        if (obj instanceof JAXBElement) obj = ((JAXBElement<?>) obj).getValue();

        if (obj.getClass().equals(toSearch))
            result.add(obj);
        else if (obj instanceof ContentAccessor) {
            List<?> children = ((ContentAccessor) obj).getContent();
            for (Object child : children) {
                result.addAll(getAllElementFromObject(child, toSearch));
            }
        }
        return result;
    }
0

There are 0 best solutions below