Header Alignment issue during mailmerge

We have a MS word document where we are reducing the top margin to 0 and starting the text content without leaving any top margin.
But after mailmerge, the resultant document is rendered with some top margin.
Due to this the text at the end of the page is pushed to next page.

Output merged file - Alignment test merged.pdf (34.2 KB)
Input file - Alignment test.docx (22.0 KB)

Below is the C# code we use to mailmerge

IDictionary<string, object> parameters1 = new Dictionary<string, object> { { "PERSONNAME", "Jagan" } };
 
 IEnumerable<TemplateSequenceParameter> sequenceParameters1 = new List<TemplateSequenceParameter>
 {
 	new TemplateSequenceParameter
 	{
 		Key = "CONTACTTYPE",
 		Values = new List<object> { "home", "office", ... }
 	},
 	new TemplateSequenceParameter
 	{
 		Key = "EMPLOYEEFIRSTNAME",
 		Values = new List<object> { "john", "peter", ... }
 	}
 };
 
 using (MemoryStream stream = new MemoryStream())
 {
 	using (XmlWriter writer = XmlWriter.Create(stream, new XmlWriterSettings()))
 	{
 		writer.WriteStartDocument();
 		writer.WriteStartElement(DataSourceName);
 
 		foreach (KeyValuePair<string, object> parameter in parameters)
 		{
 			writer.WriteElementString(parameter.Key, parameter.Value.ToString());
 		}
 
 		int colCount = sequenceParameters.Count();
 		if (colCount > 0)
 		{
 			int rowCount = sequenceParameters.First().Values.Count();
 
 			for (int rowInd = 0; rowInd < rowCount; rowInd++)
 			{
 				writer.WriteStartElement(DataSourceSequenceParameterPrefix);
 
 				for (int colInd = 0; colInd < colCount; colInd++)
 				{
 					writer.WriteElementString(sequenceParameters.ElementAt(colInd).Key, sequenceParameters.ElementAt(colInd).Values.ElementAt(rowInd).ToString());
 				}
 
 				writer.WriteEndElement();
 			}
 		}
 
 		writer.WriteEndElement();
 		writer.WriteEndDocument();
 		writer.Flush();
   }
 
 	stream.Position = 0;
 
 	XmlDataSource dataSource = new XmlDataSource(stream);

      ReportingEngine engine = new ReportingEngine();
           engine.Options |= ReportBuildOptions.AllowMissingMembers;
           engine.Options |= ReportBuildOptions.RemoveEmptyParagraphs;

     engine.BuildReport(document, dataSource, DataSourceName);

    using (MemoryStream ms = new MemoryStream(4096))
    {
	   document.LayoutOptions.TextShaperFactory = HarfBuzzTextShaperFactory.Instance;
	   document.Save(ms, GetSaveOptions("pdf"));
	   byte[] documentContent = ms.ToArray();

          return documentContent;
    }

 }


private static SaveOptions GetSaveOptions(DocumentFormat outputFormat)
{
	switch (outputFormat)
	{
		case "pdf":
			PdfSaveOptions options = new PdfSaveOptions();

			options.MemoryOptimization = true;
			options.ImageCompression = PdfImageCompression.Jpeg;
			options.JpegQuality = 0;
			options.UseHighQualityRendering = false;
			options.DmlRenderingMode = DmlRenderingMode.Fallback;
			options.DmlEffectsRenderingMode = DmlEffectsRenderingMode.None;

			return options;
	}
}

Can you please suggest how to correct this alignment issue

@mjjagan

Cause

The issue you’re experiencing with the top margin during the mail merge process is likely due to the default settings in the document or the way the mail merge is handling the layout. Even if you set the top margin to zero in the original document, the mail merge process may introduce additional spacing or formatting that affects the final output.

Solution

