首页 文章

使用Aspose.Words将样式从模板复制到许多文档

提问于
浏览
0

我正在尝试创建一个Java“脚本”,以便给定模板和目标文档:

  • 读取模板中定义的所有样式,包括文本和表格

  • 将每个样式复制到目标文档上,如果样式已存在则替换该样式

总而言之,这是我到现在为止所提出的,也是基于API reference for the StyleCollection class

Document target = new Document(targetPath);
StyleCollection targetStyles = target.getStyles();

for (Style style : source.getStyles()) {
    switch (style.getType()) {
        case StyleType.PARAGRAPH:
        case StyleType.TABLE:
        case StyleType.LIST:
            if (!style.getName().trim().toLowerCase().endsWith("carattere")) {
                String name = style.getName();
                Style copied = styles.addCopy(style);

                switch (style.getType()) {
                    case StyleType.PARAGRAPH:
                        copied.setNextParagraphStyleName(style.getNextParagraphStyleName());
                        // fallthrough

                    case StyleType.CHARACTER:
                    case StyleType.TABLE:
                        copied.setBaseStyleName(style.getBaseStyleName());
                        break;

                    default:
                        break;
                }

                copied.setName(name);
            }
            break;

        default:
            break;
    }
}

target.save(savePath);

截至目前,我发现的问题如下:

  • 如果我尝试使用标准MS Word样式(“正常”,“ Headers 1”,......),当它们被复制时,即使使用setName()“技巧”它们也会被复制

  • 如果我改为使用自定义样式,我对表格样式有问题,其中文本颜色会发生变化

如何获得文档中所有样式的干净副本?

1 回答

  • 1

    如果我尝试使用标准的MS Word样式(“正常”,“ Headers 1”,......),当它们被复制时,即使使用setName()“技巧”,它们也会被复制

    请使用以下示例代码段,它将帮助您获得没有样式重复的输出 .

    Document source = new Document(MyDir + "template.doc");
    Document target = new Document(MyDir + "target.doc");
    
    StyleCollection sourceStyles = source.getStyles();
    StyleCollection targetStyles = target.getStyles();
    
    System.out.println("SORGENTE = " + sourceStyles.getCount() + " stili");
    System.out.println("DESTINAZIONE = " + targetStyles.getCount() + " stili");
    
    for (Style style : sourceStyles) {
        String name = style.getName();
        if (name.endsWith("Carattere")) continue;
    
        if (style.getType() == StyleType.PARAGRAPH
                                || style.getType() == StyleType.TABLE)
        {
            Style copied = targetStyles.addCopy(style);
            copied.setBaseStyleName(style.getBaseStyleName());
    
            if (style.getType() == StyleType.PARAGRAPH) {
               copied.setNextParagraphStyleName(style.getNextParagraphStyleName());
            }
            copied.setName(name);
            System.out.println("COPIA STILE " + name + " -> " + copied.getName());
        }
    }
    
    target.cleanup();
    target.save(MyDir + "output.docx");
    

    如果我改为使用自定义样式,我会遇到表格样式的问题,其中文本颜色会发生变化

    请注意Aspose.Words模仿MS Word行为 . 如果你import the styles from your template to target document using MS Word,它将显示与Aspose.Words相同的结果 .

    我和Aspose一起担任开发人员Evangelist .

相关问题