Wstaw Checkboxes, wprowadzanie tekstu lub obrazy

Silnik scalania przyjmuje dokument jako dane wejściowe, szuka w nim pól MERGEFIELD i zastępuje je danymi uzyskanymi ze źródła danych. Zazwyczaj wstawiany jest zwykły tekst i HTML, ale użytkownicy Aspose.Words mogą również wygenerować dokument, który obsługuje bardziej nietypowe scenariusze dla pól Mail Merge.

Potężna funkcjonalność Aspose.Words pozwala rozszerzyć proces Mail Merge:

  • Wstaw checkboxpola formularza es i wprowadzania tekstu do dokumentu podczas mail merge
  • Wstaw obrazy z dowolnego niestandardowego magazynu (pliki, pola BLOB itp.)

Insert Checkboxes i wprowadzanie tekstu podczas Mail Merge

Czasami konieczne jest wykonanie operacji Mail Merge, aby w polu scalania nie podstawiono tekstu, ale checkbox lub pole wprowadzania tekstu. Chociaż nie jest to najczęstszy scenariusz, jest bardzo przydatny w przypadku niektórych zadań.

Poniższy zrzut ekranu dokumentu Word pokazuje szablon z polami scalania:

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

Ten zrzut ekranu dokumentu Word poniżej pokazuje już wygenerowany dokument:

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

Poniższy przykład kodu pokazuje, jak wstawić checkboxes i wprowadzić pola tekstowe do dokumentu podczas 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;
}

Wstawianie obrazów podczas Mail Merge

Podczas wykonywania operacji Mail Merge można wstawiać obrazy z bazy danych do dokumentu za pomocą specjalnych pól image Mail Merge. Pole image Mail Merge jest polem scalania o nazwie Image: MyFieldName.

Wstawianie obrazów z bazy danych

Podczas mail merge, gdy napotkane jest pole obraz Mail Merge w dokumencie, Zdarzenie FieldMergingCallback jest uruchamiane. Możesz odpowiedzieć na to zdarzenie, aby zwrócić nazwę pliku, strumień lub obiekt obrazu do silnika Mail Merge, aby można go było wstawić do dokumentu.

Poniższy przykład kodu pokazuje, jak wstawić obrazy zapisane w bazie danych BLOB pole do raportu:

// 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;
}
}

Ustaw właściwości obrazu podczas Mail Merge

Podczas scalania pola scalania obrazu czasami może być konieczne kontrolowanie różnych właściwości obrazu, takich jak WrapType.

Obecnie za pomocą ImageFieldMergingArgs można ustawić tylko odpowiednio właściwości szerokości lub wysokości obrazu. Aby rozwiązać ten problem, Aspose.Words udostępnia Właściwość Shape, która ułatwia uzyskanie pełnej kontroli nad wstawionym obrazem lub dowolnym innym kształtem.

Poniższy przykład kodu pokazuje, jak ustawić różne właściwości obrazu:

// 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;
}
}
}