Docx4j docx toPdf 不保留空格

Docx4j docx toPdf don't preserve whitespaces

提问人:Guglio 提问时间:11/15/2023 更新时间:11/15/2023 访问量:26

问:

我对 docx4j 有疑问。输出的 pdf 被剪切,所有空格或制表符现在都只替换为一个。例如,如果在 docx 中有一个字符串,例如 “一个,一个,一个” 输出将为“a a a”。与选项卡相同。我的代码和我的pom在下面。我做错了什么?谢谢。

           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();

我的绒球看起来像

      <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>

我尝试过使用 t.setSpace(“preserve”)(下面的代码),但空格仍然被剪切。

    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;
    }
java docx4j pdf 尾随空格 docx到pdf转换

评论

0赞 Bagus Tesa 11/15/2023
这回答了你的问题吗?docx4j - 为什么空格的文本被截断?
0赞 Guglio 11/15/2023
不,我已经在做 t.setSpace(“preserve”);但仍然没有正确的结果。在您链接的这篇文章中,问题是在创建文本部分时,就我而言,我必须更新我的文本部分而不是创建新的文本部分。
0赞 Bagus Tesa 11/15/2023
问题是,生成 XML 的软件可能会因为忘记保留标志而做奇怪的事情。那个或特定的 docx4j 有一个错误,以前发生过。也许您应该检查 docx 文件,包括原始文件和您添加的文件。t.setSpace(..
0赞 Guglio 11/15/2023
我已经检查了我在输入中给出的 docx 文件,并且在空格之前有 <w:t xml:space=“preserve”>所以问题出在我的代码中,或者是 docx4j 的问题。

答: 暂无答案