DEV Community

Oliver
Oliver

Posted on

Style not remain (including font size, font weight, font color,...) after doing mail merge

I’m working with the Aspose and facing these problems:

Style applied on the merge fields all lost after merging:
Alt text of image

Then, i tried with another approach by removing the MERGEFIELD keyword inside field code, the applied style retained properly but not so really. Merge fields that had been removed these keywords piled up on top of the document (Please ignore the copyright warning):
Alt text of image

This is my code to execute the mail merge process:

public static void generateMailMergePdfFromJson(Document template, String json, String outputFilePath) throws ParserConfigurationException, SAXException, IOException, Exception {
    //Remove merge field with empty value and if the row are empty=> remove paragraph
    template.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_UNUSED_FIELDS
            | MailMergeCleanupOptions.REMOVE_EMPTY_PARAGRAPHS
            | MailMergeCleanupOptions.REMOVE_UNUSED_REGIONS
            | MailMergeCleanupOptions.REMOVE_CONTAINING_FIELDS);

    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode jsonNode = objectMapper.readTree(json);

    ArrayNode arrayNode = objectMapper.createArrayNode();
    arrayNode.add(jsonNode);

    JsonNode rootNode = objectMapper.createObjectNode();

    ((ObjectNode) rootNode).set(Dictionary.ROOT_TAG_NAME, arrayNode);

    //To call custom merge data with html code
    template.getMailMerge().setFieldMergingCallback(new HandleMergeFieldInsertHtml());

    // Add main merge field based of main root tag name
    template.accept(new TableTagHandler(Dictionary.ROOT_TAG_NAME));
    // Merge fields
    template.getMailMerge().executeWithRegions(new JsonMailMergeDataSet(new JsonDocument(rootNode, Dictionary.ROOT_TAG_NAME)));

    template.save(outputFilePath, SaveFormat.PDF);
}

Anyone who has been working with Aspose, please give me an advice on this one.

Top comments (0)