הכנס Checkbox, קלט טקסט או תמונות

מנוע המיזוג לוקח מסמך כקלט, מחפש בו שדות MERGEFIELD ומחליף אותם בנתונים המתקבלים ממקור הנתונים. בדרך כלל, טקסט רגיל ו HTML מוכנסים, אך Aspose.Words משתמשים יכולים גם ליצור מסמך המטפל בתרחישים יוצאי דופן יותר עבור שדות Mail Merge.

פונקציונליות Aspose.Words עוצמתית מאפשרת לך להרחיב את התהליך Mail Merge:

  • הכנס checkboxשדות טופס קלט טקסט למסמך במהלך mail merge
  • הוסף תמונות מכל אחסון מותאם אישית (קבצים, BLOB שדות, וכו').)

הכנס Checkboxקלט טקסט במהלך Mail Merge

לפעמים יש צורך לבצע פעולת Mail Merge כך שלא יוחלף טקסט בשדה המיזוג, אלא שדה checkbox או קלט טקסט. למרות שזה לא התרחיש הנפוץ ביותר, זה מאוד שימושי למשימות מסוימות.

צילום המסך הבא של מסמך Word מציג תבנית עם שדות מיזוג:

insert-checkboxes-or-images-mail-merge-aspose-words

צילום מסך זה של המסמך Word למטה מציג את המסמך שכבר נוצר:

insert-checkboxes-html-or-images-mail-merge-aspose-words

דוגמת הקוד הבאה מראה כיצד להוסיף checkboxשדות טקסט ושדות טקסט למסמך במהלך mail merge:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document(MyDir + "Mail merge destinations - Fax.docx");
// Setup mail merge event handler to do the custom work.
doc.MailMerge.FieldMergingCallback = new HandleMergeField();
// Trim trailing and leading whitespaces mail merge values.
doc.MailMerge.TrimWhitespaces = false;
string[] fieldNames = {
"RecipientName", "SenderName", "FaxNumber", "PhoneNumber",
"Subject", "Body", "Urgent", "ForReview", "PleaseComment"
};
object[] fieldValues = {
"Josh", "Jenny", "123456789", "", "Hello",
"<b>HTML Body Test message 1</b>", true, false, true
};
doc.MailMerge.Execute(fieldNames, fieldValues);
doc.Save(ArtifactsDir + "WorkingWithFields.MailMergeFormFields.docx");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
private class HandleMergeField : IFieldMergingCallback
{
/// <summary>
/// This handler is called for every mail merge field found in the document,
/// for every record found in the data source.
/// </summary>
void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
{
if (mBuilder == null)
mBuilder = new DocumentBuilder(e.Document);
// We decided that we want all boolean values to be output as check box form fields.
if (e.FieldValue is bool)
{
// Move the "cursor" to the current merge field.
mBuilder.MoveToMergeField(e.FieldName);
string checkBoxName = $"{e.FieldName}{e.RecordIndex}";
mBuilder.InsertCheckBox(checkBoxName, (bool) e.FieldValue, 0);
return;
}
switch (e.FieldName)
{
case "Body":
mBuilder.MoveToMergeField(e.FieldName);
mBuilder.InsertHtml((string) e.FieldValue);
break;
case "Subject":
{
mBuilder.MoveToMergeField(e.FieldName);
string textInputName = $"{e.FieldName}{e.RecordIndex}";
mBuilder.InsertTextInput(textInputName, TextFormFieldType.Regular, "", (string) e.FieldValue, 0);
break;
}
}
}
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
{
args.ImageFileName = "Image.png";
args.ImageWidth.Value = 200;
args.ImageHeight = new MergeFieldImageDimension(200, MergeFieldImageDimensionUnit.Percent);
}
private DocumentBuilder mBuilder;
}

הכנס תמונות במהלך Mail Merge

בעת ביצוע פעולת Mail Merge, ניתן להוסיף תמונות ממסד הנתונים למסמך באמצעות שדות מיוחדים Mail Merge. שדה התמונה Mail Merge הוא שדה מיזוג בשם תמונה: MyFieldName.

הכנס תמונות ממסד נתונים

במהלך mail merge, כאשר שדה תמונה Mail Merge נתקל במסמך, האירוע FieldMergingCallback יורה. אתה יכול להגיב לאירוע זה כדי להחזיר שם קובץ, זרם או אובייקט תמונה למנוע Mail Merge כך שניתן יהיה להכניס אותו למסמך.

דוגמת הקוד הבאה מראה כיצד להוסיף תמונות המאוחסנות בשדה מסד נתונים BLOB לדוח:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document(MyDir + "Mail merge destination - Northwind employees.docx");
doc.MailMerge.FieldMergingCallback = new HandleMergeImageFieldFromBlob();
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DatabaseDir + "Northwind.accdb";
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM Employees", conn);
IDataReader dataReader = cmd.ExecuteReader();
doc.MailMerge.ExecuteWithRegions(dataReader, "Employees");
conn.Close();
doc.Save(ArtifactsDir + "WorkingWithFields.MailMergeImageFromBlob.docx");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
public class HandleMergeImageFieldFromBlob : IFieldMergingCallback
{
void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
{
// Do nothing.
}
/// <summary>
/// This is called when mail merge engine encounters Image:XXX merge field in the document.
/// You have a chance to return an Image object, file name, or a stream that contains the image.
/// </summary>
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
{
// The field value is a byte array, just cast it and create a stream on it.
MemoryStream imageStream = new MemoryStream((byte[]) e.FieldValue);
// Now the mail merge engine will retrieve the image from the stream.
e.ImageStream = imageStream;
}
}

הגדר מאפייני תמונה במהלך Mail Merge

בעת מיזוג שדה מיזוג תמונות, ייתכן שתצטרך לפעמים לשלוט במאפייני תמונה שונים, כגון WrapType.

נכון לעכשיו, באמצעות ImageFieldMergingArgs ניתן להגדיר רק מאפייני רוחב תמונה או גובה, בהתאמה. כדי להתגבר על בעיה זו, Aspose.Words מספק את המאפיין Shape, המאפשר לקבל שליטה מלאה על התמונה שהוכנסה או על כל צורה אחרת.

דוגמת הקוד הבאה מראה כיצד להגדיר מאפייני תמונה שונים:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("{{#foreach example}}");
builder.Writeln("{{Image(126pt;126pt):stempel}}");
builder.Writeln("{{/foreach example}}");
doc.MailMerge.UseNonMergeFields = true;
doc.MailMerge.TrimWhitespaces = true;
doc.MailMerge.UseWholeParagraphAsRegion = false;
doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveEmptyTableRows
| MailMergeCleanupOptions.RemoveContainingFields
| MailMergeCleanupOptions.RemoveUnusedRegions
| MailMergeCleanupOptions.RemoveUnusedFields;
doc.MailMerge.FieldMergingCallback = new ImageFieldMergingHandler();
doc.MailMerge.ExecuteWithRegions(new DataSourceRoot());
doc.Save(ArtifactsDir + "WorkingWithFields.MailMergeImageField.docx");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
private class ImageFieldMergingHandler : IFieldMergingCallback
{
void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
{
// Implementation is not required.
}
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
{
Shape shape = new Shape(args.Document, ShapeType.Image)
{
Width = 126, Height = 126, WrapType = WrapType.Square
};
shape.ImageData.SetImage(MyDir + "Mail merge image.png");
args.Shape = shape;
}
}
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
public class DataSourceRoot : IMailMergeDataSourceRoot
{
public IMailMergeDataSource GetDataSource(string s)
{
return new DataSource();
}
private class DataSource : IMailMergeDataSource
{
private bool next = true;
string IMailMergeDataSource.TableName => TableName();
private string TableName()
{
return "example";
}
public bool MoveNext()
{
bool result = next;
next = false;
return result;
}
public IMailMergeDataSource GetChildDataSource(string s)
{
return null;
}
public bool GetValue(string fieldName, out object fieldValue)
{
fieldValue = null;
return false;
}
}
}