Font Style for MailMerge Fields

Hello,

I am creating a PDF document using word template as shown in below code.

How to set the font style for the mail merge fields and regions?

Thanks for your time and help.

Hiren

AccountMailMergeDataSource bankingAccountDataSource = new AccountMailMergeDataSource(bankingAccounts);
LocaleBean localeBean =(LocaleBean) Utilities.getUIBean(“localeBean”);
String downloadDate = localeBean.getCurrentDateTimeForPrintHeader();
String assets = displayAssets();
String liabilities = displayLiabilities();
String netWorth = displayNetWorth();
doc.getMailMerge().execute(
new String[] {“DownloadDate”, “Assets”, “Liabilities”, “NetWorth”},
new Object[] {downloadDate, assets, liabilities,netWorth });
doc.getMailMerge().executeWithRegions(bankingAccountDataSource);
ByteArrayOutputStream dstStream = new ByteArrayOutputStream();
doc.save(dstStream, SaveFormat.PDF);

Hi Hiren,

Thanks for your inquiry. You can achieve your requirements by using one of following approaches.

  1. Open your template document in MS Word and format the fields (set font style) according to your requirements and then use Aspose.Words to perform mail merge operation. You can also apply formatting to text using Aspose.Words. Please read following documentation link for your kind reference.
    https://docs.aspose.com/words/java/mail-merge-and-reporting/

  2. Implement IFieldMergingCallback interface and set font style in IFieldMergingCallback.fieldMerging. Please check code example in following documentation link.
    https://reference.aspose.com/words/java/com.aspose.words/IFieldMergingCallback

Hope this helps you. If you still face problem, please share following detail for investigation purposes.

  • Please attach your input Word document.
  • Pleasecreate a standalone/runnable simple Java application that demonstrates the code (Aspose.Words code) you used to generate your output document
  • Please attach the output Word file that shows the undesired behavior.
  • Please attach your target Word document showing the desired behavior. You can
    use Microsoft Word to create your target Word document. I will investigate as to how you are expecting your final document be generated like.

As soon as you get these pieces of information to
us we’ll start our investigation into your issue.

Thanks for your response.

I am trying below code in IFieldMergingCallback handler method, but do not see the Font as expected in RED color.

Please let me know what I am missing.

Thanks for your time and help.

public void fieldMerging(FieldMergingArgs e) throws Exception
{
    if (mBuilder == null){
        mBuilder = new DocumentBuilder(e.getDocument());
    }
    if (e.getFieldName().equals(“investingnickname”) || e.getFieldName().equals(“investingbalance”) || e.getFieldName().equals(“Assets”)) {
        mBuilder.getFont().setColor(Color.RED);
    }
}

Hi Hiren,

Thanks for your inquiry. Please move the cursor to the mail merge field and write the mail merge field’s value as shown below.

public void fieldMerging(FieldMergingArgs e) throws Exception {
    if (mBuilder == null){
        mBuilder = new DocumentBuilder(e.getDocument());
    }

    if (e.getFieldName().equals(“investingnickname”) || e.getFieldName().equals(“investingbalance”) || e.getFieldName().equals(“Assets”)) {
        mBuilder.getFont().setColor(Color.RED);
        mBuilder.moveToMergeField(e.getFieldName(), false, false);
        mBuilder.write(e.getFieldValue().toString());
    }
}

If you still face problem, please share the detail requested in my previous post for investigation purposes. I will investigate the issue on my side and provide you more information.

Thanks a lot for your consistent help.


I was able to get the font style as expected.

Hiren

Hi Hiren,

Thanks for your feedback. Please feel free to ask if you have any question about Aspose.Words, we will be happy to help you.

Hi I’ve been having similar issues where the font I set in the docx gets changed when merged to a pdf.
I’ve tried what was posted above, adding the * Charformat tag in the mergefield, I’ve made sure the fonts are available in my system and tried explicitly pointing to the fonts folder.
I am merging with regions using a dataset.

