Search code examples
asposeaspose.wordsaspose.pdf

Aspose WORD styling for JAVA


Current situation:

I have multiple word documents with hardcoded styling(e.g. font size, heading color etc.). Using Aspose.WORD for java which generates PDFs.

What I want to achieve:

I would like to use one set of documents for multiple tenants but change the styling based on tenant's need.

Perfect solution would be to have predefined styles before the actual generation of document happens. This style would be applied to the document.

Any solutions?


Solution

  • In your case you can create different templates for each tenant and use AttachedTemplate property to attach the corresponding template to the document and set AutomaticallyUpdateStyles property to true. This forces Aspose.Words to update the styles in your document to match the styles in the attached template. Please see the following simple code example:

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

    You have one template for generating your reports, in this template you define document layout. For demonstration purposes I use Mail Merge feature. And you have several templates where defined only styles. Upon generation the final document you attach the corresponding template with styles and as a result get the desired output. See the following screenshots and the code.

    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

    UPDATE: Instead of using AttachedTemplate and AutomaticallyUpdateStyles properties, you can use copyStylesFromTemplate method. It copies styles from the specified template to a document.