Hello,
I have a docx document of 8 pages with merge fields.
I use IMailMergeDataSource to provide a Dictionary<string, string> collection of data.
After MailMerge.Execute(dataSource), I save the document in PDF.
When I open my PDF, I have 256 pages (32 times the docx document) !!!
Why ?
Here is my method :
public byte[] GeneratePdfFromWordTemplate(byte[] wordTemplateData, ConventionMailMergeDataSource dataSource)
{
var wordTemplateDocument = new Document(new MemoryStream(wordTemplateData));
wordTemplateDocument.MailMerge.TrimWhitespaces = false;
wordTemplateDocument.MailMerge.Execute(dataSource);
MemoryStream pdfDocumentStream = new MemoryStream();
wordTemplateDocument.Save(pdfDocumentStream, SaveFormat.Pdf);
return pdfDocumentStream.ToArray();
}
And here is the IMailMergeDataSource implementation :
public class ConventionMailMergeDataSource : IMailMergeDataSource
{
private readonly Dictionary<string, string> _dataCollection;
private int _recordIndex;
/// <summary>
/// Name of the data source. Used by Aspose.Words only when executing mail merge with repeatable regions.
/// </summary>
public string TableName { get; }
public ConventionMailMergeDataSource(string tableName)
{
TableName = tableName;
_dataCollection = new Dictionary<string, string>();
// When the data source is initialized, it must be positioned before the first record.
_recordIndex = -1;
}
public void AddData(Dictionary<string,string> newData)
{
foreach (var data in newData)
_dataCollection[data.Key] = data.Value;
}
public bool MoveNext()
{
if (!IsEof)
_recordIndex++;
return (!IsEof);
}
public bool GetValue(string fieldName, out object fieldValue)
{
string stringFieldValue = null;
bool result = _dataCollection.TryGetValue(fieldName, out stringFieldValue);
fieldValue = stringFieldValue;
return result;
}
public IMailMergeDataSource GetChildDataSource(string tableName)
{
return null;
}
private bool IsEof
{
get { return (_recordIndex >= _dataCollection.Count); }
}
}
Thank you for your help.