com.aspose.words.FolderFontSource folderFontSource = new com.aspose.words.FolderFontSource("/usr/share/fonts/truetype", false, 1);
docToGen.setFontSettings(new FontSettings());
docToGen.getFontSettings().setFontsSources(new com.aspose.words.FontSourceBase[]{folderFontSource});
docToGen.getMailMerge().setFieldMergingCallback(new IFieldMergingCallback() {
    public void fieldMerging(FieldMergingArgs e) throws Exception {
        DocumentBuilder mBuilder = null;
        if (mBuilder == null)
            mBuilder = new DocumentBuilder(e.getDocument());

        if (e.getFieldName().contains("fieldname")) {
            com.aspose.words.Font font = mBuilder.getFont();
            font.setSize(16.0);
            font.setBold(true);
            font.setName("Segoe Script");
            mBuilder.moveToMergeField(e.getFieldName(), false, false);
            mBuilder.write(e.getFieldValue().toString());
            // e.setText("");
        }
    }
    // needed for implementation of above.
    public void /*IFieldMergingCallback.*/imageFieldMerging(ImageFieldMergingArgs args) {
        // Do nothing
    }
});

Any other ideas would be helpful.

@anotherdev86 Could you please attach your template, output and expected documents here for testing? We will check the issue and provide you more information.

mytest.pdf (14.5 KB)
mytest.docx (12.1 KB)
expectedOutput.pdf (49.9 KB)

I can’t send you the actual documents I’m working on due to NDA’s however these are the same in concept.
A main region which contains fields, and potentially nested regions. One of those fields needing a specific font.

So far the closest success has been turning the whole document into segoe script but no other font so I’m not sure why it’s suddenly defaulted to that whenever I comment out these FontSetting lines. When its in use it doesn’t matter whether is true or false, the font remains the same. I’m not sure the solution lies here but it’s the only thing that has made a difference.

// FontSettings fontSettings = new FontSettings();
// fontSettings.getSubstitutionSettings().getDefaultFontSubstitution().setEnabled(false);
// docToGen.setFontSettings(fontSettings);

@anotherdev86 Thank you for additional information. As I can see in your template you already specified \* CHARFORMAT in the FirstName merge field. If this format switch is specified Aspose.Words uses character format of the field code to format the result value. In your case in the field code Segoe Script font is specified:

After executing the following code the output looks as your expected output:

DataTable dt = new DataTable("MergeRegion");
dt.getColumns().add("FirstName");
dt.getColumns().add("LastName");
dt.getRows().add("James", "Bond");
dt.getRows().add("Money", "Penny");

Document doc = new Document("C:\\Temp\\in.docx");
doc.getMailMerge().executeWithRegions(dt);
doc.save("C:\\Temp\\out.pdf");

Here is output document: out.pdf (23.8 KB)

If clear formatting of the document and it is required to apply font formatting in the code, the code should looks like this:

Document doc = new Document("C:\\Temp\\in.docx");
doc.getMailMerge().setFieldMergingCallback(new FontChangeCallback());
doc.getMailMerge().executeWithRegions(dt);
doc.save("C:\\Temp\\out.pdf");
private static class FontChangeCallback implements IFieldMergingCallback
{
    @Override
    public void fieldMerging(FieldMergingArgs args) throws Exception {

        if(args.getFieldName().equals("FirstName"))
        {
            // Change formatting of the field.
            Node currentNode = args.getField().getStart();
            do {
                SetFont(currentNode);
                currentNode = currentNode.getNextSibling();
            }while (currentNode != null && currentNode != args.getField().getEnd());
        }
    }

    @Override
    public void imageFieldMerging(ImageFieldMergingArgs args) throws Exception {
        // Do nothing
    }

    private static void SetFont(Node node)
    {
        boolean isInline = node instanceof Inline;
        if(isInline) {
            Font font = ((Inline)node).getFont();
            font.setName("Segoe Script");
        }
    }
}

Here are input and output documents: in.docx (14.1 KB) out.pdf (23.8 KB)

1 Like

That inline portion did it! Thanks for the help and quick response time!

1 Like