为 JAVA 设置 WORD 样式

问题描述

现状

我有多个带有硬编码样式(例如字体大小、标题颜色等)的 Word 文档。使用 Aspose.WORD for java 生成 PDF。

我想要达到的目标

我想为多个租户使用一组文档,但根据租户的需要更改样式。

完美的解决方案是在实际生成文档之前拥有预定义的样式。此样式将应用于文档。

有什么解决办法吗?

解决方法

在您的情况下,您可以为每个租户创建不同的模板,并使用 AttachedTemplate 属性将相应的模板附加到文档并将 AutomaticallyUpdateStyles 属性设置为 true。这会强制 Aspose.Words 更新文档中的样式以匹配附加模板中的样式。请看下面的简单代码示例:

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// The Hello World text will use Normal style.
builder.writeln("Hello world");

// In the template.dotx I modified Normal style 
// and after saving the text will be styled like defined in the template.
doc.setAttachedTemplate("C:\\Temp\\template.dotx");
doc.setAutomaticallyUpdateStyles(true);

doc.save("C:\\Temp\\out.docx");
doc.save("C:\\Temp\\out.pdf");

您有一个用于生成报告的模板,您可以在该模板中定义文档布局。出于演示目的,我使用邮件合并功能。并且您有几个仅定义样式的模板。在生成最终文档时,您可以附加带有样式的相应模板,从而获得所需的输出。请参阅以下屏幕截图和代码。

generateWithStyling("styling1","C:\\Temp\\template1.dotx");
generateWithStyling("styling2","C:\\Temp\\template2.dotx");
private static void generateWithStyling(String suffix,String template) throws Exception
{
    // Open template
    Document doc = new Document("C:\\Temp\\in.docx");
    // Execute mail merge to fill the template with data.
    doc.getMailMerge().execute(new String[] { "FirstName","LastName" },new String[] { "Alexey","Noskov" });

    doc.setAttachedTemplate(template);
    doc.setAutomaticallyUpdateStyles(true);

    doc.save("C:\\Temp\\out_" + suffix + ".docx");
    doc.save("C:\\Temp\\out_" + suffix + ".pdf");
}

enter image description here