To resolve this alignment issue, you can try the following steps:

  1. Check Document Margins: Ensure that the margins in your Word document are set to zero. You can do this by going to the “Layout” tab in Word and checking the “Margins” settings.

  2. Remove Empty Paragraphs: Since you are already using ReportBuildOptions.RemoveEmptyParagraphs, ensure that there are no empty paragraphs or additional spacing in your document that could be causing the issue.

  3. Adjust Layout Options: Modify the layout options in your code to ensure that the document is rendered correctly. For example, set the LayoutOptions to avoid any unexpected spacing.

  4. Set Page Size and Orientation: Ensure that the page size and orientation are set correctly in the document. Incorrect settings can lead to unexpected margins.

Code

Here’s a modified version of your existing code that includes setting the layout options:

engine.Options |= ReportBuildOptions.RemoveEmptyParagraphs;
engine.Options |= ReportBuildOptions.AllowMissingMembers;

// Set layout options to avoid unexpected margins
document.LayoutOptions.TextShaperFactory = HarfBuzzTextShaperFactory.Instance;
document.LayoutOptions.UseOptimizedLayout = true; // Add this line

// Save the document
using (MemoryStream ms = new MemoryStream(4096))
{
    document.Save(ms, GetSaveOptions("pdf"));
    byte[] documentContent = ms.ToArray();
    return documentContent;
}

Next Steps

  1. After making these adjustments, run the mail merge again and check the output document.
  2. If the issue persists, review the document structure in Word to ensure there are no hidden elements affecting the layout.
  3. Test with a simpler document to isolate the issue.

Please implement these changes and let me know the results!

@mjjagan According to the attached output document, you are adding watermark into the document. In MS Word watermarks are added to the document header, the same does Aspose.Words. Your original document does not have header, so it is created when watermark is added and this adds space at the top. You can reproduce the problem using the following simple code:

Document doc = new Document(@"C:\Temp\in.docx");
doc.Watermark.SetText("test");
doc.Save(@"C:\Temp\out.docx");
doc.Save(@"C:\Temp\out.pdf");

out.docx (16.0 KB)
out.pdf (41.0 KB)

This is expected behavior and you will see the same when add watermark using MS Word.

You can work the problem around by setting header distance to zero and setting paragraph break font size of header paragraphs to zero. Something like this:

Document doc = new Document(@"C:\Temp\in.docx");
doc.Watermark.SetText("test");

foreach (Section s in doc.Sections)
{
    s.PageSetup.HeaderDistance = 0;
    foreach (HeaderFooter hf in s.HeadersFooters)
    {
        foreach (Paragraph p in hf.Paragraphs)
            p.ParagraphBreakFont.Size = 0;
    }
}

doc.Save(@"C:\Temp\out_workaround.docx");
doc.Save(@"C:\Temp\out_workaround.pdf");

out_workaround.docx (16.1 KB)
out_workaround.pdf (40.5 KB)

Thanks Alexey,

The suggestion is working fine for the sample document.
However, we have a complex template for which we have space alignment issue

Input template:
PND91SPECIALTAX_Leelawadee.docx (349.8 KB)

Output merged PDF:
PND91SPECIALTAX_Leelawadee Merged.pdf (132.5 KB)

can you please suggest for this template

@mjjagan The problem is not reproducible on my side. Here are output documents produced by the code provided above:
out_workaround.docx (106.6 KB)
out_workaround.pdf (178.8 KB)

As I can see fonts using in your PDF document differs from fronts used on my side. Usually, such problems occur because the fonts used in your input document are not available on the machine where document is converted to PDF. The fonts are required to build document layout. If Aspose.Words cannot find the font used in the document, the font is substituted . This might lead into fonts mismatch and document layout differences due to the different fonts metrics. You can implement IWarningCallback to get notifications when font substitution is performed.
Please see our documentation to learn where Aspose.Words looks for fonts:
https://docs.aspose.com/words/net/specifying-truetype-fonts-location/

yes, you are right Alexey.

The alignment issue was due to the font substitution.
I installed the needed fonts in Docker and now the alignment looks perfect.

Thanks for your suggestion.

1 Like