From ad7971a86dcc7458521ed1fc1f7fb61e5e6181e1 Mon Sep 17 00:00:00 2001 From: SujithkumarSekar Date: Tue, 21 Jul 2026 20:15:59 +0530 Subject: [PATCH 1/2] Committing files --- .../Word-document/Compare-Word-documents.md | 159 +++++++++++------- .../Iterating-Word-document-elements.md | 63 +++---- .../Word-document/Merging-Word-documents.md | 44 +++-- .../NET/Word-document/Print-Word-documents.md | 26 +-- .../NET/Word-document/Split-Word-documents.md | 77 +++++---- .../NET/Working-with-Word-document.md | 58 ++++--- 6 files changed, 253 insertions(+), 174 deletions(-) diff --git a/Document-Processing/Word/Word-Library/NET/Word-document/Compare-Word-documents.md b/Document-Processing/Word/Word-Library/NET/Word-document/Compare-Word-documents.md index ea797ad22a..f2ef60b190 100644 --- a/Document-Processing/Word/Word-Library/NET/Word-document/Compare-Word-documents.md +++ b/Document-Processing/Word/Word-Library/NET/Word-document/Compare-Word-documents.md @@ -37,12 +37,15 @@ N> Refer to the appropriate tabs in the code snippets section: ***C# [Cross-plat {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Compare-Word-documents/Compare-two-Word-documents/.NET/Compare-Word-documents/Program.cs" %} -//Load the original document. +using Syncfusion.DocIO; +using Syncfusion.DocIO.DLS; + +// Load the original document. using (FileStream originalDocumentStreamPath = new FileStream("Data/OriginalDocument.docx", FileMode.Open, FileAccess.Read)) { using (WordDocument originalDocument = new WordDocument(originalDocumentStreamPath, FormatType.Docx)) { - //Load the revised document. + // Load the revised document. using (FileStream revisedDocumentStreamPath = new FileStream("Data/RevisedDocument.docx", FileMode.Open, FileAccess.Read)) { using (WordDocument revisedDocument = new WordDocument(revisedDocumentStreamPath, FormatType.Docx)) @@ -50,38 +53,48 @@ using (FileStream originalDocumentStreamPath = new FileStream("Data/OriginalDocu // Compare the original and revised Word documents. originalDocument.Compare(revisedDocument); - //Save the Word document to MemoryStream - MemoryStream stream = new MemoryStream(); - originalDocument.Save(stream, FormatType.Docx); + // Save the Word document to MemoryStream. + using (MemoryStream stream = new MemoryStream()) + { + originalDocument.Save(stream, FormatType.Docx); + // Save the stream to a file. + File.WriteAllBytes("Result.docx", stream.ToArray()); + } } - } - } + } + } } {% endhighlight %} {% highlight c# tabtitle="C# [Windows-specific]" %} -//Load the original document. +using Syncfusion.DocIO; +using Syncfusion.DocIO.DLS; + +// Load the original document. using (WordDocument originalDocument = new WordDocument("Data/OriginalDocument.docx", FormatType.Docx)) { - //Load the revised document. + // Load the revised document. using (WordDocument revisedDocument = new WordDocument("Data/RevisedDocument.docx", FormatType.Docx)) - { + { // Compare the original and revised Word documents. originalDocument.Compare(revisedDocument); - //Save the Word document. - originalDocument.Save("Result.docx"); + // Save the Word document. + originalDocument.Save("Result.docx"); } } {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} +Imports Syncfusion.DocIO +Imports Syncfusion.DocIO.DLS + ' Load the original document. Using originalDocument As New WordDocument("Data/OriginalDocument.docx", FormatType.Docx) ' Load the revised document. Using revisedDocument As New WordDocument("Data/RevisedDocument.docx", FormatType.Docx) - ' Compare the original document and revised documents. + ' Compare the original and revised Word documents. originalDocument.Compare(revisedDocument) ' Save the Word document. originalDocument.Save("Result.docx") @@ -97,61 +110,74 @@ You can download a complete working sample from [GitHub](https://github.com/Sync ## Set Author and Date -Compare the two Word documents by setting the author and date for revisions to identify the changes. In DocIO, the default setting for the "author" field is "Author", and the default setting for the "dateTime" field is the current time. +Compare the two Word documents by setting the author and date for revisions to identify the changes. In DocIO, the default author is "Author" and the default date/time is the current time. The following sample uses an overload of the [`Compare`](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WordDocument.html) method that accepts an author and date. The following code example shows how to set the author and date for revision while comparing two Word documents. {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Compare-Word-documents/Set-author-and-date/.NET/Program.cs" %} -//Load the original document. +using Syncfusion.DocIO; +using Syncfusion.DocIO.DLS; + +// Load the original document. using (FileStream originalDocumentStreamPath = new FileStream("Data/OriginalDocument.docx", FileMode.Open, FileAccess.Read)) { using (WordDocument originalDocument = new WordDocument(originalDocumentStreamPath, FormatType.Docx)) { - //Load the revised document. + // Load the revised document. using (FileStream revisedDocumentStreamPath = new FileStream("Data/RevisedDocument.docx", FileMode.Open, FileAccess.Read)) { using (WordDocument revisedDocument = new WordDocument(revisedDocumentStreamPath, FormatType.Docx)) { // Compare the original and revised Word documents. - originalDocument.Compare(revisedDocument,"Nancy Davolio", DateTime.Now.AddDays(-1)); + originalDocument.Compare(revisedDocument, "Nancy Davolio", DateTime.Now.AddDays(-1)); - //Save the Word document to MemoryStream - MemoryStream stream = new MemoryStream(); - originalDocument.Save(stream, FormatType.Docx); + // Save the Word document to MemoryStream. + using (MemoryStream stream = new MemoryStream()) + { + originalDocument.Save(stream, FormatType.Docx); + // Save the stream to a file. + File.WriteAllBytes("Result.docx", stream.ToArray()); + } } - } - } + } + } } {% endhighlight %} {% highlight c# tabtitle="C# [Windows-specific]" %} -//Load the original document. +using Syncfusion.DocIO; +using Syncfusion.DocIO.DLS; + +// Load the original document. using (WordDocument originalDocument = new WordDocument("Data/OriginalDocument.docx", FormatType.Docx)) { - //Load the revised document. + // Load the revised document. using (WordDocument revisedDocument = new WordDocument("Data/RevisedDocument.docx", FormatType.Docx)) - { - // Compare the original document and revised documents. - originalDocument.Compare(revisedDocument,"Nancy Davolio", DateTime.Now.AddDays(-1)); - //Save the Word document. - originalDocument.Save("Result.docx"); + { + // Compare the original and revised Word documents. + originalDocument.Compare(revisedDocument, "Nancy Davolio", DateTime.Now.AddDays(-1)); + // Save the Word document. + originalDocument.Save("Result.docx"); } } {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} -' Open the original Word document. -Using originalDocument As New WordDocument(originalFilePath, FormatType.Docx) - ' Open the revised Word document. - Using revisedDocument As New WordDocument(revisedFilePath, FormatType.Docx) - ' Compare the original document with the revised document. +Imports Syncfusion.DocIO +Imports Syncfusion.DocIO.DLS + +' Load the original document. +Using originalDocument As New WordDocument("Data/OriginalDocument.docx", FormatType.Docx) + ' Load the revised document. + Using revisedDocument As New WordDocument("Data/RevisedDocument.docx", FormatType.Docx) + ' Compare the original and revised Word documents. originalDocument.Compare(revisedDocument, "Nancy Davolio", DateTime.Now.AddDays(-1)) ' Save the Word document. - originalDocument.Save(resultFilePath) + originalDocument.Save("Result.docx") End Using End Using @@ -176,25 +202,30 @@ The following code example illustrates how to compare two Word documents by igno {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Compare-Word-documents/Ignore-format-changes/.NET/Ignore-format-changes/Program.cs" %} -//Load the original document -using (FileStream originalDocumentStreamPath = new FileStream("OriginalDocument.docx", FileMode.Open, FileAccess.Read)) +using Syncfusion.DocIO; +using Syncfusion.DocIO.DLS; + +// Load the original document. +using (FileStream originalDocumentStreamPath = new FileStream("Data/OriginalDocument.docx", FileMode.Open, FileAccess.Read)) { using (WordDocument originalDocument = new WordDocument(originalDocumentStreamPath, FormatType.Docx)) { - //Load the revised document - using (FileStream revisedDocumentStreamPath = new FileStream("RevisedDocument.docx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) + // Load the revised document. + using (FileStream revisedDocumentStreamPath = new FileStream("Data/RevisedDocument.docx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { - using (WordDocument revisedDocument = new WordDocument(revisedDocumentStreamPath, FormatType.Automatic)) + using (WordDocument revisedDocument = new WordDocument(revisedDocumentStreamPath, FormatType.Docx)) { - //Set the Comparison option to detect format changes, whether to detect format changes while comparing two Word documents. + // Set whether to detect format changes while comparing two Word documents. ComparisonOptions compareOptions = new ComparisonOptions(); compareOptions.DetectFormatChanges = false; - //Compare the original document with the revised document + // Compare the original and revised Word documents. originalDocument.Compare(revisedDocument, "Syncfusion", DateTime.Now, compareOptions); - //Save the Word document to MemoryStream + // Save the Word document to MemoryStream. using (MemoryStream stream = new MemoryStream()) { originalDocument.Save(stream, FormatType.Docx); + // Save the stream to a file. + File.WriteAllBytes("Result.docx", stream.ToArray()); } } } @@ -204,36 +235,42 @@ using (FileStream originalDocumentStreamPath = new FileStream("OriginalDocument. {% endhighlight %} {% highlight c# tabtitle="C# [Windows-specific]" %} -//Load the original document -using (WordDocument originalDocument = new WordDocument("OriginalDocument.docx")) +using Syncfusion.DocIO; +using Syncfusion.DocIO.DLS; + +// Load the original document. +using (WordDocument originalDocument = new WordDocument("Data/OriginalDocument.docx", FormatType.Docx)) { - //Load the revised document - using (WordDocument revisedDocument = new WordDocument("RevisedDocument.docx")) + // Load the revised document. + using (WordDocument revisedDocument = new WordDocument("Data/RevisedDocument.docx", FormatType.Docx)) { - //Set the Comparison option detect format changes, whether to detect format changes while comparing two Word documents. + // Set whether to detect format changes while comparing two Word documents. ComparisonOptions compareOptions = new ComparisonOptions(); compareOptions.DetectFormatChanges = false; - //Compare the original document with the revised document + // Compare the original and revised Word documents. originalDocument.Compare(revisedDocument, "Syncfusion", DateTime.Now, compareOptions); - //Save the Word document. - originalDocument.Save(output); - } -} + // Save the Word document. + originalDocument.Save("Result.docx"); + } +} {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} -'Load the original document -Using originalDocument As New WordDocument("OriginalDocument.docx") - 'Load the revised document - Using revisedDocument As New WordDocument("RevisedDocument.docx") - 'Set the Comparison option to detect format changes +Imports Syncfusion.DocIO +Imports Syncfusion.DocIO.DLS + +' Load the original document. +Using originalDocument As New WordDocument("Data/OriginalDocument.docx", FormatType.Docx) + ' Load the revised document. + Using revisedDocument As New WordDocument("Data/RevisedDocument.docx", FormatType.Docx) + ' Set whether to detect format changes while comparing two Word documents. Dim compareOptions As New ComparisonOptions() compareOptions.DetectFormatChanges = False - 'Compare the original document with the revised document + ' Compare the original and revised Word documents. originalDocument.Compare(revisedDocument, "Syncfusion", DateTime.Now, compareOptions) - 'Save the Word document - originalDocument.Save(output) + ' Save the Word document. + originalDocument.Save("Result.docx") End Using End Using diff --git a/Document-Processing/Word/Word-Library/NET/Word-document/Iterating-Word-document-elements.md b/Document-Processing/Word/Word-Library/NET/Word-document/Iterating-Word-document-elements.md index c3f21a3288..6a91c9e807 100644 --- a/Document-Processing/Word/Word-Library/NET/Word-document/Iterating-Word-document-elements.md +++ b/Document-Processing/Word/Word-Library/NET/Word-document/Iterating-Word-document-elements.md @@ -7,7 +7,7 @@ documentation: UG --- # Iterating Word document elements -The following are the important points to be remembered while iterating the document elements +The following are the important points to be remembered while iterating the document elements. * Document consists of one or more sections. * Section contains the contents present in Headers, Footers and main document through the instances of [WTextBody](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WTextBody.html). @@ -15,7 +15,7 @@ The following are the important points to be remembered while iterating the docu ## Remove paragraph with style -The following code example shows how to iterate throughout the Word document and remove the paragraph with a particular style. +The following code example shows how to iterate throughout the Word document and remove the paragraph with a particular style. The sample assumes that the `Template.docx` file contains a paragraph style named "MyStyle". Refer to [create and apply paragraph styles](https://help.syncfusion.com/document-processing/word/word-library/net/create-and-apply-paragraph-style) for adding styles to a document. N> Refer to the appropriate tabs in the code snippets section: ***C# [Cross-platform]*** for ASP.NET Core, Blazor, Xamarin, UWP, .NET MAUI, and WinUI; ***C# [Windows-specific]*** for WinForms and WPF; ***VB.NET [Windows-specific]*** for VB.NET applications. @@ -28,7 +28,7 @@ using (WordDocument document = new WordDocument(fileStreamPath, FormatType.Autom { foreach (WSection section in document.Sections) { - //Accesses the Body of section where all the contents in document are apart + //Accesses the Body of section where all the contents in document reside WTextBody sectionBody = section.Body; IterateTextBody(sectionBody); WHeadersFooters headersFooters = section.HeadersFooters; @@ -41,6 +41,8 @@ using (WordDocument document = new WordDocument(fileStreamPath, FormatType.Autom document.Save(stream, FormatType.Docx); //Closes the Word document document.Close(); + //Saves the MemoryStream to a file + File.WriteAllBytes("Result.docx", stream.ToArray()); } {% endhighlight %} @@ -50,7 +52,7 @@ WordDocument document = new WordDocument("Template.docx"); //Processes the body contents for each section in the Word document foreach (WSection section in document.Sections) { - //Accesses the Body of section where all the contents in document are apart + //Accesses the Body of section where all the contents in document reside WTextBody sectionBody = section.Body; IterateTextBody(sectionBody); WHeadersFooters headersFooters = section.HeadersFooters; @@ -69,7 +71,7 @@ document.Close(); Dim document As New WordDocument("Template.docx") 'Processes the body contents for each section in the Word document For Each section As WSection In document.Sections - 'Accesses the Body of section where all the contents in document are apart + 'Accesses the Body of section where all the contents in document reside Dim sectionBody As WTextBody = section.Body IterateTextBody(sectionBody) Dim headersFooters As WHeadersFooters = section.HeadersFooters @@ -118,7 +120,7 @@ private static void IterateTextBody(WTextBody textBody) break; case EntityType.BlockContentControl: BlockContentControl blockContentControl = bodyItemEntity as BlockContentControl; - //Iterates to the body items of Block Content Control. + //Iterates through the body items of Block Content Control. IterateTextBody(blockContentControl.TextBody); break; } @@ -155,7 +157,7 @@ private static void IterateTextBody(WTextBody textBody) break; case EntityType.BlockContentControl: BlockContentControl blockContentControl = bodyItemEntity as BlockContentControl; - //Iterates to the body items of Block Content Control. + //Iterates through the body items of Block Content Control. IterateTextBody(blockContentControl.TextBody); break; } @@ -171,7 +173,7 @@ For i As Integer = 0 To textBody.ChildEntities.Count - 1 'Accesses the body items (should be either paragraph, table or block content control) as IEntity Dim bodyItemEntity As IEntity = textBody.ChildEntities(i) 'A Text body has 3 types of elements - Paragraph, Table and Block Content Control - 'decide the element type using EntityType + 'Determines the element type using EntityType Select Case bodyItemEntity.EntityType Case EntityType.Paragraph Dim paragraph As WParagraph = TryCast(bodyItemEntity, WParagraph) @@ -188,7 +190,7 @@ For i As Integer = 0 To textBody.ChildEntities.Count - 1 Exit Select Case EntityType.BlockContentControl Dim BlockContentControl As BlockContentControl = TryCast(bodyItemEntity, BlockContentControl) - 'Iterates to the body items of Block Content Control. + 'Iterates through the body items of Block Content Control. IterateTextBody(BlockContentControl.TextBody) Exit Select End Select @@ -256,7 +258,7 @@ You can download a complete working sample from [GitHub](https://github.com/Sync ## Modify Hyperlink Uri -The following code example shows how to iterate throughout the paragraph and modify the hyperlink ([Hyperlink](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.Hyperlink.html)) Uri and specific text ([WTextRange](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.Hyperlink.html)) with another. +The following code example shows how to iterate throughout the paragraph and modify the hyperlink ([Hyperlink](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.Hyperlink.html)) Uri and specific text ([WTextRange](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WTextRange.html)) with another. The sample also replaces the text "Andrew" with "Fuller" and updates any hyperlink whose display text is "HTML" to point to `http://www.w3schools.com/`. These values are sample-specific; update them to suit your document. {% tabs %} @@ -267,7 +269,7 @@ using (WordDocument document = new WordDocument(fileStreamPath, FormatType.Autom { foreach (WSection section in document.Sections) { - //Accesses the Body of section where all the contents in document are apart + //Accesses the Body of section where all the contents in document reside WTextBody sectionBody = section.Body; IterateTextBody(sectionBody); WHeadersFooters headersFooters = section.HeadersFooters; @@ -280,6 +282,8 @@ using (WordDocument document = new WordDocument(fileStreamPath, FormatType.Autom document.Save(stream, FormatType.Docx); //Closes the Word document document.Close(); + //Saves the MemoryStream to a file + File.WriteAllBytes("Result.docx", stream.ToArray()); } {% endhighlight %} @@ -289,11 +293,11 @@ WordDocument document = new WordDocument("Template.docx"); //Processes the body contents for each section in the Word document foreach (WSection section in document.Sections) { - //Accesses the Body of section where all the contents in document are apart + //Accesses the Body of section where all the contents in document reside WTextBody sectionBody = section.Body; IterateTextBody(sectionBody); WHeadersFooters headersFooters = section.HeadersFooters; - //consider that OddHeader & OddFooter are applied to this document + //Consider that OddHeader and OddFooter are applied to this document //Iterates through the TextBody of OddHeader and OddFooter IterateTextBody(headersFooters.OddHeader); IterateTextBody(headersFooters.OddFooter); @@ -307,12 +311,13 @@ document.Close(); Dim document As New WordDocument("Template.docx") 'Processes the body contents for each section in the Word document For Each section As WSection In document.Sections - 'Accesses the Body of section where all the contents in document are apart + 'Accesses the Body of section where all the contents in document reside Dim sectionBody As WTextBody = section.Body IterateTextBody(sectionBody) Dim headersFooters As WHeadersFooters = section.HeadersFooters - 'Considers that OddHeader and OddFooter are applied to this document - 'Iterates through the TextBody of OddHeader and OddFooterIterateTextBody(headersFooters.OddHeader) + 'Assume that OddHeader and OddFooter are applied to this document + 'Iterates through the TextBody of OddHeader and OddFooter + IterateTextBody(headersFooters.OddHeader) IterateTextBody(headersFooters.OddFooter) Next 'Saves and closes the document instance @@ -352,7 +357,7 @@ private static void IterateTextBody(WTextBody textBody) break; case EntityType.BlockContentControl: BlockContentControl blockContentControl = bodyItemEntity as BlockContentControl; - //Iterates to the body items of Block Content Control. + //Iterates through the body items of Block Content Control. IterateTextBody(blockContentControl.TextBody); break; } @@ -386,7 +391,7 @@ private static void IterateTextBody(WTextBody textBody) break; case EntityType.BlockContentControl: BlockContentControl blockContentControl = bodyItemEntity as BlockContentControl; - //Iterates to the body items of Block Content Control. + //Iterates through the body items of Block Content Control. IterateTextBody(blockContentControl.TextBody); break; } @@ -417,7 +422,7 @@ For i As Integer = 0 To textBody.ChildEntities.Count - 1 Exit Select Case EntityType.BlockContentControl Dim BlockContentControl As BlockContentControl = TryCast(bodyItemEntity, BlockContentControl) - 'Iterates to the body items of Block Content Control. + 'Iterates through the body items of Block Content Control. IterateTextBody(BlockContentControl.TextBody) Exit Select End Select @@ -517,17 +522,17 @@ private static void IterateParagraph(ParagraphItemCollection paraItems) } break; case EntityType.TextBox: - //Iterates to the body items of textbox. + //Iterates through the body items of textbox. WTextBox textBox = entity as WTextBox; IterateTextBody(textBox.TextBoxBody); break; case EntityType.Shape: - //Iterates to the body items of shape. + //Iterates through the body items of shape. Shape shape = entity as Shape; IterateTextBody(shape.TextBody); break; case EntityType.InlineContentControl: - //Iterates to the paragraph items of inline content control. + //Iterates through the paragraph items of inline content control. InlineContentControl inlineContentControl = entity as InlineContentControl; IterateParagraph(inlineContentControl.ParagraphItems); break; @@ -568,17 +573,17 @@ private static void IterateParagraph(ParagraphItemCollection paraItems) } break; case EntityType.TextBox: - //Iterates to the body items of textbox. + //Iterates through the body items of textbox. WTextBox textBox = entity as WTextBox; IterateTextBody(textBox.TextBoxBody); break; case EntityType.Shape: - //Iterates to the body items of shape. + //Iterates through the body items of shape. Shape shape = entity as Shape; IterateTextBody(shape.TextBody); break; case EntityType.InlineContentControl: - //Iterates to the paragraph items of inline content control. + //Iterates through the paragraph items of inline content control. InlineContentControl inlineContentControl = entity as InlineContentControl; IterateParagraph(inlineContentControl.ParagraphItems); break; @@ -613,17 +618,17 @@ For i As Integer = 0 To paraItems.Count - 1 End If Exit Select Case EntityType.TextBox - 'Iterates to the body items of textbox. + 'Iterates through the body items of textbox. Dim textBox As WTextBox = TryCast(entity, WTextBox) IterateTextBody(textBox.TextBoxBody) Exit Select Case EntityType.Shape - 'Iterates to the body items of shape. + 'Iterates through the body items of shape. Dim shape As Shape = TryCast(entity, Shape) IterateTextBody(shape.TextBody) Exit Select Case EntityType.InlineContentControl - 'Iterates to the paragraph items of inline content control. + 'Iterates through the paragraph items of inline content control. Dim inlineContentControl As InlineContentControl = TryCast(entity, InlineContentControl) IterateParagraph(inlineContentControl.ParagraphItems) Exit Select @@ -636,8 +641,6 @@ End Sub You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Word-document/Iterate-document-elements). -T> If you wish to find an item in a Word document rather than iterating through each element one by one, you can use [finding the item functionality](https://help.syncfusion.com/document-processing/word/word-library/net/find-item-in-word-document) to achieve it. - ## See Also * [Why it is not possible to access the Word document contents page by page?](https://support.syncfusion.com/kb/article/18815/why-it-is-not-possible-to-access-the-word-document-contents-page-by-page) diff --git a/Document-Processing/Word/Word-Library/NET/Word-document/Merging-Word-documents.md b/Document-Processing/Word/Word-Library/NET/Word-document/Merging-Word-documents.md index 21b8ea0ad2..8c52648025 100644 --- a/Document-Processing/Word/Word-Library/NET/Word-document/Merging-Word-documents.md +++ b/Document-Processing/Word/Word-Library/NET/Word-document/Merging-Word-documents.md @@ -7,11 +7,13 @@ documentation: UG --- # Merging Word documents -You can merge multiple Word documents into single Word document by using DocIO’s capability of importing contents from one document to another. The imported contents are appended at the end of document. +You can merge multiple Word documents into a single Word document by using DocIO’s capability of importing contents from one document to another. The imported contents are appended at the end of the document. + +By default, the imported contents start on a new page. You can also merge the contents on the same page by adjusting the source document’s first section break, as shown in the following sections. ## Assemblies and NuGet packages required -Refer to the following links for assemblies and NuGet packages required based on platforms to merge Word documents using the [.NET Word Library](https://www.syncfusion.com/document-sdk/net-word-library) (DocIO). +Refer to the following links for the assemblies and NuGet packages required for each platform to merge Word documents using the [.NET Word Library](https://www.syncfusion.com/document-sdk/net-word-library) (DocIO). * [Merge Word documents assemblies](https://help.syncfusion.com/document-processing/word/word-library/net/assemblies-required) * [Merge Word documents NuGet packages](https://help.syncfusion.com/document-processing/word/word-library/net/nuget-packages-required) @@ -19,25 +21,25 @@ Refer to the following links for assemblies and NuGet packages required based on To quickly start merging Word documents, please check out this video: {% youtube "https://www.youtube.com/watch?v=atOSwzidmdw" %} -## Merge document in new page +## Merging documents in a new page -The following code example illustrates how to import the contents from source document into destination document where the contents are appended. +The following code example illustrates how to import the contents from a source document into a destination document where the contents are appended. N> Refer to the appropriate tabs in the code snippets section: ***C# [Cross-platform]*** for ASP.NET Core, Blazor, Xamarin, UWP, .NET MAUI, and WinUI; ***C# [Windows-specific]*** for WinForms and WPF; ***VB.NET [Windows-specific]*** for VB.NET applications. {% tabs %} -{% highlight C# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Word-document/Merge-documents-in-new-page/.NET/Merge-documents-in-new-page/Program.cs" %} +{% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Word-document/Merge-documents-in-new-page/.NET/Merge-documents-in-new-page/Program.cs" %} FileStream sourceStreamPath = new FileStream(sourceFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); FileStream destinationStreamPath = new FileStream(destinationFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); -//Opens an source document from file system through constructor of WordDocument class +//Opens a source document from file system through constructor of WordDocument class using (WordDocument document = new WordDocument(sourceStreamPath, FormatType.Automatic)) { //Opens the destination document WordDocument destinationDocument = new WordDocument(destinationStreamPath, FormatType.Docx); //Imports the contents of source document at the end of destination document destinationDocument.ImportContent(document, ImportOptions.UseDestinationStyles); - //Saves and closes the destination document to MemoryStream + //Saves and closes the destination document to a MemoryStream MemoryStream stream = new MemoryStream(); destinationDocument.Save(stream, FormatType.Docx); destinationDocument.Close(); @@ -54,7 +56,7 @@ WordDocument destinationDocument = new WordDocument(targetFileName); destinationDocument.ImportContent(sourceDocument, ImportOptions.UseDestinationStyles); //Saves the destination document destinationDocument.Save(outputFileName, FormatType.Docx); -//closes the document instances +//Closes the document instances sourceDocument.Close(); destinationDocument.Close(); {% endhighlight %} @@ -68,7 +70,7 @@ Dim destinationDocument As New WordDocument(targetFileName) destinationDocument.ImportContent(sourceDocument, ImportOptions.UseDestinationStyles) 'Saves the destination document destinationDocument.Save(outputFileName, FormatType.Docx) -'closes the document instances +'Closes the document instances sourceDocument.Close() destinationDocument.Close() {% endhighlight %} @@ -79,25 +81,29 @@ You can download a complete working sample from [GitHub](https://github.com/Sync In the resultant document, the imported contents start from a new page followed by existing contents in a destination document. This is the default behavior. -## Merge document in same page +## Merging documents on the same page + +When your requirement is to append the contents on the same page instead of starting from a new page, you need to set the break code of the first section of the source document as [NoBreak](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.SectionBreakCode.html). The following code example illustrates how to import the contents on the same page. -When your requirement is to append the contents from the same page instead of starting from a new page, you need to set the break code of first section of Source document as [NoBreak](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.SectionBreakCode.html). The following code example illustrates the importing contents from the same page. +N> For multi-section source documents, only the first section's break code controls the page break behavior of the imported content. + +N> Refer to the appropriate tabs in the code snippets section: ***C# [Cross-platform]*** for ASP.NET Core, Blazor, Xamarin, UWP, .NET MAUI, and WinUI; ***C# [Windows-specific]*** for WinForms and WPF; ***VB.NET [Windows-specific]*** for VB.NET applications. {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Word-document/Merge-documents-in-same-page/.NET/Merge-documents-in-same-page/Program.cs" %} FileStream sourceStreamPath = new FileStream(sourceFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); FileStream destinationStreamPath = new FileStream(destinationFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); -//Opens an source document from file system through constructor of WordDocument class +//Opens a source document from file system through constructor of WordDocument class using (WordDocument document = new WordDocument(sourceStreamPath, FormatType.Automatic)) { //Opens the destination document WordDocument destinationDocument = new WordDocument(destinationStreamPath, FormatType.Docx); - //Sets the break-code of First section of source document as NoBreak to avoid imported from a new page + //Sets the break code of the first section of the source document as NoBreak to avoid importing from a new page document.Sections[0].BreakCode = SectionBreakCode.NoBreak; //Imports the contents of source document at the end of destination document destinationDocument.ImportContent(document, ImportOptions.UseDestinationStyles); - //Saves and closes the destination document to MemoryStream + //Saves and closes the destination document to a MemoryStream MemoryStream stream = new MemoryStream(); destinationDocument.Save(stream, FormatType.Docx); destinationDocument.Close(); @@ -110,7 +116,7 @@ using (WordDocument document = new WordDocument(sourceStreamPath, FormatType.Aut WordDocument sourceDocument = new WordDocument(sourceFileName); //Opens the destination document WordDocument destinationDocument = new WordDocument(targetFileName); -//Sets the break-code of First section of source document as NoBreak to avoid imported from a new page +//Sets the break code of the first section of the source document as NoBreak to avoid importing from a new page sourceDocument.Sections[0].BreakCode = SectionBreakCode.NoBreak; //Imports the contents of source document at the end of destination document destinationDocument.ImportContent(sourceDocument, ImportOptions.UseDestinationStyles); @@ -126,7 +132,7 @@ destinationDocument.Close(); Dim sourceDocument As New WordDocument(sourceFileName) 'Opens the destination document Dim destinationDocument As New WordDocument(targetFileName) -'Sets the break-code of first section of source document as NoBreak to avoid imported from a new page +'Sets the break code of the first section of the source document as NoBreak to avoid importing from a new page sourceDocument.Sections(0).BreakCode = SectionBreakCode.NoBreak 'Imports the contents of source document at the end of destination document destinationDocument.ImportContent(sourceDocument, ImportOptions.UseDestinationStyles) @@ -141,7 +147,7 @@ destinationDocument.Close() You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Word-document/Merge-documents-in-same-page). -## Maintain Imported List style information +## Maintain imported list style information The following code example shows how to maintain information about imported list styles in a Word document while cloning and merging multiple Word documents. @@ -228,6 +234,10 @@ destinationDocument.Close() {% endtabs %} +You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Word-document/Maintain-Imported-List-Style-Information). + +N> For production use, register a Syncfusion license before merging Word documents. Refer to the [licensing registration guide](https://help.syncfusion.com/document-processing/word/licensing/how-to-register-in-an-application) for details. + ## See Also * [How to merge multiple Word documents in C#, VB.NET](https://support.syncfusion.com/kb/article/11499/how-to-merge-multiple-word-documents-in-c-vb-net) diff --git a/Document-Processing/Word/Word-Library/NET/Word-document/Print-Word-documents.md b/Document-Processing/Word/Word-Library/NET/Word-document/Print-Word-documents.md index c485556971..2ce5f61173 100644 --- a/Document-Processing/Word/Word-Library/NET/Word-document/Print-Word-documents.md +++ b/Document-Processing/Word/Word-Library/NET/Word-document/Print-Word-documents.md @@ -1,6 +1,6 @@ --- title: Print Word documents in C# | DocIO | Syncfusion -description: Learn how to print the Word documents into one using .NET Word (DocIO) library without Microsoft Word or interop dependencies. +description: Learn how to print Word documents using the .NET Word (DocIO) library without Microsoft Word or interop dependencies. platform: document-processing control: DocIO documentation: UG @@ -9,7 +9,7 @@ documentation: UG You can print a Word document by utilizing DocIO’s capability to convert the document into images and .NET framework’s [PrintDocument](https://learn.microsoft.com/en-us/dotnet/api/system.drawing.printing.printdocument?view=dotnet-plat-ext-7.0&viewFallbackFrom=net-5.0) class -Initially you have to render the pages as images as shown below +Initially you have to render the pages of the Word document as images, as shown below. N> Refer to the appropriate tabs in the code snippets section: ***C# [Windows-specific]*** for WinForms and WPF; ***VB.NET [Windows-specific]*** for VB.NET applications. @@ -20,7 +20,7 @@ N> Refer to the appropriate tabs in the code snippets section: ***C# [Windows-sp WordDocument document = new WordDocument((string)this.textBox.Tag); //Renders the Word document as image Image[] images = document.RenderAsImages(ImageType.Metafile); -//Closes the Word Document +//Closes the Word document document.Close(); {% endhighlight %} @@ -29,15 +29,19 @@ document.Close(); Dim document As New WordDocument(DirectCast(Me.textBox.Tag, String)) 'Renders the Word document as image Dim images As Image() = document.RenderAsImages(ImageType.Metafile) -'Closes the Word Document +'Closes the Word document document.Close() {% endhighlight %} {% endtabs %} -You can specify the printer settings and page settings through the [PrintDocument](https://docs.microsoft.com/en-us/dotnet/api/system.drawing.printing.printdocument?view=net-5.0) class. The [PrintDocument.PrintPage](https://learn.microsoft.com/en-us/dotnet/api/system.drawing.printing.printdocument?view=dotnet-plat-ext-7.0&viewFallbackFrom=net-5.0) event should be handled to layout the document for printing. +## Configuring print settings -The following code example demonstrates how to print the Word document pages that have been rendered as an image: +You can specify the printer settings and page settings through the [PrintDocument](https://learn.microsoft.com/dotnet/api/system.drawing.printing.printdocument) class. The [PrintDocument.PrintPage](https://learn.microsoft.com/dotnet/api/system.drawing.printing.printdocument.printpage) event should be handled to layout the document for printing. The following code example demonstrates how to print the Word document pages that have been rendered as an image, using the `images` array produced in the previous snippet. + +N> Refer to the appropriate tabs in the code snippets section: ***C# [Windows-specific]*** for WinForms and WPF; ***VB.NET [Windows-specific]*** for VB.NET applications. + +N> `startPageIndex` must be declared as a class-level integer field (initialize it to `0`). The snippet updates it based on the page range chosen in the print dialog. {% tabs %} @@ -66,7 +70,7 @@ if (printDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) endPageIndex = printDialog.PrinterSettings.ToPage; //Hooks the PrintPage event to handle the drawing pages for printing printDialog.Document.PrintPage += new PrintPageEventHandler(PrintPageMethod); - //Print the document + //Prints the document printDialog.Document.Print(); } } @@ -87,14 +91,14 @@ printDialog.PrinterSettings.FromPage = 1 printDialog.PrinterSettings.ToPage = images.Length 'Opens the print dialog box If printDialog.ShowDialog() = System.Windows.Forms.DialogResult.OK Then - 'Checks whether the selected page range is valid or not + 'Checks whether the selected page range is valid If printDialog.PrinterSettings.FromPage > 0 AndAlso printDialog.PrinterSettings.ToPage <= images.Length Then 'Updates the start page of the document to print startPageIndex = printDialog.PrinterSettings.FromPage - 1 'Updates the end page of the document to print endPageIndex = printDialog.PrinterSettings.ToPage 'Hooks the PrintPage event to handle the drawing pages for printing - printDialog.Document.PrintPage += New PrintPageEventHandler(PrintPageMethod) + AddHandler printDialog.Document.PrintPage, AddressOf PrintPageMethod 'Prints the document printDialog.Document.Print() End If @@ -184,6 +188,8 @@ End Sub You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Word-document/Print-Word-document). +N> If `RenderAsImages` returns an empty array (for example, an empty document), skip printing and check the input document. Ensure the rendered array length is validated before configuring the page range. + ## See Also -* [How to do silent printing to print the Word document by rendering document pages as Image using Essential® DocIO](https://support.syncfusion.com/kb/article/4546/how-to-do-silent-printing-to-print-the-word-document-by-rendering-document-pages-as-image) \ No newline at end of file +* [How to do silent printing to print the Word document by rendering document pages as image using DocIO](https://support.syncfusion.com/kb/article/4546/how-to-do-silent-printing-to-print-the-word-document-by-rendering-document-pages-as-image) \ No newline at end of file diff --git a/Document-Processing/Word/Word-Library/NET/Word-document/Split-Word-documents.md b/Document-Processing/Word/Word-Library/NET/Word-document/Split-Word-documents.md index 7324de4a34..dda0626926 100644 --- a/Document-Processing/Word/Word-Library/NET/Word-document/Split-Word-documents.md +++ b/Document-Processing/Word/Word-Library/NET/Word-document/Split-Word-documents.md @@ -7,9 +7,9 @@ documentation: UG --- # Split Word documents -The [.NET Word Library](https://www.syncfusion.com/document-sdk/net-word-library) allows you to split the large Word document into number of smaller word documents by the sections, headings, bookmarks, and placeholder text in programmatically. +The [.NET Word Library](https://www.syncfusion.com/document-sdk/net-word-library) allows you to split a large Word document into a number of smaller Word documents by section, heading, bookmark, and placeholder text programmatically. -By using this feature, you can be able to split/extract the necessary parts from the original document for further processing. +By using this feature, you can split/extract the necessary parts from the original document for further processing. You can save the resultant document as a Word document (DOCX, WordML, DOC), PDF, image, HTML, RTF, and more. @@ -18,14 +18,18 @@ To quickly start splitting Word documents, please check out this video: ## Assemblies and NuGet packages required -Refer to the following links for assemblies and NuGet packages required based on platforms to split Word documents using the [.NET Word Library](https://www.syncfusion.com/document-sdk/net-word-library) (DocIO). +Refer to the following links for the assemblies and NuGet packages required for each platform to split Word documents using the [.NET Word Library](https://www.syncfusion.com/document-sdk/net-word-library) (DocIO). * [Split Word documents assemblies](https://help.syncfusion.com/document-processing/word/word-library/net/assemblies-required) * [Split Word documents NuGet packages](https://help.syncfusion.com/document-processing/word/word-library/net/nuget-packages-required) +N> For production use, register a Syncfusion license before splitting Word documents. Refer to the [licensing registration guide](https://help.syncfusion.com/document-processing/word/licensing/how-to-register-in-an-application) for details. + +N> The code samples use the namespaces `Syncfusion.DocIO.DLS`, `System.IO`, and `System.Text.RegularExpressions`. Add the corresponding `using`/`Imports` directives for these namespaces before running the samples. + ## Split by Section -The following code example illustrates how to split the Word document by sections. +The following code example illustrates how to split the Word document by section. N> Refer to the appropriate tabs in the code snippets section: ***C# [Cross-platform]*** for ASP.NET Core, Blazor, Xamarin, UWP, .NET MAUI, and WinUI; ***C# [Windows-specific]*** for WinForms and WPF; ***VB.NET [Windows-specific]*** for VB.NET applications. @@ -33,8 +37,8 @@ N> Refer to the appropriate tabs in the code snippets section: ***C# [Cross-plat {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Word-document/Split-by-section/.NET/Split-by-section/Program.cs" %} FileStream fileStreamPath = new FileStream("Template.docx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); -//Load the template document as stream -using(WordDocument document = new WordDocument(fileStreamPath, FormatType.Docx)) +//Load the template document as a stream +using (WordDocument document = new WordDocument(fileStreamPath, FormatType.Docx)) { //Iterate each section from Word document for (int i = 0; i < document.Sections.Count; i++) @@ -43,11 +47,13 @@ using(WordDocument document = new WordDocument(fileStreamPath, FormatType.Docx)) WordDocument newDocument = new WordDocument(); //Add cloned section into new Word document newDocument.Sections.Add(document.Sections[i].Clone()); - //Saves the Word document to MemoryStream - FileStream outputStream = new FileStream("Section" + i + ".docx", FileMode.OpenOrCreate, FileAccess.ReadWrite); - newDocument.Save(outputStream, FormatType.Docx); - //Closes the document - newDocument.Close(); + //Saves the Word document to a file stream + using (FileStream outputStream = new FileStream("Section" + i + ".docx", FileMode.OpenOrCreate, FileAccess.ReadWrite)) + { + newDocument.Save(outputStream, FormatType.Docx); + //Closes the document + newDocument.Close(); + } } } {% endhighlight %} @@ -63,7 +69,7 @@ using (WordDocument document = new WordDocument(@"Template.docx")) WordDocument newDocument = new WordDocument(); //Add cloned section into new Word document newDocument.Sections.Add(document.Sections[i].Clone()); - //Save and close the new Word documet + //Save and close the new Word document newDocument.Save("Section" + i + ".docx"); newDocument.Close(); } @@ -90,7 +96,7 @@ End Using You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Word-document/Split-by-section). -## Split by Headings +## Split by Heading The following code example illustrates how to split the Word document by using headings. @@ -99,13 +105,13 @@ The following code example illustrates how to split the Word document by using h {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Word-document/Split-by-heading/.NET/Split-by-heading/Program.cs" %} using (FileStream inputStream = new FileStream("Template.docx", FileMode.Open, FileAccess.Read)) { - //Load the template document as stream + //Load the template document as a stream using (WordDocument document = new WordDocument(inputStream, FormatType.Docx)) { WordDocument newDocument = null; WSection newSection = null; int headingIndex = 0; - /Iterate each section in the Word document. + //Iterate each section in the Word document. foreach (WSection section in document.Sections) { // Clone the section and add into new document. @@ -154,7 +160,7 @@ using (FileStream inputStream = new FileStream("Template.docx", FileMode.Open, F private static WSection AddSection(WordDocument newDocument, WSection section) { - //Create new session based on original document + //Create a new section based on the original document WSection newSection = section.Clone(); newSection.Body.ChildEntities.Clear(); //Remove the first page header. @@ -200,8 +206,8 @@ using (WordDocument doc = new WordDocument("Template.docx")) WordDocument newDocument = null; WSection newSection = null; int headingIndex = 0; - /Iterate each section in the Word document. - foreach (WSection section in document.Sections) + //Iterate each section in the Word document. + foreach (WSection section in doc.Sections) { // Clone the section and add into new document. if (newDocument != null) @@ -248,7 +254,7 @@ using (WordDocument doc = new WordDocument("Template.docx")) private static WSection AddSection(WordDocument newDocument, WSection section) { - //Create new session based on original document + //Create a new section based on the original document WSection newSection = section.Clone(); newSection.Body.ChildEntities.Clear(); //Remove the first page header. @@ -276,7 +282,7 @@ private static void AddEntity(WSection newSection, Entity entity) private static void SaveWordDocument(WordDocument newDocument, string fileName) { - //Save file stream as Word document + //Save the new Word document newDocument.Save(fileName, FormatType.Docx); //Closes the document newDocument.Close(); @@ -291,7 +297,7 @@ Using doc As WordDocument = New WordDocument("Template.docx") Dim newSection As WSection = Nothing Dim headingIndex = 0 'Iterate each section in the Word document. - For Each section As WSection In document.Sections + For Each section As WSection In doc.Sections ' Clone the section and add into new document. If newDocument IsNot Nothing Then newSection = AddSection(newDocument, section) 'Iterate each child entity in the Word document. @@ -302,7 +308,7 @@ Using doc As WordDocument = New WordDocument("Template.docx") Dim paragraph As WParagraph = TryCast(item, WParagraph) 'If paragraph has Heading 1 style, then save the traversed content as separate document. 'And create new document for new heading content. - If paragraph.StyleName Is "Heading 1" Then + If paragraph.StyleName = "Heading 1" Then If newDocument IsNot Nothing Then 'Saves the Word document Dim fileName As String = "Document" & (headingIndex + 1).ToString() & ".docx" @@ -359,7 +365,11 @@ You can download a complete working sample from [GitHub](https://github.com/Sync ## Split by Bookmark -The following code example illustrates how to split the Word document using bookmarks. +The following code example illustrates how to split the Word document using bookmarks. The [`BookmarksNavigator.MoveToBookmark`](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BookmarksNavigator.html) API moves the virtual cursor to a bookmark, and [`GetContent`](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BookmarksNavigator.html) returns the bookmark range as a `WordDocumentPart`; calling `WordDocumentPart.GetAsWordDocument()` produces a standalone `WordDocument` containing the bookmark's contents. + +N> Refer to the appropriate tabs in the code snippets section: ***C# [Cross-platform]*** for ASP.NET Core, Blazor, Xamarin, UWP, .NET MAUI, and WinUI; ***C# [Windows-specific]*** for WinForms and WPF; ***VB.NET [Windows-specific]*** for VB.NET applications. + +N> If a bookmark name contains characters that are invalid in file names (for example, `\`, `/`, `:`, `*`, `?`, `"`, `<`, `>`, `|`), the `Save` call will throw. Sanitize the bookmark name before using it as a file name. {% tabs %} @@ -374,7 +384,7 @@ using (WordDocument document = new WordDocument(fileStreamPath, FormatType.Docx) //Iterate each bookmark in Word document. foreach (Bookmark bookmark in bookmarkCollection) { - //Move the virtual cursor to the location before the end of the bookmark. + //Move the virtual cursor to the bookmark. bookmarksNavigator.MoveToBookmark(bookmark.Name); //Get the bookmark content as WordDocumentPart. WordDocumentPart documentPart = bookmarksNavigator.GetContent(); @@ -401,7 +411,7 @@ using (WordDocument document = new WordDocument("Template.docx", FormatType.Docx //Iterate each bookmark in Word document. foreach (Bookmark bookmark in bookmarkCollection) { - //Move the virtual cursor to the location before the end of the bookmark. + //Move the virtual cursor to the bookmark. bookmarksNavigator.MoveToBookmark(bookmark.Name); //Get the bookmark content as WordDocumentPart. WordDocumentPart documentPart = bookmarksNavigator.GetContent(); @@ -422,7 +432,7 @@ Using document As WordDocument = New WordDocument("Template.docx", FormatType.Do Dim bookmarkCollection As BookmarkCollection = document.Bookmarks 'Iterate each bookmark in Word document. For Each bookmark As Bookmark In bookmarkCollection - 'Move the virtual cursor to the location before the end of the bookmark. + 'Move the virtual cursor to the bookmark. bookmarksNavigator.MoveToBookmark(bookmark.Name) 'Get the bookmark content as WordDocumentPart. Dim documentPart As WordDocumentPart = bookmarksNavigator.GetContent() @@ -439,9 +449,13 @@ End Using You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Word-document/Split-by-bookmark). -## Split by placeholder text +## Split by Placeholder Text + +The following code example illustrates how to split the Word document using placeholder text. The snippet finds every placeholder of the form `<<…>>`, and inserts `BookmarkStart`/`BookmarkEnd` markers around each *pair* of placeholders (the start placeholder of a pair becomes the bookmark start; the next placeholder becomes the bookmark end). After all pairs are marked, each bookmark is extracted into a standalone document. The algorithm assumes the placeholders appear in start/end pairs; an odd number of placeholders will leave the last one unpaired and should be validated before processing. -The following code example illustrates how to split the Word document using the placeholder text. +N> Refer to the appropriate tabs in the code snippets section: ***C# [Cross-platform]*** for ASP.NET Core, Blazor, Xamarin, UWP, .NET MAUI, and WinUI; ***C# [Windows-specific]*** for WinForms and WPF; ***VB.NET [Windows-specific]*** for VB.NET applications. + +N> The regular expression `"<<(.*)>>"` is greedy and will match from the first `<<` to the last `>>` in a single line/span. If your placeholders appear on the same line, use a non-greedy pattern such as `"<<(.*?)>>"` to limit each match to a single placeholder. {% tabs %} @@ -644,4 +658,9 @@ You can download a complete working sample from [GitHub](https://github.com/Sync * Explore how to split a Word document by section using the [.NET Word Library](https://www.syncfusion.com/document-sdk/net-word-library) (DocIO) in a live demo [here](https://document.syncfusion.com/demos/word/splitbysection#/tailwind). * See how to split a Word document by heading using the [.NET Word Library](https://www.syncfusion.com/document-sdk/net-word-library) (DocIO) in a live demo [here](https://document.syncfusion.com/demos/word/splitbyheading#/tailwind). * See how to split a Word document by bookmark using the [.NET Word Library](https://www.syncfusion.com/document-sdk/net-word-library) (DocIO) in a live demo [here](https://document.syncfusion.com/demos/word/splitbybookmark#/tailwind). -* See how to split a Word document by placeholder using the [.NET Word Library](https://www.syncfusion.com/document-sdk/net-word-library) (DocIO) in a live demo [here](https://document.syncfusion.com/demos/word/splitbyplaceholder#/tailwind). \ No newline at end of file +* See how to split a Word document by placeholder text using the [.NET Word Library](https://www.syncfusion.com/document-sdk/net-word-library) (DocIO) in a live demo [here](https://document.syncfusion.com/demos/word/splitbyplaceholder#/tailwind). + +## See Also + +* [How to split Word document by bookmarks in C#, VB.NET](https://support.syncfusion.com/kb/article/6723/how-to-split-word-document-by-bookmarks-in-c-vb-net) +* [How to split Word document by sections in C#, VB.NET](https://support.syncfusion.com/kb/article/6456/how-to-split-word-document-by-sections-in-c-vb-net) \ No newline at end of file diff --git a/Document-Processing/Word/Word-Library/NET/Working-with-Word-document.md b/Document-Processing/Word/Word-Library/NET/Working-with-Word-document.md index 4a61ec8ea8..b299893f74 100644 --- a/Document-Processing/Word/Word-Library/NET/Working-with-Word-document.md +++ b/Document-Processing/Word/Word-Library/NET/Working-with-Word-document.md @@ -32,6 +32,7 @@ using (WordDocument document = new WordDocument(fileStreamPath, FormatType.Docx) {% endhighlight %} {% highlight c# tabtitle="C# [Windows-specific]" %} +string fileName = "Template.docx"; //Opens an existing document WordDocument inputTemplateDoc = new WordDocument(fileName); //Creates a clone of Input Template @@ -40,10 +41,11 @@ WordDocument clonedDocument = inputTemplateDoc.Clone(); clonedDocument.Save("ClonedDocument.docx"); clonedDocument.Close(); //Closes the input template document instance -sourceDocument.Close(); +inputTemplateDoc.Close(); {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} +Dim fileName As String = "Template.docx" 'Opens an existing document Dim inputTemplateDoc As New WordDocument(fileName) 'Creates a clone of Input Template @@ -52,14 +54,14 @@ Dim clonedDocument As WordDocument = inputTemplateDoc.Clone() clonedDocument.Save("ClonedDocument.docx") clonedDocument.Close() 'Closes the input template document instance -sourceDocument.Close() +inputTemplateDoc.Close() {% endhighlight %} {% endtabs %} You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Word-document/Clone-whole-Word-document). -You can also create a deep copy of document elements such as sections, paragraphs, Tables, Text, Image, OleObject, Shapes, TextBoxes and etc., The following code example illustrates how to clone the section and save each cloned section as a Word document. +You can also create a deep copy of document elements such as sections, paragraphs, Tables, Text, Image, OleObject, Shapes, TextBoxes, etc. The following code example illustrates how to clone the section and save each cloned section as a Word document. {% tabs %} @@ -67,7 +69,7 @@ You can also create a deep copy of document elements such as sections, paragraph //Creates an instance of WordDocument class FileStream fileStreamPath = new FileStream("SourceDocument.docx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); WordDocument sourceDocument = new WordDocument(fileStreamPath); -//Processes the each section in the Word document +//Processes each section in the Word document for (int i = 0; i < sourceDocument.Sections.Count;i++) { //Creates new WordDocument instance to add cloned section @@ -86,7 +88,7 @@ sourceDocument.Close(); {% highlight c# tabtitle="C# [Windows-specific]" %} //Opens a source document WordDocument sourceDocument = new WordDocument("SourceDocument.docx"); -//Processes the each section in the Word document +//Processes each section in the Word document for (int i = 0; i < sourceDocument.Sections.Count;i++) { //Creates new WordDocument instance to add cloned section @@ -104,7 +106,7 @@ sourceDocument.Close(); {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} 'Opens a source document Dim sourceDocument As New WordDocument("SourceDocument.docx") -'Processes the each section in the Word document +'Processes each section in the Word document For i As Integer = 0 To sourceDocument.Sections.Count - 1 'Creates new WordDocument instance to add cloned section Dim destinationDocument As New WordDocument() @@ -122,9 +124,9 @@ sourceDocument.Close() You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Word-document/Split-by-section). -### Link Paragraph and Character Style +## Link Paragraph and Character Style -You can link character styles with paragraph and vice versa in a Word document using [LinkedStyleName](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.Style.html#Syncfusion_DocIO_DLS_Style_LinkedStyleName) property. +You can link character styles with paragraph styles, and vice versa in a Word document using [LinkedStyleName](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.Style.html#Syncfusion_DocIO_DLS_Style_LinkedStyleName) property. The following code example explains how to link character and paragraph style. @@ -145,7 +147,7 @@ using (WordDocument document = new WordDocument()) //Sets the formatting of the style charStyle.CharacterFormat.Bold = true; charStyle.CharacterFormat.Italic = true; - //Link both paragraph and character style + //Links both paragraph and character style paraStyle.LinkedStyleName = "CharacterStyle"; //Appends the contents into the paragraph document.LastParagraph.AppendText("AdventureWorks Cycles"); @@ -178,8 +180,8 @@ using (WordDocument document = new WordDocument()) //Sets the formatting of the style charStyle.CharacterFormat.Bold = true; charStyle.CharacterFormat.Italic = true; - //Link both paragraph and character style - paraStyle.LinkedStyleName = "CharacterStyle"; + //Links both paragraph and character style + paraStyle.LinkedStyleName = "CharacterStyle"; //Appends the contents into the paragraph document.LastParagraph.AppendText("AdventureWorks Cycles"); //Applies the style to paragraph @@ -196,7 +198,7 @@ using (WordDocument document = new WordDocument()) {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} -'Opens an input Word template +'Creates a new Word document Using document As WordDocument = New WordDocument() 'This method adds a section and a paragraph in the document document.EnsureMinimal() @@ -209,7 +211,7 @@ Using document As WordDocument = New WordDocument() 'Sets the formatting of the style charStyle.CharacterFormat.Bold = True charStyle.CharacterFormat.Italic = True - 'Link both paragraph and character style + 'Links both paragraph and character style paraStyle.LinkedStyleName = "CharacterStyle" 'Appends the content into the paragraph document.LastParagraph.AppendText("AdventureWorks Cycles") @@ -231,7 +233,7 @@ End Using ## Working with Word document properties -Document properties, also known as metadata, are details about a file that describe or identify it. You can also define the additional custom document properties for the documents by using DocIO Document properties that are classified as two categories. +Document properties, also known as metadata, are details about a file that describe or identify it. You can also define additional custom document properties by using DocIO document properties, which are classified into two categories: * Built-in document properties - includes details such as title, author name, subject, and keywords that identify the document's topic or contents. * Custom document properties - defines the user-defined document properties. @@ -250,7 +252,7 @@ using (WordDocument document = new WordDocument(sourceStreamPath, FormatType.Aut //Accesses the built-in document properties Console.WriteLine("Title - {0}",document.BuiltinDocumentProperties.Title); Console.WriteLine("Author - {0}", document.BuiltinDocumentProperties.Author); - //Modifies or sets the Built-in document properties. + //Modifies or sets the built-in document properties. document.BuiltinDocumentProperties.Author = "Andrew"; document.BuiltinDocumentProperties.LastAuthor = "Steven"; document.BuiltinDocumentProperties.CreateDate = new DateTime(1900, 12, 31, 12, 0, 0); @@ -275,7 +277,7 @@ WordDocument document = new WordDocument(inputFileName); //Accesses the built-in document properties Console.WriteLine("Title - {0}",document.BuiltinDocumentProperties.Title); Console.WriteLine("Author - {0}", document.BuiltinDocumentProperties.Author); -//Modifies or sets the Built-in document properties. +//Modifies or sets the built-in document properties. document.BuiltinDocumentProperties.Author = "Andrew"; document.BuiltinDocumentProperties.LastAuthor = "Steven"; document.BuiltinDocumentProperties.CreateDate = new DateTime(1900, 12, 31, 12, 0, 0); @@ -437,7 +439,7 @@ N> 2. In ASP.NET Core and Xamarin platforms, to update page count in a Word doc N> 3. DocIO uses the Word-to-PDF layout engine to update page count. If the required fonts are missing in the environment, alternate fonts are used, which may affect accuracy. [Ensure](https://support.syncfusion.com/kb/article/6821/check-whether-fonts-in-word-document-are-available-in-machine-for-pdf-or-image-conversion) all fonts used in the input document are available for a correct page count. N> 4. In UWP platform, to updates paragraph, word, and character counts in the document using the [UpdateWordCount()](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WordDocument.html#Syncfusion_DocIO_DLS_WordDocument_UpdateWordCount) API. -### Adding Custom Document properties +### Adding custom document properties You add a new custom document properties through [Add](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.CustomDocumentProperties.html#Syncfusion_DocIO_DLS_CustomDocumentProperties_Add_System_String_System_Object_) method of [CustomProperties](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WordDocument.html#Syncfusion_DocIO_DLS_WordDocument_CustomDocumentProperties) class. The following code example illustrates how to add a new custom document properties. @@ -899,22 +901,22 @@ using (FileStream docStream = new FileStream("Input.docx", FileMode.Open, FileAc {% highlight c# tabtitle="C# [Windows-specific]" %} //Load Word document. -using (WordDocument document = new WordDocument(“Input.docx” FormatType.Docx)) +using (WordDocument document = new WordDocument("Input.docx", FormatType.Docx)) { //Disable a flag to hide the background in print layout view. document.Settings.DisplayBackgrounds = false; //Save the Word document. - document.Save(“Sample.docx”), FormatType.Docx); + document.Save("Sample.docx", FormatType.Docx); } {% endhighlight %} -{% highlight vb.net tabtitle="VB.NET [Windows-specific] " %} +{% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} 'Load Word document. -Using document As WordDocument = New WordDocument(“Input.docx"), FormatType.Docx) +Using document As WordDocument = New WordDocument("Input.docx", FormatType.Docx) 'Disable a flag to hide the background in the print layout view. document.Settings.DisplayBackgrounds = False 'Save the Word document. - document.Save(“Sample.docx"), FormatType.Docx) + document.Save("Sample.docx", FormatType.Docx) End Using {% endhighlight %} @@ -922,6 +924,8 @@ End Using You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Word-document/Hide-backgrounds-in-print-layout-view). +N> This setting affects only the Word client's print-layout view; it does not alter the background stored in the document. + ## Remove background in a Word document You can remove background colors and images in an existing Word document by setting [NoBackground](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BackgroundType.html) as the background type. @@ -948,23 +952,23 @@ using (FileStream docStream = new FileStream("Input.docx", FileMode.Open, FileAc {% highlight c# tabtitle="C# [Windows-specific]" %} //Load Word document. -using (WordDocument document = new WordDocument(“Input.docx” FormatType.Docx)) +using (WordDocument document = new WordDocument("Input.docx", FormatType.Docx)) { //Remove the existing background in the Word document. document.Background.Type = BackgroundType.NoBackground; //Save the Word document. - document.Save(“Sample.docx”), FormatType.Docx); + document.Save("Sample.docx", FormatType.Docx); } {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} 'Load Word document. -Using document As WordDocument = New WordDocument(“Input.docx"), FormatType.Docx) +Using document As WordDocument = New WordDocument("Input.docx", FormatType.Docx) 'Remove the existing background in the Word document. - document.Background.Type = BackgroundType.NoBackground; + document.Background.Type = BackgroundType.NoBackground 'Save the Word document. - document.Save(“Sample.docx"), FormatType.Docx) + document.Save("Sample.docx", FormatType.Docx) End Using {% endhighlight %} From 0078d4059ccd23ad6f4b08c71cf440a64031ccad Mon Sep 17 00:00:00 2001 From: SujithkumarSekar Date: Wed, 22 Jul 2026 23:14:29 +0530 Subject: [PATCH 2/2] Committing files --- .../Word-Library/NET/Working-With-Images.md | 130 +++++---- .../NET/Working-with-Bookmarks.md | 80 +++--- .../Word-Library/NET/Working-with-Fields.md | 36 +-- .../NET/Working-with-Hyperlinks.md | 263 +++++++++++------- .../NET/Working-with-Paragraph.md | 86 +++--- .../Word-Library/NET/Working-with-Sections.md | 44 +-- .../Word-Library/NET/Working-with-Shapes.md | 249 +++++++++-------- .../Word-Library/NET/Working-with-Tables.md | 72 ++--- .../NET/mail-merge/mail-merge-events.md | 61 ++-- .../NET/mail-merge/mail-merge-for-group.md | 27 +- .../mail-merge-for-nested-groups.md | 65 +++-- .../NET/mail-merge/mail-merge-options.md | 63 +++-- .../mail-merge-troubleshooting-tips.md | 32 +-- .../NET/mail-merge/simple-mail-merge.md | 27 +- .../Word-Library/NET/working-with-lists.md | 62 ++--- .../NET/working-with-mail-merge.md | 90 +++--- 16 files changed, 747 insertions(+), 640 deletions(-) diff --git a/Document-Processing/Word/Word-Library/NET/Working-With-Images.md b/Document-Processing/Word/Word-Library/NET/Working-With-Images.md index 9f92204443..2831106967 100644 --- a/Document-Processing/Word/Word-Library/NET/Working-With-Images.md +++ b/Document-Processing/Word/Word-Library/NET/Working-With-Images.md @@ -5,13 +5,15 @@ platform: document-processing control: DocIO documentation: UG --- -# Working with Images in Word document +# Working with Images in a Word document -DocIO provides support for both inline and absolute positioned images. +DocIO provides support for both inline and absolute positioned images. * Inline images: The position of the image is constrained to the lines of text on the page. * Absolute positioned images: The images can be positioned anywhere irrespective of the lines of text. +N> To run the code samples in this topic, install the `Syncfusion.DocIO.Net.Core` (cross-platform) or `Syncfusion.DocIO.Wpf`/`Syncfusion.DocIO.WinForms` (Windows-specific) NuGet package, register your Syncfusion license, and add `using`/`Imports` directives for the `Syncfusion.DocIO` and `Syncfusion.DocIO.DLS` namespaces. + The following code example explains how to add image to the paragraph. N> Refer to the appropriate tabs in the code snippets section: ***C# [Cross-platform]*** for ASP.NET Core, Blazor, Xamarin, UWP, .NET MAUI, and WinUI; ***C# [Windows-specific]*** for WinForms and WPF; ***VB.NET [Windows-specific]*** for VB.NET applications. @@ -25,8 +27,8 @@ WordDocument document = new WordDocument(); IWSection section = document.AddSection(); //Adds new paragraph to the section IWParagraph firstParagraph = section.AddParagraph(); -//Adds image to the paragraph -FileStream imageStream = new FileStream(@"Image.png", FileMode.Open, FileAccess.ReadWrite); +//Adds image to the paragraph +FileStream imageStream = new FileStream(@"Image.png", FileMode.Open, FileAccess.Read); IWPicture picture = firstParagraph.AppendPicture(imageStream); //Sets height and width for the image picture.Height = 100; @@ -45,7 +47,7 @@ WordDocument document = new WordDocument(); IWSection section = document.AddSection(); //Adds new paragraph to the section IWParagraph firstParagraph = section.AddParagraph(); -//Adds image to the paragraph +//Adds image to the paragraph IWPicture picture = firstParagraph.AppendPicture(Image.FromFile("Image.png")); //Sets height and width for the image picture.Height = 100; @@ -63,7 +65,7 @@ Dim document As New WordDocument() Dim section As IWSection = document.AddSection() 'Adds new paragraph to the section Dim firstParagraph As IWParagraph = section.AddParagraph() -'Adds image to the paragraph +'Adds image to the paragraph Dim picture As IWPicture = firstParagraph.AppendPicture(Image.FromFile("Image.png")) 'Sets height and width for the image picture.Height = 100 @@ -82,12 +84,14 @@ You can download a complete working sample from [GitHub](https://github.com/Sync Image present in the document can be replaced with a new image. This can be achieved by iterating through the paragraph items. +N> To identify images by `Title`, the `Title` property must have been set on the picture in the source document (for example, by Microsoft Word's "Alt Text" panel, or by setting `picture.Title` when the picture was created with DocIO). + The following code example explains how to replace an existing image. {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Paragraphs/Replace-image/.NET/Replace-image/Program.cs" %} -FileStream fileStream = new FileStream(@"Template.docx", FileMode.Open, FileAccess.ReadWrite); +FileStream fileStream = new FileStream(@"Template.docx", FileMode.Open, FileAccess.Read); //Loads the template document WordDocument document = new WordDocument(fileStream, FormatType.Automatic); WTextBody textbody = document.Sections[0].Body; @@ -103,7 +107,7 @@ foreach (WParagraph paragraph in textbody.Paragraphs) //Replaces the image if (picture.Title == "Bookmark") { - FileStream imageStream = new FileStream(@"Image.png", FileMode.Open, FileAccess.ReadWrite); + FileStream imageStream = new FileStream(@"Image.png", FileMode.Open, FileAccess.Read); picture.LoadImage(imageStream); } } @@ -177,7 +181,7 @@ The following code example explains how to remove the image from the paragraph i {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Paragraphs/Remove-image/.NET/Remove-image/Program.cs" %} -FileStream fileStream = new FileStream(@"Template.docx", FileMode.Open, FileAccess.ReadWrite); +FileStream fileStream = new FileStream(@"Template.docx", FileMode.Open, FileAccess.Read); //Loads the template document WordDocument document = new WordDocument(fileStream, FormatType.Automatic); WTextBody textbody = document.Sections[0].Body; @@ -267,7 +271,7 @@ IWSection section = document.AddSection(); //Adds new paragraph to the section IWParagraph paragraph = section.AddParagraph(); paragraph.AppendText("This paragraph has picture. "); -FileStream imageStream = new FileStream(@"Image.png", FileMode.Open, FileAccess.ReadWrite); +FileStream imageStream = new FileStream(@"Image.png", FileMode.Open, FileAccess.Read); //Appends new picture to the paragraph WPicture picture = paragraph.AppendPicture(imageStream) as WPicture; //Sets text wrapping style – When the wrapping style is inline, the images are not absolutely positioned. It is added next to the text range. @@ -275,8 +279,8 @@ picture.TextWrappingStyle = TextWrappingStyle.Square; //Sets horizontal and vertical origin picture.HorizontalOrigin = HorizontalOrigin.Page; picture.VerticalOrigin = VerticalOrigin.Paragraph; -//Sets width and height for the paragraph -picture.Width = 150; +//Sets width and height for the picture +picture.Width = 150; picture.Height = 100; //Sets horizontal and vertical position for the picture picture.HorizontalPosition = 200; @@ -313,7 +317,7 @@ picture.TextWrappingStyle = TextWrappingStyle.Square; //Sets horizontal and vertical origin picture.HorizontalOrigin = HorizontalOrigin.Page; picture.VerticalOrigin = VerticalOrigin.Paragraph; -//Sets width and height for the paragraph +//Sets width and height for the picture picture.Width = 150; picture.Height = 100; //Sets horizontal and vertical position for the picture @@ -350,7 +354,7 @@ picture.TextWrappingStyle = TextWrappingStyle.Square 'Sets horizontal and vertical origin picture.HorizontalOrigin = HorizontalOrigin.Page picture.VerticalOrigin = VerticalOrigin.Paragraph -'Sets width and height for the paragraph +'Sets width and height for the picture picture.Width = 150 picture.Height = 100 'Sets horizontal and vertical position for the picture @@ -378,14 +382,14 @@ You can download a complete working sample from [GitHub](https://github.com/Sync ## Find an image by title -An Image with a specific title can be retrieved by iterating the paragraph items that can be used for further manipulations. +An image with a specific title can be retrieved by iterating the text body child entities (paragraphs, tables, etc.) and the paragraph items within them, so that it can be used for further manipulations. The following code example explains how images can be iterated from the document elements. {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Paragraphs/Find-an-image-by-title/.NET/Find-an-image-by-title/Program.cs" %} -FileStream fileStream = new FileStream(@"Template.docx", FileMode.Open, FileAccess.ReadWrite); +FileStream fileStream = new FileStream(@"Template.docx", FileMode.Open, FileAccess.Read); //Loads an existing Word document into DocIO instance WordDocument document = new WordDocument(fileStream, FormatType.Docx); //Gets textbody content @@ -419,7 +423,7 @@ document.Close(); {% endhighlight %} {% highlight c# tabtitle="C# [Windows-specific]" %} -//Creates a new Word document +//Loads an existing Word document WordDocument document = new WordDocument("Template.docx"); //Gets textbody content WTextBody textBody = document.Sections[0].Body; @@ -451,7 +455,7 @@ document.Close(); {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} -'Creates a new Word document +'Loads an existing Word document Dim document As New WordDocument("Template.docx") 'Gets textbody content Dim textBody As WTextBody = document.Sections(0).Body @@ -481,9 +485,15 @@ document.Close() You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Paragraphs/Find-an-image-by-title). -## Add Image caption +## Add image caption + +You can add caption to an image and update the caption numbers (Sequence fields) using [AddCaption](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WPicture.html#Syncfusion_DocIO_DLS_WPicture_AddCaption_System_String_Syncfusion_DocIO_CaptionNumberingFormat_Syncfusion_DocIO_CaptionPosition_) method. The `AddCaption` method accepts the following parameters: -You can add caption to an image and update the caption numbers (Sequence fields) using [AddCaption](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WPicture.html#Syncfusion_DocIO_DLS_WPicture_AddCaption_System_String_Syncfusion_DocIO_CaptionNumberingFormat_Syncfusion_DocIO_CaptionPosition_) method. +* `imageName`: The caption label name (e.g., "Figure", "Table"). +* `captionNumberingFormat`: A `CaptionNumberingFormat` value that controls how the caption number is formatted (e.g., `Roman`, `Number`). +* `captionPosition`: A `CaptionPosition` value that determines whether the caption appears before or after the image (e.g., `AfterImage`, `BeforeImage`). + +N> Call `UpdateDocumentFields()` after adding captions so that the sequence (caption number) fields are computed and rendered in the output. The following code example shows how to add caption to an image. @@ -499,29 +509,29 @@ section.PageSetup.Margins.All = 72; //Adds a paragraph to the section IWParagraph paragraph = section.AddParagraph(); paragraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center; -//Adds image to the paragraph -FileStream imageStream = new FileStream(@"Google.png", FileMode.Open, FileAccess.ReadWrite); +//Adds image to the paragraph +FileStream imageStream = new FileStream(@"Google.png", FileMode.Open, FileAccess.Read); IWPicture picture = paragraph.AppendPicture(imageStream); //Adds Image caption -IWParagraph lastParagragh = picture.AddCaption("Figure", CaptionNumberingFormat.Roman, CaptionPosition.AfterImage); +IWParagraph lastParagraph = picture.AddCaption("Figure", CaptionNumberingFormat.Roman, CaptionPosition.AfterImage); //Aligns the caption -lastParagragh.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center; +lastParagraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center; //Sets after spacing -lastParagragh.ParagraphFormat.AfterSpacing = 12f; +lastParagraph.ParagraphFormat.AfterSpacing = 12f; //Sets before spacing -lastParagragh.ParagraphFormat.BeforeSpacing = 1.5f; +lastParagraph.ParagraphFormat.BeforeSpacing = 1.5f; //Adds a paragraph to the section paragraph = section.AddParagraph(); paragraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center; -//Adds image to the paragraph -imageStream = new FileStream(@"Yahoo.png", FileMode.Open, FileAccess.ReadWrite); +//Adds image to the paragraph +imageStream = new FileStream(@"Yahoo.png", FileMode.Open, FileAccess.Read); picture = paragraph.AppendPicture(imageStream); //Adds Image caption -lastParagragh = picture.AddCaption("Figure", CaptionNumberingFormat.Roman, CaptionPosition.AfterImage); +lastParagraph = picture.AddCaption("Figure", CaptionNumberingFormat.Roman, CaptionPosition.AfterImage); //Aligns the caption -lastParagragh.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center; +lastParagraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center; //Sets before spacing -lastParagragh.ParagraphFormat.BeforeSpacing = 1.5f; +lastParagraph.ParagraphFormat.BeforeSpacing = 1.5f; //Updates the fields in Word document document.UpdateDocumentFields(); //Saves the Word document to MemoryStream. @@ -541,27 +551,27 @@ section.PageSetup.Margins.All = 72; //Adds a paragraph to the section IWParagraph paragraph = section.AddParagraph(); paragraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center; -//Adds image to the paragraph +//Adds image to the paragraph IWPicture picture = paragraph.AppendPicture(Image.FromFile("Google.png")); //Adds Image caption -IWParagraph lastParagragh = picture.AddCaption("Figure", CaptionNumberingFormat.Roman, CaptionPosition.AfterImage); +IWParagraph lastParagraph = picture.AddCaption("Figure", CaptionNumberingFormat.Roman, CaptionPosition.AfterImage); //Aligns the caption -lastParagragh.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center; +lastParagraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center; //Sets after spacing -lastParagragh.ParagraphFormat.AfterSpacing = 12f; +lastParagraph.ParagraphFormat.AfterSpacing = 12f; //Sets before spacing -lastParagragh.ParagraphFormat.BeforeSpacing = 1.5f; +lastParagraph.ParagraphFormat.BeforeSpacing = 1.5f; //Adds a paragraph to the section paragraph = section.AddParagraph(); paragraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center; -//Adds image to the paragraph +//Adds image to the paragraph picture = paragraph.AppendPicture(Image.FromFile("Yahoo.png")); //Adds Image caption -lastParagragh = picture.AddCaption("Figure", CaptionNumberingFormat.Roman, CaptionPosition.AfterImage); +lastParagraph = picture.AddCaption("Figure", CaptionNumberingFormat.Roman, CaptionPosition.AfterImage); //Aligns the caption -lastParagragh.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center; +lastParagraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center; //Sets before spacing -lastParagragh.ParagraphFormat.BeforeSpacing = 1.5f; +lastParagraph.ParagraphFormat.BeforeSpacing = 1.5f; //Updates the fields in Word document document.UpdateDocumentFields(); //Saves and closes the document @@ -579,27 +589,27 @@ section.PageSetup.Margins.All = 72 'Adds a paragraph to the section Dim paragraph As IWParagraph = section.AddParagraph paragraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center -'Adds image to the paragraph +'Adds image to the paragraph Dim picture As IWPicture = paragraph.AppendPicture(Image.FromFile("Google.png")) 'Adds Image caption -Dim lastParagragh As IWParagraph = picture.AddCaption("Figure", CaptionNumberingFormat.Roman, CaptionPosition.AfterImage) +Dim lastParagraph As IWParagraph = picture.AddCaption("Figure", CaptionNumberingFormat.Roman, CaptionPosition.AfterImage) 'Aligns the caption -lastParagragh.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center +lastParagraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center 'Sets after spacing -lastParagragh.ParagraphFormat.AfterSpacing = 12.0F +lastParagraph.ParagraphFormat.AfterSpacing = 12.0F 'Sets before spacing -lastParagragh.ParagraphFormat.BeforeSpacing = 1.5F +lastParagraph.ParagraphFormat.BeforeSpacing = 1.5F 'Adds a paragraph to the section paragraph = section.AddParagraph paragraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center -'Adds image to the paragraph +'Adds image to the paragraph picture = paragraph.AppendPicture(Image.FromFile("Yahoo.png")) 'Adds Image caption -lastParagragh = picture.AddCaption("Figure", CaptionNumberingFormat.Roman, CaptionPosition.AfterImage) +lastParagraph = picture.AddCaption("Figure", CaptionNumberingFormat.Roman, CaptionPosition.AfterImage) 'Aligns the caption -lastParagragh.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center +lastParagraph.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center 'Sets before spacing -lastParagragh.ParagraphFormat.BeforeSpacing = 1.5F +lastParagraph.ParagraphFormat.BeforeSpacing = 1.5F 'Updates the fields in Word document document.UpdateDocumentFields() 'Saves and closes the document @@ -619,14 +629,16 @@ By executing the above code example, it generates output Word document as follow To add an SVG image to a paragraph in a Word document using Syncfusion® DocIO, you can use the [AppendPicture](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.IWParagraph.html#Syncfusion_DocIO_DLS_IWParagraph_AppendPicture_System_Byte___System_Byte___) API. -N> To preserve the SVG image in the Word document, pass both the SVG image data and the equivalent bitmap image bytes to DocIO. +N> To preserve the SVG image in the Word document, pass both the SVG image data and a fallback raster image (e.g., PNG) as byte arrays to DocIO. The fallback image is used by viewers that do not support SVG. + +N> SVG image support is available from Syncfusion.DocIO packages version 20.1.0.x and later. The following code example shows how to add an SVG image in a Word document. {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Paragraphs/Add-svg-image/.NET/Add-svg-image/Program.cs" %} -///Create a new Word document. +//Create a new Word document. using (WordDocument document = new WordDocument()) { //Add a new section to the document. @@ -643,8 +655,10 @@ using (WordDocument document = new WordDocument()) picture.Height = 100; picture.Width = 100; //Save the Word document to MemoryStream. - MemoryStream stream = new MemoryStream(); - document.Save(stream, FormatType.Docx); + using (MemoryStream stream = new MemoryStream()) + { + document.Save(stream, FormatType.Docx); + } } {% endhighlight %} @@ -677,12 +691,12 @@ Using document As New WordDocument() Dim section As IWSection = document.AddSection() ' Add a new paragraph to the section. Dim firstParagraph As IWParagraph = section.AddParagraph() - ' Get the PNG image as a byte array. + ' Get the fallback image (PNG) as a byte array. Dim imageBytes As Byte() = File.ReadAllBytes("Buyers.png") ' Get the SVG image as a byte array. Dim svgData As Byte() = File.ReadAllBytes("Buyers.svg") ' Add SVG image to the paragraph. - Dim picture As IWPicture = firstParagraph.AppendPicture(svgData, ImageType.Metafile, imageBytes) + Dim picture As IWPicture = firstParagraph.AppendPicture(svgData, imageBytes) ' Set height and width for the image. picture.Height = 100 picture.Width = 100 @@ -695,12 +709,9 @@ End Using You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Paragraphs/Add-svg-image/.NET). -## Online Demo - -* Explore how to insert an image into the Word document using the [.NET Word Library](https://www.syncfusion.com/document-sdk/net-word-library) (DocIO) in a live demo [here](https://document.syncfusion.com/demos/word/imageinsertion#/tailwind). - ## See Also +* [How to insert an image into a Word document (live demo)](https://document.syncfusion.com/demos/word/imageinsertion#/tailwind) using the [.NET Word Library](https://www.syncfusion.com/document-sdk/net-word-library) (DocIO). * [How to extract Images from Word document in C# and VB?](https://support.syncfusion.com/kb/article/11829/how-to-extract-images-from-word-document-in-c-and-vb) * [How to replace an image with same size in a Word document](https://support.syncfusion.com/kb/article/17796/how-to-replace-an-image-with-same-size-in-a-word-document) * [How to find and replace an image title in a Word document?](https://support.syncfusion.com/kb/article/18808/how-to-find-and-replace-an-image-title-in-a-word-document) @@ -712,7 +723,6 @@ You can download a complete working sample from [GitHub](https://github.com/Sync * [How to Find and Remove Corrupted Images in .NET Core Word Document?](https://support.syncfusion.com/kb/article/19605/how-to-find-and-remove-corrupted-images-in-net-core-word-document) * [How to Convert Excel Worksheets to Images in .NET Core Word document?](https://support.syncfusion.com/kb/article/20162/how-to-convert-excel-worksheets-to-images-in-net-core-word-document) * [How to resize images to fit owner element in NET Core Word document?](https://support.syncfusion.com/kb/article/21490/how-to-resize-images-to-fit-owner-element-in-net-core-word-document) -* [How to extract all images from ASP.NET Core Word Document?](https://support.syncfusion.com/kb/article/19583/how-to-extract-all-images-from-aspnet-core-word-document) ## Frequently Asked Questions diff --git a/Document-Processing/Word/Word-Library/NET/Working-with-Bookmarks.md b/Document-Processing/Word/Word-Library/NET/Working-with-Bookmarks.md index 178a4f920e..f4c2879bca 100644 --- a/Document-Processing/Word/Word-Library/NET/Working-with-Bookmarks.md +++ b/Document-Processing/Word/Word-Library/NET/Working-with-Bookmarks.md @@ -9,8 +9,8 @@ documentation: UG A bookmark identifies a location or a selection of text within a document that you can name and identify for future reference. -In Essential® DocIO, bookmark is represented by [Bookmark](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.Bookmark.html) instance that is a pair of [BookmarkStart](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BookmarkStart.html) and [BookmarkEnd](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BookmarkEnd.html). -[BookmarkStart](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BookmarkStart.html) represents start point of a bookmark and [BookmarkEnd](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BookmarkEnd.html) represents end point of a bookmark. Every Word document contains a collection of bookmarks that are accessible through the [Bookmarks](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WordDocument.html#Syncfusion_DocIO_DLS_WordDocument_Bookmarks) property of [WordDocument](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WordDocument.html) class. +In Essential® DocIO, a bookmark is represented by a [Bookmark](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.Bookmark.html) instance that is a pair of [BookmarkStart](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BookmarkStart.html) and [BookmarkEnd](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BookmarkEnd.html). +[BookmarkStart](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BookmarkStart.html) represents the start point of a bookmark and [BookmarkEnd](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BookmarkEnd.html) represents the end point of a bookmark. Every Word document contains a collection of bookmarks that are accessible through the [Bookmarks](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WordDocument.html#Syncfusion_DocIO_DLS_WordDocument_Bookmarks) property of [WordDocument](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WordDocument.html) class. To quickly start working with bookmarks in a Word document, please check out this video: {% youtube "https://www.youtube.com/watch?v=8C2-aS8tdLU" %} @@ -34,7 +34,7 @@ IWParagraph paragraph = document.LastParagraph; paragraph.AppendBookmarkStart("Northwind"); //Adds a text between the bookmark start and end into paragraph paragraph.AppendText("The Northwind sample database (Northwind.mdb) is included with all versions of Access. It provides data you can experiment with and database objects that demonstrate features you might want to implement in your own databases."); -//Adds a new bookmark end into paragraph with name " Northwind " +//Adds a new bookmark end into paragraph with name "Northwind" paragraph.AppendBookmarkEnd("Northwind"); //Adds a text after the bookmark end paragraph.AppendText(" Using Northwind, you can become familiar with how a relational database is structured and how the database objects work together to help you enter, store, manipulate, and print your data."); @@ -56,14 +56,14 @@ IWParagraph paragraph = document.LastParagraph; paragraph.AppendBookmarkStart("Northwind"); //Adds a text between the bookmark start and end into paragraph paragraph.AppendText("The Northwind sample database (Northwind.mdb) is included with all versions of Access. It provides data you can experiment with and database objects that demonstrate features you might want to implement in your own databases."); -//Adds a new bookmark end into paragraph with name " Northwind " +//Adds a new bookmark end into paragraph with name "Northwind" paragraph.AppendBookmarkEnd("Northwind"); //Adds a text after the bookmark end paragraph.AppendText(" Using Northwind, you can become familiar with how a relational database is structured and how the database objects work together to help you enter, store, manipulate, and print your data."); //Saves the document in the given name and format document.Save("Bookmarks.docx", FormatType.Docx); -//Releases the resources occupied by WordDocument instance -document.Close(); +//Releases the resources occupied by the WordDocument instance +document.Close(); {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} @@ -77,14 +77,14 @@ Dim paragraph As IWParagraph = document.LastParagraph paragraph.AppendBookmarkStart("Northwind") 'Adds a text between the bookmark start and end into paragraph paragraph.AppendText("The Northwind sample database (Northwind.mdb) is included with all versions of Access. It provides data you can experiment with and database objects that demonstrate features you might want to implement in your own databases.") -'Adds a new bookmark end into paragraph with name " Northwind " +'Adds a new bookmark end into paragraph with name "Northwind" paragraph.AppendBookmarkEnd("Northwind") 'Adds a text after the bookmark end paragraph.AppendText(" Using Northwind, you can become familiar with how a relational database is structured and how the database objects work together to help you enter, store, manipulate, and print your data.") 'Saves the document in the given name and format document.Save("Bookmarks.docx", FormatType.Docx) -'Releases the resources occupied by WordDocument instance -document.Close() +'Releases the resources occupied by the WordDocument instance +document.Close() {% endhighlight %} {% endtabs %} @@ -103,7 +103,7 @@ FileStream fileStreamPath = new FileStream(@"Bookmarks.docx", FileMode.Open, Fil WordDocument document = new WordDocument(fileStreamPath, FormatType.Docx); //Gets the bookmark instance by using FindByName method of BookmarkCollection with bookmark name Syncfusion.DocIO.DLS.Bookmark bookmark = document.Bookmarks.FindByName("Northwind"); -//Accesses the bookmark start’s owner paragraph by using bookmark and changes its back color +//Accesses the bookmark start's owner paragraph by using the bookmark and changes its back color bookmark.BookmarkStart.OwnerParagraph.ParagraphFormat.BackColor = Color.AliceBlue; //Saves the Word document to MemoryStream MemoryStream stream = new MemoryStream(); @@ -117,7 +117,7 @@ document.Close(); WordDocument document = new WordDocument("Bookmarks.docx", FormatType.Docx); //Gets the bookmark instance by using FindByName method of BookmarkCollection with bookmark name Syncfusion.DocIO.DLS.Bookmark bookmark = document.Bookmarks.FindByName("Northwind"); -//Accesses the bookmark start’s owner paragraph by using bookmark and changes its back color +//Accesses the bookmark start's owner paragraph by using the bookmark and changes its back color bookmark.BookmarkStart.OwnerParagraph.ParagraphFormat.BackColor = Color.AliceBlue; document.Save("Result.docx", FormatType.Docx); document.Close(); @@ -128,7 +128,7 @@ document.Close(); Dim document As New WordDocument("Bookmarks.docx", FormatType.Docx) 'Gets the bookmark instance by using FindByName method of BookmarkCollection with bookmark name Dim bookmark As Syncfusion.DocIO.DLS.Bookmark = document.Bookmarks.FindByName("Northwind") -'Accesses the bookmark start’s owner paragraph by using bookmark and changes its back color +'Accesses the bookmark start's owner paragraph by using the bookmark and changes its back color bookmark.BookmarkStart.OwnerParagraph.ParagraphFormat.BackColor = Color.AliceBlue document.Save("Result.docx", FormatType.Docx) document.Close() @@ -138,9 +138,9 @@ document.Close() You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Bookmarks/Get-an-instance-of-bookmark). -## Removing a Bookmark from Word document +## Removing a bookmark from a Word document -The following code example shows how to remove a bookmark from Word document. +The following code example shows how to remove a bookmark from a Word document. {% tabs %} @@ -185,14 +185,14 @@ document.Close() You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Bookmarks/Remove-bookmark-from-Word-document). -## Retrieving contents within a bookmark +## Retrieving contents within a bookmark -[BookmarkNavigator](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BookmarksNavigator.html) is used for navigating to a bookmark in a Word document. You can retrieve, replace and delete the content of a specified bookmark by using [BookmarkNavigator](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BookmarksNavigator.html). +[BookmarkNavigator](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BookmarksNavigator.html) is used for navigating to a bookmark in a Word document. You can retrieve, replace, and delete the content of a specified bookmark by using [BookmarkNavigator](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BookmarksNavigator.html). You can get the content between bookmark start and bookmark end of the specified bookmark in two ways: -1. You can use [GetBookmarkContent](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BookmarksNavigator.html#Syncfusion_DocIO_DLS_BookmarksNavigator_GetBookmarkContent) method for retrieving content as collection of body items when the bookmark start and bookmark end are preserved in a single section. -2. You can use [GetContent](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BookmarksNavigator.html#Syncfusion_DocIO_DLS_BookmarksNavigator_GetContent) method for retrieving content as collection of sections when the bookmark start and bookmark end are preserved in different sections. +1. You can use [GetBookmarkContent](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BookmarksNavigator.html#Syncfusion_DocIO_DLS_BookmarksNavigator_GetBookmarkContent) method for retrieving content as a collection of body items when the bookmark start and bookmark end are preserved in a single section. +2. You can use [GetContent](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BookmarksNavigator.html#Syncfusion_DocIO_DLS_BookmarksNavigator_GetContent) method for retrieving content as a collection of sections when the bookmark start and bookmark end are preserved in different sections. The following code example shows how to retrieve the specified bookmark content by using [GetBookmarkContent](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BookmarksNavigator.html#Syncfusion_DocIO_DLS_BookmarksNavigator_GetBookmarkContent) method in a Word document. @@ -317,7 +317,7 @@ wordDocumentPart.Close() 'Close the template Word document document.Close() newDocument.Save("Result.docx", FormatType.Docx) -'Releases the resources hold by WordDocument instance +'Releases the resources held by the WordDocument instance newDocument.Close() {% endhighlight %} @@ -325,12 +325,12 @@ newDocument.Close() You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Bookmarks/Get-bookmark-content-as-document-part). -## Retrieving bookmark contents within a table +## Retrieving bookmark contents within a table You can select the column range for bookmarks inside the tables in Word documents by using [FirstColumn](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.Bookmark.html#Syncfusion_DocIO_DLS_Bookmark_FirstColumn) and [LastColumn](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.Bookmark.html#Syncfusion_DocIO_DLS_Bookmark_LastColumn) properties. -N> 1. [FirstColumn](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.Bookmark.html#Syncfusion_DocIO_DLS_Bookmark_FirstColumn) and [LastColumn](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.Bookmark.html#Syncfusion_DocIO_DLS_Bookmark_LastColumn) properties are valid to select table cells, only when the respective bookmark end and start is present within the same row or next rows of the same table. -N> 2. [FirstColumn](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.Bookmark.html#Syncfusion_DocIO_DLS_Bookmark_FirstColumn) property denotes the top left corner cell and [LastColumn](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.Bookmark.html#Syncfusion_DocIO_DLS_Bookmark_LastColumn) property denotes the bottom right corner cell of rectangular selection region since you can only select the content as a rectangular selection by using bookmarks within the table. +N> 1. [FirstColumn](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.Bookmark.html#Syncfusion_DocIO_DLS_Bookmark_FirstColumn) and [LastColumn](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.Bookmark.html#Syncfusion_DocIO_DLS_Bookmark_LastColumn) properties are valid to select table cells, only when the respective bookmark end and start are present within the same row or next rows of the same table. +N> 2. [FirstColumn](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.Bookmark.html#Syncfusion_DocIO_DLS_Bookmark_FirstColumn) property denotes the top left corner cell and [LastColumn](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.Bookmark.html#Syncfusion_DocIO_DLS_Bookmark_LastColumn) property denotes the bottom right corner cell of rectangular selection region, because bookmark selections inside a table are always rectangular. N> 3. [FirstColumn](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.Bookmark.html#Syncfusion_DocIO_DLS_Bookmark_FirstColumn) property selects from the first cell of the respective row when this property value is negative (or) greater than the cells of a row (or) greater than the [LastColumn](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.Bookmark.html#Syncfusion_DocIO_DLS_Bookmark_LastColumn) value. N> 4. [LastColumn](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.Bookmark.html#Syncfusion_DocIO_DLS_Bookmark_LastColumn) property selects till last cell of the respective row when this property value is negative (or) greater than the cells of a row (or) less than the [FirstColumn](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.Bookmark.html#Syncfusion_DocIO_DLS_Bookmark_FirstColumn) value. @@ -357,9 +357,11 @@ bookmarkNavigator.CurrentBookmark.LastColumn = 4; TextBodyPart part = bookmarkNavigator.GetBookmarkContent(); //Adds new section document.AddSection(); -for (int i = 0; i < part.BodyItems.Count; i++) //Adds the retrieved content into another new section -document.LastSection.Body.ChildEntities.Add(part.BodyItems[i]); +for (int i = 0; i < part.BodyItems.Count; i++) +{ + document.LastSection.Body.ChildEntities.Add(part.BodyItems[i]); +} //Saves the Word document to MemoryStream MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Docx); @@ -388,9 +390,11 @@ TextBodyPart part = bookmarkNavigator.GetBookmarkContent(); document.AddSection(); //Adds the retrieved content into another new section for (int i = 0; i < part.BodyItems.Count; i++) -document.LastSection.Body.ChildEntities.Add(part.BodyItems[i]); +{ + document.LastSection.Body.ChildEntities.Add(part.BodyItems[i]); +} //Saves and closes the Word document -document.Save("Sample.docx", FormatType.Docx); +document.Save("Result.docx", FormatType.Docx); document.Close(); {% endhighlight %} @@ -630,6 +634,8 @@ FileStream imageStream = new FileStream("Northwind.png", FileMode.Open, FileAcce picture.LoadImage(imageStream); picture.WidthScale = 50; picture.HeightScale = 50; +//Disposes the image stream +imageStream.Dispose(); //Saves the Word document to MemoryStream MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Docx); @@ -904,7 +910,7 @@ FileStream fileStreamPath = new FileStream("Bookmarks.docx", FileMode.Open, File WordDocument document = new WordDocument(fileStreamPath, FormatType.Docx); //Creates the bookmark navigator instance to access the bookmark BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); -//Moves the virtual cursor to the location before the end of the bookmark "Northwind " +//Moves the virtual cursor to the location before the end of the bookmark "Northwind" bookmarkNavigator.MoveToBookmark("Northwind"); //Deletes bookmark content without deleting the format in the target document. bookmarkNavigator.DeleteBookmarkContent(false); @@ -920,7 +926,7 @@ document.Close(); WordDocument document = new WordDocument("Bookmarks.docx", FormatType.Docx); //Creates the bookmark navigator instance to access the bookmark BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); -//Moves the virtual cursor to the location before the end of the bookmark "Northwind " +//Moves the virtual cursor to the location before the end of the bookmark "Northwind" bookmarkNavigator.MoveToBookmark("Northwind"); //Deletes bookmark content without deleting the format in the target document. bookmarkNavigator.DeleteBookmarkContent(false); @@ -951,13 +957,13 @@ You can replace the contents of an existing bookmark with simple text, [TextBody N> You cannot replace the multi section contents into a bookmark within table in Word documents. Use "for loop" instead of "foreach loop" to iterate through document elements when replacing the bookmark contents to avoid “collection modified exception”, as there is a chance for modification in the document elements on replacing the bookmark contents. -As per Microsoft Word behavior, you cannot replace the bookmark contents when the bookmark start and end is not in a same table as following cases: +As per Microsoft Word behavior, you cannot replace the bookmark contents when the bookmark start and end are not in the same table, as in the following cases: -Case 1 +Case 1: Bookmark start and end are present in different tables. ![Bookmark start and end present in different tables](WorkingwithBookmarks_images/WorkingwithBookmarks_img1.jpeg) -Case 2 +Case 2: Bookmark start is placed outside the table and the end is inside the table. ![Bookmark start placed outside table and end in table](WorkingwithBookmarks_images/WorkingwithBookmarks_img2.jpeg) @@ -1055,13 +1061,13 @@ bookmarkNavigator.MoveToBookmark("Northwind"); //Gets the bookmark content as WordDocumentPart WordDocumentPart wordDocumentPart = bookmarkNavigator.GetContent(); //Loads the Word document with bookmark NorthwindDB -FileStream fileStreamPath = new FileStream("Bookmarks.docx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); -WordDocument document = new WordDocument(fileStreamPath, FormatType.Docx); +FileStream fileStream = new FileStream("Bookmarks.docx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); +WordDocument document = new WordDocument(fileStream, FormatType.Docx); //Creates the bookmark navigator instance to access the bookmark bookmarkNavigator = new BookmarksNavigator(document); //Moves the virtual cursor to the location before the end of the bookmark "NorthwindDB" bookmarkNavigator.MoveToBookmark("NorthwindDB"); -//Replaces the bookmark content with word body part +//Replaces the bookmark content with WordDocumentPart bookmarkNavigator.ReplaceContent(wordDocumentPart); //Close the WordDocumentPart instance wordDocumentPart.Close(); @@ -1089,7 +1095,7 @@ WordDocument document = new WordDocument("Bookmarks.docx", FormatType.Docx); bookmarkNavigator = new BookmarksNavigator(document); //Moves the virtual cursor to the location before the end of the bookmark "NorthwindDB" bookmarkNavigator.MoveToBookmark("NorthwindDB"); -//Replaces the bookmark content with word body part +//Replaces the bookmark content with WordDocumentPart bookmarkNavigator.ReplaceContent(wordDocumentPart); //Close the WordDocumentPart instance wordDocumentPart.Close(); @@ -1114,7 +1120,7 @@ Dim document As New WordDocument("Bookmarks.docx", FormatType.Docx) bookmarkNavigator = New BookmarksNavigator(document) 'Moves the virtual cursor to the location before the end of the bookmark "NorthwindDB" bookmarkNavigator.MoveToBookmark("NorthwindDB") -'Replaces the bookmark content with word body part +'Replaces the bookmark content with WordDocumentPart bookmarkNavigator.ReplaceContent(wordDocumentPart) 'Close the WordDocumentPart instance wordDocumentPart.Close() @@ -1152,7 +1158,7 @@ You can download a complete working sample from [GitHub](https://github.com/Sync * [How to export content between two bookmarks as HTML in a Word document?](https://support.syncfusion.com/kb/article/20097/how-to-export-content-between-two-bookmarks-as-html-in-a-word-document) * [How to apply a style to bookmark content in a Word document?](https://support.syncfusion.com/kb/article/20093/how-to-apply-a-style-to-bookmark-content-in-a-word-document) * [How to export Bookmarks content as HTML in .NET Core Word Document?](https://support.syncfusion.com/kb/article/22282/how-to-export-bookmarks-content-as-html-in-net-core-word-document) -* [How to Add Bookmarks to All Paragraphs and Retrieve Their Contents in .NET Core Word document?](https://support.syncfusion.com/kb/article/22282/how-to-export-bookmarks-content-as-html-in-net-core-word-document) +* [How to Add Bookmarks to All Paragraphs and Retrieve Their Contents in .NET Core Word document?](https://support.syncfusion.com/kb/article/22282/how-to-add-bookmarks-to-all-paragraphs-and-retrieve-their-contents-in-net-core-word-document) * [How to format bookmark content in ASP.NET Core Word Document?](https://support.syncfusion.com/kb/article/22143/how-to-format-bookmark-content-in-aspnet-core-word-document) * [How to Identify Bookmark Placement in Word Document in .NET Core?](https://support.syncfusion.com/kb/article/22205/how-to-identify-bookmark-placement-in-word-document-in-net-core) * [How to Find Nested Bookmarks in a Word Document in C# .NET Core?](https://support.syncfusion.com/kb/article/22187/how-to-find-nested-bookmarks-in-a-word-document-in-c-net-core) diff --git a/Document-Processing/Word/Word-Library/NET/Working-with-Fields.md b/Document-Processing/Word/Word-Library/NET/Working-with-Fields.md index 9fddd4cb80..0c12a2e6bb 100644 --- a/Document-Processing/Word/Word-Library/NET/Working-with-Fields.md +++ b/Document-Processing/Word/Word-Library/NET/Working-with-Fields.md @@ -9,9 +9,9 @@ documentation: UG Fields in a Word document are placeholders for data that might change on field update. Fields are represented by the [WField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WField.html) and [WFieldMark](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WFieldMark.html) instances in DocIO. A field in a Word document contains field codes, field separator, field result, and field end. -To learn various types of Microsoft Word supported fields and their syntax,refer to the [MSDN article](https://support.microsoft.com/en-us/office/list-of-field-codes-in-word-1ad6d91a-55a7-4a8d-b535-cf7888659a51?ui=en-us&rs=en-us&ad=us#) +To learn various types of Microsoft Word supported fields and their syntax, refer to the [MSDN article](https://support.microsoft.com/en-us/office/list-of-field-codes-in-word-1ad6d91a-55a7-4a8d-b535-cf7888659a51?ui=en-us&rs=en-us&ad=us#) -From v16.1.0.24, the entire field code is included in Document Object Model(DOM). Hence, adding a field will automatically include the following elements in DOM: +From v16.1.0.24, the entire field code is included in Document Object Model (DOM). Hence, adding a field will automatically include the following elements in DOM: 1. [WField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WField.html): Represents the starting of a Field. @@ -505,7 +505,7 @@ paragraph = section.AddParagraph() as WParagraph; //Gets the collection of bookmark start in the word document List items = document.GetCrossReferenceItems(ReferenceType.Bookmark); paragraph.AppendText("Bookmark Cross Reference starts here "); -//Appends the cross reference for bookmark “Title” with ContentText as reference kind +//Appends the cross reference for bookmark "Title" with ContentText as reference kind paragraph.AppendCrossReference(ReferenceType.Bookmark, ReferenceKind.ContentText, items[0], true, false, false, string.Empty); //Updates the document Fields document.UpdateDocumentFields(); @@ -533,7 +533,7 @@ paragraph = section.AddParagraph() as WParagraph; //Gets the collection of bookmark start in the word document List items = document.GetCrossReferenceItems(ReferenceType.Bookmark); paragraph.AppendText("Bookmark Cross Reference starts here "); -//Appends the cross reference for bookmark “Title” with ContentText as reference kind +//Appends the cross reference for bookmark "Title" with ContentText as reference kind paragraph.AppendCrossReference(ReferenceType.Bookmark, ReferenceKind.ContentText, items[0], true, false, false, string.Empty); //Updates the document Fields document.UpdateDocumentFields(); @@ -558,7 +558,7 @@ paragraph = TryCast(section.AddParagraph(), WParagraph) 'Gets the collection of bookmark start in the word document Dim items As List(Of Entity) = document.GetCrossReferenceItems(ReferenceType.Bookmark) paragraph.AppendText("Bookmark Cross Reference starts here ") -'Appends the cross reference for bookmark “Title” with ContentText as reference kind +'Appends the cross reference for bookmark "Title" with ContentText as reference kind paragraph.AppendCrossReference(ReferenceType.Bookmark, ReferenceKind.ContentText, items(0), True, False, False, String.Empty) 'Updates the document Fields document.UpdateDocumentFields() @@ -646,14 +646,14 @@ You can download a complete working sample from [GitHub](https://github.com/Sync N> XE (Index Entry) fields cannot be unlinked. ## Sequence Field -You can use the Sequence (SEQ) field to automatically numbers the chapters, tables, figures, and other items in a Word document. When you add, delete, or move an item in Word document (along with SEQ fields), you can update the remaining SEQ fields with a new sequence. +You can use the Sequence (SEQ) field to automatically number the chapters, tables, figures, and other items in a Word document. When you add, delete, or move an item in Word document (along with SEQ fields), you can update the remaining SEQ fields with a new sequence. You can format the SEQ field using below switches. \c -- Repeats the closest preceding sequence number. \h -- Hides the field result unless a general-formatting-switch is also present. \n -- Inserts the next sequence number for the specified items. This is the default switch. -\r -- Resets the sequence number to the number following “r”. +\r -- Resets the sequence number to the number following "r". \s -- Resets the sequence number at the heading level following the "s". ### Apply Number format @@ -841,7 +841,7 @@ seqField.BookmarkName = "BkmkPurchase"; paragraph = document.LastSection.Paragraphs[5] as WParagraph; seqField = paragraph.ChildEntities[1] as WSeqField; //Adds bookmark reference to the sequence field -seqField.BookmarkName = "BkkmUnitPrice"; +seqField.BookmarkName = "BkmkUnitPrice"; //Updates the document fields document.UpdateDocumentFields(); //Saves the Word document to MemoryStream @@ -852,7 +852,7 @@ document.Close(); {% endhighlight %} {% highlight c# tabtitle="C# [Windows-specific]" %} -//Opens an exixting word document +//Opens an existing word document WordDocument document = new WordDocument("Template.docx"); //Accesses sequence field in the document WParagraph paragraph = document.LastSection.Body.ChildEntities[4] as WParagraph; @@ -863,7 +863,7 @@ seqField.BookmarkName = "BkmkPurchase"; paragraph = document.LastSection.Paragraphs[5] as WParagraph; seqField = paragraph.ChildEntities[1] as WSeqField; //Adds bookmark reference to the sequence field -seqField.BookmarkName = "BkkmUnitPrice"; +seqField.BookmarkName = "BkmkUnitPrice"; //Updates the document fields document.UpdateDocumentFields(); //Saves and closes the Word document @@ -872,7 +872,7 @@ document.Close(); {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} -'Opens an exixting word document +'Opens an existing word document Dim document As WordDocument = New WordDocument("Template.docx") 'Accesses sequence field in the document Dim paragraph As WParagraph = CType(document.LastSection.Body.ChildEntities(4), WParagraph) @@ -883,7 +883,7 @@ seqField.BookmarkName = "BkmkPurchase" paragraph = CType(document.LastSection.Paragraphs(5), WParagraph) seqField = CType(paragraph.ChildEntities(1), WSeqField) 'Adds bookmark reference to the sequence field -seqField.BookmarkName = "BkkmUnitPrice" +seqField.BookmarkName = "BkmkUnitPrice" 'Updates the document fields document.UpdateDocumentFields() 'Saves and closes the Word document @@ -900,7 +900,7 @@ By executing the above code example, it generates output Word document as follow ![Output document of Bookmark referred in SEQ field](workingwithfields_images/file-formats-word-seql-field-bookmark-output.png) ### Reset numbering -You can reset the numbering for sequence field (\r) using [ResetNumber](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WSeqField.html#Syncfusion_DocIO_DLS_WSeqField_ResetNumber) property and reset the numbering based on heading level (\s) in the Word document using [ResetHeadingLevel](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WSeqField.html#Syncfusion_DocIO_DLS_WSeqField_ResetHeadingLevel) property. +You can reset the numbering for sequence field (\r) using [ResetNumber](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WSeqField.html#Syncfusion_DocIO_DLS_WSeqField_ResetNumber) property and reset the numbering based on the heading level (\s) in the Word document using [ResetHeadingLevel](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WSeqField.html#Syncfusion_DocIO_DLS_WSeqField_ResetHeadingLevel) property. The following code example shows how to reset the numbering for sequence field. @@ -1534,7 +1534,7 @@ WordDocument document = CreateDocument(); //Accesses sequence field in the document WTable table = document.LastSection.Body.ChildEntities[1] as WTable; WSeqField field = ((table[2, 1].ChildEntities[0] as WParagraph).ChildEntities[0] as WSeqField); -//Enables a flag to to hide the sequence field result +//Enables a flag to hide the sequence field result field.HideResult = true; //Accesses sequence field in the document field = ((table[4, 1].ChildEntities[0] as WParagraph).ChildEntities[0] as WSeqField); @@ -1555,7 +1555,7 @@ WordDocument document = CreateDocument(); //Accesses sequence field in the document WTable table = document.LastSection.Body.ChildEntities[1] as WTable; WSeqField field = ((table[2, 1].ChildEntities[0] as WParagraph).ChildEntities[0] as WSeqField); -//Enables a flag to to hide the sequence field result +//Enables a flag to hide the sequence field result field.HideResult = true; //Accesses sequence field in the document field = ((table[4, 1].ChildEntities[0] as WParagraph).ChildEntities[0] as WSeqField); @@ -1574,7 +1574,7 @@ Dim document As WordDocument = CreateDocument() 'Accesses sequence field in the document Dim table As WTable = CType(document.LastSection.Body.ChildEntities(1), WTable) Dim field As WSeqField = CType(CType(table(2, 1).ChildEntities(0), WParagraph).ChildEntities(0), WSeqField) -'Enables a flag to to hide the sequence field result +'Enables a flag to hide the sequence field result field.HideResult = True 'Accesses sequence field in the document field = CType(CType(table(4, 1).ChildEntities(0), WParagraph).ChildEntities(0), WSeqField) @@ -1779,7 +1779,7 @@ document.Close(); {% endhighlight %} {% highlight c# tabtitle="C# [Windows-specific]" %} -//Opens an exixting word document +//Opens an existing word document WordDocument document = new WordDocument("Template.docx"); //Accesses sequence field in the document WParagraph paragraph = document.LastSection.Body.ChildEntities[4] as WParagraph; @@ -1794,7 +1794,7 @@ document.Close(); {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} -'Opens an exixting word document +'Opens an existing word document Dim document As WordDocument = New WordDocument("Template.docx") 'Accesses sequence field in the document diff --git a/Document-Processing/Word/Word-Library/NET/Working-with-Hyperlinks.md b/Document-Processing/Word/Word-Library/NET/Working-with-Hyperlinks.md index 9213d5fa2b..6411d3dab1 100644 --- a/Document-Processing/Word/Word-Library/NET/Working-with-Hyperlinks.md +++ b/Document-Processing/Word/Word-Library/NET/Working-with-Hyperlinks.md @@ -5,45 +5,75 @@ platform: document-processing control: DocIO documentation: UG --- -# Working with Hyperlinks in Word Library +# Working with Hyperlinks in the Word Library -Hyperlinks have two parts: the address and display content. +Hyperlinks have two parts: the address and the display content. The Syncfusion® .NET Word (DocIO) library supports the following hyperlink types: + +* Web hyperlink +* Email hyperlink +* File hyperlink +* Bookmark hyperlink +* Image hyperlink + +## Prerequisites + +To use the DocIO library, add a reference to the **Syncfusion.DocIO.Net.Core** (cross-platform) or **Syncfusion.DocIO.WinForms** (Windows-specific) NuGet package from [nuget.org](https://www.nuget.org/). For more information, refer to [NuGet packages required](https://help.syncfusion.com/document-processing/word/word-library/net/nuget-packages-required). + +**Starting with v16.2.0.x**, you must also install the **Syncfusion.Licensing** package and register a valid license key in your application. For details, refer to the [Syncfusion licensing documentation](https://help.syncfusion.com/common/essential-studio/licensing/overview). + +The following namespaces are required in the samples below. + +{% tabs %} + +{% highlight c# tabtitle="C#" %} +using Syncfusion.DocIO; +using Syncfusion.DocIO.DLS; +{% endhighlight %} + +{% highlight vb.net tabtitle="VB.NET" %} +Imports Syncfusion.DocIO +Imports Syncfusion.DocIO.DLS +{% endhighlight %} + +{% endtabs %} ## Web hyperlink -The following code example explains how to insert a web link. +The following code example shows how to insert a web link. {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Paragraphs/Add-web-link/.NET/Add-web-link/Program.cs" %} -//Creates a new Word document +//Creates a new Word document WordDocument document = new WordDocument(); //Adds new section to the document IWSection section = document.AddSection(); //Adds new paragraph to the section IWParagraph paragraph = section.AddParagraph(); -paragraph.AppendText("Web Hyperlink: "); +paragraph.AppendText("Web hyperlink: "); paragraph = section.AddParagraph(); -//Appends web hyperlink to the paragraph -IWField field = paragraph.AppendHyperlink("http://www.syncfusion.com", "Syncfusion", HyperlinkType.WebLink); -//Saves the Word document to MemoryStream. -MemoryStream stream = new MemoryStream(); -document.Save(stream, FormatType.Docx); -//Closes the Word document. +//Appends a web hyperlink to the paragraph +paragraph.AppendHyperlink("http://www.syncfusion.com", "Syncfusion", HyperlinkType.WebLink); +//Saves the Word document to a MemoryStream +using (MemoryStream stream = new MemoryStream()) +{ + document.Save(stream, FormatType.Docx); +} +//Closes the Word document document.Close(); {% endhighlight %} {% highlight c# tabtitle="C# [Windows-specific]" %} -//Creates a new Word document +//Creates a new Word document WordDocument document = new WordDocument(); //Adds new section to the document IWSection section = document.AddSection(); //Adds new paragraph to the section IWParagraph paragraph = section.AddParagraph(); -paragraph.AppendText("Web Hyperlink: "); +paragraph.AppendText("Web hyperlink: "); paragraph = section.AddParagraph(); -//Appends web hyperlink to the paragraph -IWField field = paragraph.AppendHyperlink("http://www.syncfusion.com", "Syncfusion", HyperlinkType.WebLink); +//Appends a web hyperlink to the paragraph +paragraph.AppendHyperlink("http://www.syncfusion.com", "Syncfusion", HyperlinkType.WebLink); //Saves the Word document document.Save("Sample.docx", FormatType.Docx); //Closes the document @@ -51,16 +81,16 @@ document.Close(); {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} -'Creates a new Word document +'Creates a new Word document Dim document As New WordDocument() 'Adds new section to the document Dim section As IWSection = document.AddSection() 'Adds new paragraph to the section Dim paragraph As IWParagraph = section.AddParagraph() -paragraph.AppendText("Web Hyperlink: ") +paragraph.AppendText("Web hyperlink: ") paragraph = section.AddParagraph() -'Appends web hyperlink to the paragraph -Dim field As IWField = paragraph.AppendHyperlink("http://www.syncfusion.com", "Syncfusion", HyperlinkType.WebLink) +'Appends a web hyperlink to the paragraph +paragraph.AppendHyperlink("http://www.syncfusion.com", "Syncfusion", HyperlinkType.WebLink) 'Saves the Word document document.Save("Sample.docx", FormatType.Docx) 'Closes the document @@ -73,12 +103,12 @@ You can download a complete working sample from [GitHub](https://github.com/Sync ## Email hyperlink -The following code example illustrates how to add an email link. +The following code example shows how to add an email link. {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Paragraphs/Add-an-email-link/.NET/Add-an-email-link/Program.cs" %} -//Creates a new Word document +//Creates a new Word document WordDocument document = new WordDocument(); //Adds new section to the document IWSection section = document.AddSection(); @@ -86,17 +116,19 @@ IWSection section = document.AddSection(); IWParagraph paragraph = section.AddParagraph(); paragraph.AppendText("Email hyperlink: "); paragraph = section.AddParagraph(); -//Appends Email hyperlink to the paragraph +//Appends an email hyperlink to the paragraph paragraph.AppendHyperlink("mailto:sales@syncfusion.com", "Sales", HyperlinkType.EMailLink); -//Saves the Word document to MemoryStream. -MemoryStream stream = new MemoryStream(); -document.Save(stream, FormatType.Docx); -//Closes the Word document. +//Saves the Word document to a MemoryStream +using (MemoryStream stream = new MemoryStream()) +{ + document.Save(stream, FormatType.Docx); +} +//Closes the Word document document.Close(); {% endhighlight %} {% highlight c# tabtitle="C# [Windows-specific]" %} -//Creates a new Word document +//Creates a new Word document WordDocument document = new WordDocument(); //Adds new section to the document IWSection section = document.AddSection(); @@ -104,8 +136,8 @@ IWSection section = document.AddSection(); IWParagraph paragraph = section.AddParagraph(); paragraph.AppendText("Email hyperlink: "); paragraph = section.AddParagraph(); -//Appends Email hyperlink to the paragraph -paragraph.AppendHyperlink("mailto:sales@syncfusion.com","Sales" , HyperlinkType.EMailLink); +//Appends an email hyperlink to the paragraph +paragraph.AppendHyperlink("mailto:sales@syncfusion.com", "Sales", HyperlinkType.EMailLink); //Saves the Word document document.Save("Sample.docx", FormatType.Docx); //Closes the document @@ -113,7 +145,7 @@ document.Close(); {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} -'Creates a new Word document +'Creates a new Word document Dim document As New WordDocument() 'Adds new section to the document Dim section As IWSection = document.AddSection() @@ -121,8 +153,8 @@ Dim section As IWSection = document.AddSection() Dim paragraph As IWParagraph = section.AddParagraph() paragraph.AppendText("Email hyperlink: ") paragraph = section.AddParagraph() -'Appends Email hyperlink to the paragraph -paragraph.AppendHyperlink("mailto:sales@syncfusion.com","Sales" , HyperlinkType.EMailLink) +'Appends an email hyperlink to the paragraph +paragraph.AppendHyperlink("mailto:sales@syncfusion.com", "Sales", HyperlinkType.EMailLink) 'Saves the Word document document.Save("Sample.docx", FormatType.Docx) 'Closes the document @@ -135,39 +167,41 @@ You can download a complete working sample from [GitHub](https://github.com/Sync ## File hyperlink -The following code example explains how to add a file hyperlink. +The following code example shows how to add a file hyperlink. {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Paragraphs/Add-file-hyperlink/.NET/Add-file-hyperlink/Program.cs" %} -//Creates a new Word document +//Creates a new Word document WordDocument document = new WordDocument(); //Adds new section to the document IWSection section = document.AddSection(); //Adds new paragraph to the section IWParagraph paragraph = section.AddParagraph(); -paragraph.AppendText("File Hyperlinks: "); +paragraph.AppendText("File hyperlink: "); paragraph = section.AddParagraph(); -//Appends hyperlink field to the paragraph +//Appends a file hyperlink to the paragraph paragraph.AppendHyperlink(@"Template.docx", "File", HyperlinkType.FileLink); -//Saves the Word document to MemoryStream. -MemoryStream stream = new MemoryStream(); -document.Save(stream, FormatType.Docx); -//Closes the Word document. +//Saves the Word document to a MemoryStream +using (MemoryStream stream = new MemoryStream()) +{ + document.Save(stream, FormatType.Docx); +} +//Closes the Word document document.Close(); {% endhighlight %} {% highlight c# tabtitle="C# [Windows-specific]" %} -//Creates a new Word document +//Creates a new Word document WordDocument document = new WordDocument(); //Adds new section to the document IWSection section = document.AddSection(); //Adds new paragraph to the section IWParagraph paragraph = section.AddParagraph(); -paragraph.AppendText("File Hyperlinks: "); +paragraph.AppendText("File hyperlink: "); paragraph = section.AddParagraph(); -//Appends hyperlink field to the paragraph -paragraph.AppendHyperlink(@"Template.docx","File", HyperlinkType.FileLink); +//Appends a file hyperlink to the paragraph +paragraph.AppendHyperlink(@"Template.docx", "File", HyperlinkType.FileLink); //Saves the Word document document.Save("Sample.docx", FormatType.Docx); //Closes the document @@ -175,15 +209,15 @@ document.Close(); {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} -'Creates a new Word document +'Creates a new Word document Dim document As New WordDocument() 'Adds new section to the document Dim section As IWSection = document.AddSection() 'Adds new paragraph to the section Dim paragraph As IWParagraph = section.AddParagraph() -paragraph.AppendText("File Hyperlinks: ") +paragraph.AppendText("File hyperlink: ") paragraph = section.AddParagraph() -'Appends hyperlink field to the paragraph +'Appends a file hyperlink to the paragraph paragraph.AppendHyperlink("Template.docx", "File", HyperlinkType.FileLink) 'Saves the Word document document.Save("Sample.docx", FormatType.Docx) @@ -202,45 +236,47 @@ The following code example explains how to add a bookmark hyperlink. {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Paragraphs/Add-bookmark-hyperlink/.NET/Add-bookmark-hyperlink/Program.cs" %} -//Creates a new Word document +//Creates a new Word document WordDocument document = new WordDocument(); //Adds new section to the document IWSection section = document.AddSection(); //Adds new paragraph to the section IWParagraph paragraph = section.AddParagraph(); -//Creates new Bookmark +//Creates a new bookmark paragraph.AppendBookmarkStart("Introduction"); paragraph.AppendText("Hyperlink"); paragraph.AppendBookmarkEnd("Introduction"); paragraph.AppendText("\nA hyperlink is a reference or navigation element in a document to another section of the same document or to another document that may be on or part of a (different) domain."); paragraph = section.AddParagraph(); -paragraph.AppendText("Bookmark Hyperlink: "); +paragraph.AppendText("Bookmark hyperlink: "); paragraph = section.AddParagraph(); -//Appends Bookmark hyperlink to the paragraph +//Appends a bookmark hyperlink to the paragraph paragraph.AppendHyperlink("Introduction", "Bookmark", HyperlinkType.Bookmark); -//Saves the Word document to MemoryStream. -MemoryStream stream = new MemoryStream(); -document.Save(stream, FormatType.Docx); -//Closes the Word document. +//Saves the Word document to a MemoryStream +using (MemoryStream stream = new MemoryStream()) +{ + document.Save(stream, FormatType.Docx); +} +//Closes the Word document document.Close(); {% endhighlight %} {% highlight c# tabtitle="C# [Windows-specific]" %} -//Creates a new Word document +//Creates a new Word document WordDocument document = new WordDocument(); //Adds new section to the document IWSection section = document.AddSection(); //Adds new paragraph to the section IWParagraph paragraph = section.AddParagraph(); -//Creates new Bookmark +//Creates a new bookmark paragraph.AppendBookmarkStart("Introduction"); paragraph.AppendText("Hyperlink"); paragraph.AppendBookmarkEnd("Introduction"); paragraph.AppendText("\nA hyperlink is a reference or navigation element in a document to another section of the same document or to another document that may be on or part of a (different) domain."); paragraph = section.AddParagraph(); -paragraph.AppendText("Bookmark Hyperlink: "); +paragraph.AppendText("Bookmark hyperlink: "); paragraph = section.AddParagraph(); -//Appends Bookmark hyperlink to the paragraph +//Appends a bookmark hyperlink to the paragraph paragraph.AppendHyperlink("Introduction", "Bookmark", HyperlinkType.Bookmark); //Saves the Word document document.Save("Sample.docx", FormatType.Docx); @@ -249,21 +285,21 @@ document.Close(); {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} -'Creates a new Word document +'Creates a new Word document Dim document As New WordDocument() 'Adds new section to the document Dim section As IWSection = document.AddSection() 'Adds new paragraph to the section Dim paragraph As IWParagraph = section.AddParagraph() -'Creates new Bookmark +'Creates a new bookmark paragraph.AppendBookmarkStart("Introduction") paragraph.AppendText("Hyperlink") paragraph.AppendBookmarkEnd("Introduction") paragraph.AppendText(vbLf & "A hyperlink is a reference or navigation element in a document to another section of the same document or to another document that may be on or part of a (different) domain.") paragraph = section.AddParagraph() -paragraph.AppendText("Bookmark Hyperlink: ") +paragraph.AppendText("Bookmark hyperlink: ") paragraph = section.AddParagraph() -'Appends Bookmark hyperlink to the paragraph +'Appends a bookmark hyperlink to the paragraph paragraph.AppendHyperlink("Introduction", "Bookmark", HyperlinkType.Bookmark) 'Saves the Word document document.Save("Sample.docx", FormatType.Docx) @@ -277,47 +313,51 @@ You can download a complete working sample from [GitHub](https://github.com/Sync ## Image hyperlink -The display content for the Hyperlinks can also be an image that may redirect to some other contents. +The display content for a hyperlink can also be an image that redirects to other content. The following code example explains how to add an image hyperlink. {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Paragraphs/Add-image-hyperlink/.NET/Add-image-hyperlink/Program.cs" %} -//Creates a new Word document +//Creates a new Word document WordDocument document = new WordDocument(); //Adds new section to the document IWSection section = document.AddSection(); //Adds new paragraph to the section IWParagraph paragraph = section.AddParagraph(); -paragraph.AppendText("Image Hyperlink"); +paragraph.AppendText("Image hyperlink: "); paragraph = section.AddParagraph(); -//Creates a new image instance and load image +//Creates a new image instance and loads the image WPicture picture = new WPicture(document); -FileStream imageStream = new FileStream(@"Mountain-200.jpg", FileMode.Open, FileAccess.ReadWrite); -picture.LoadImage(imageStream); -//Appends new image hyperlink to the paragraph +using (FileStream imageStream = new FileStream(@"Mountain-200.jpg", FileMode.Open, FileAccess.ReadWrite)) +{ + picture.LoadImage(imageStream); +} +//Appends an image hyperlink to the paragraph paragraph.AppendHyperlink("http://www.syncfusion.com", picture, HyperlinkType.WebLink); -//Saves the Word document to MemoryStream. -MemoryStream stream = new MemoryStream(); -document.Save(stream, FormatType.Docx); -//Closes the Word document. +//Saves the Word document to a MemoryStream +using (MemoryStream stream = new MemoryStream()) +{ + document.Save(stream, FormatType.Docx); +} +//Closes the Word document document.Close(); {% endhighlight %} {% highlight c# tabtitle="C# [Windows-specific]" %} -//Creates a new Word document +//Creates a new Word document WordDocument document = new WordDocument(); //Adds new section to the document IWSection section = document.AddSection(); //Adds new paragraph to the section IWParagraph paragraph = section.AddParagraph(); -paragraph.AppendText("Image Hyperlink"); +paragraph.AppendText("Image hyperlink: "); paragraph = section.AddParagraph(); -//Creates a new image instance and load image +//Creates a new image instance and loads the image WPicture picture = new WPicture(document); picture.LoadImage(Image.FromFile("Image.png")); -//Appends new image hyperlink to the paragraph +//Appends an image hyperlink to the paragraph paragraph.AppendHyperlink("http://www.syncfusion.com", picture, HyperlinkType.WebLink); //Saves the Word document document.Save("Sample.docx", FormatType.Docx); @@ -326,18 +366,18 @@ document.Close(); {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} -'Creates a new Word document +'Creates a new Word document Dim document As New WordDocument() 'Adds new section to the document Dim section As IWSection = document.AddSection() 'Adds new paragraph to the section Dim paragraph As IWParagraph = section.AddParagraph() -paragraph.AppendText("Image Hyperlink") +paragraph.AppendText("Image hyperlink: ") paragraph = section.AddParagraph() -'Creates a new image instance and load image +'Creates a new image instance and loads the image Dim picture As New WPicture(document) picture.LoadImage(Image.FromFile("Image.png")) -'Appends new image hyperlink to the paragraph +'Appends an image hyperlink to the paragraph paragraph.AppendHyperlink("http://www.syncfusion.com", picture, HyperlinkType.WebLink) 'Saves the Word document document.Save("Sample.docx", FormatType.Docx) @@ -356,38 +396,42 @@ The following code example explains how to modify the URL of an existing hyperli {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Paragraphs/Modify-url-of-hyperlink/.NET/Modify-url-of-hyperlink/Program.cs" %} -FileStream fileStream = new FileStream(@"Sample.docx", FileMode.Open, FileAccess.ReadWrite); -//Loads the template document -WordDocument document = new WordDocument(fileStream, FormatType.Docx); -WParagraph paragraph = document.LastParagraph; -//Iterates through the paragraph items -foreach (ParagraphItem item in paragraph.ChildEntities) +using (FileStream fileStream = new FileStream(@"Sample.docx", FileMode.Open, FileAccess.ReadWrite)) { - if (item is WField) + //Loads the template document + WordDocument document = new WordDocument(fileStream, FormatType.Docx); + WParagraph paragraph = document.LastParagraph; + //Iterates through the paragraph items + foreach (ParagraphItem item in paragraph.ChildEntities) { - if ((item as WField).FieldType == FieldType.FieldHyperlink) + if (item is WField) { - //Gets the hyperlink field - Hyperlink link = new Hyperlink(item as WField); - if (link.Type == HyperlinkType.WebLink) + if ((item as WField).FieldType == FieldType.FieldHyperlink) { - //Modifies the url of the hyperlink - link.Uri = "http://www.google.com"; - link.TextToDisplay = "Google"; - break; + //Gets the hyperlink field + Hyperlink link = new Hyperlink(item as WField); + if (link.Type == HyperlinkType.WebLink) + { + //Modifies the URL of the hyperlink + link.Uri = "http://www.google.com"; + link.TextToDisplay = "Google"; + break; + } } } } + //Saves the Word document to a MemoryStream + using (MemoryStream stream = new MemoryStream()) + { + document.Save(stream, FormatType.Docx); + } + //Closes the Word document + document.Close(); } -//Saves the Word document to MemoryStream. -MemoryStream stream = new MemoryStream(); -document.Save(stream, FormatType.Docx); -//Closes the Word document. -document.Close(); {% endhighlight %} {% highlight c# tabtitle="C# [Windows-specific]" %} -//Loads the template document +//Loads the template document WordDocument document = new WordDocument("Sample.docx", FormatType.Docx); WParagraph paragraph = document.LastParagraph; //Iterates through the paragraph items @@ -401,7 +445,7 @@ foreach (ParagraphItem item in paragraph.ChildEntities) Hyperlink link = new Hyperlink(item as WField); if (link.Type == HyperlinkType.WebLink) { - //Modifies the url of the hyperlink + //Modifies the URL of the hyperlink link.Uri = "http://www.google.com"; link.TextToDisplay = "Google"; break; @@ -415,17 +459,18 @@ document.Close(); {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} -'Loads the template document +'Loads the template document Dim document As New WordDocument("Sample.docx", FormatType.Docx) Dim paragraph As WParagraph = document.LastParagraph 'Iterates through the paragraph items For Each item As ParagraphItem In paragraph.ChildEntities If TypeOf item Is WField Then - If TryCast(item, WField).FieldType = FieldType.FieldHyperlink Then + Dim field As WField = DirectCast(item, WField) + If field.FieldType = FieldType.FieldHyperlink Then 'Gets the hyperlink field - Dim link As New Hyperlink(TryCast(item, WField)) + Dim link As New Hyperlink(field) If link.Type = HyperlinkType.WebLink Then - 'Modifies the url of the hyperlink + 'Modifies the URL of the hyperlink link.Uri = "http://www.google.com" link.TextToDisplay = "Google" Exit For @@ -444,6 +489,8 @@ You can download a complete working sample from [GitHub](https://github.com/Sync ## See Also +The following knowledge base articles cover scenarios not discussed above — removing hyperlinks, replacing text with hyperlinks, and stripping hyperlink styling. + * [How to find and modify hyperlink address in Word document in C#, VB.NET](https://support.syncfusion.com/kb/article/12198/find-and-modify-hyperlink-address-in-word-document) * [How to replace particular text with hyperlink in the Word document](https://support.syncfusion.com/kb/article/10326/how-to-replace-the-particular-text-with-hyperlink-in-word-document) * [How to replace the URL of image hyperlink in Word document in C# and VB](https://support.syncfusion.com/kb/article/11259/how-to-replace-url-of-image-hyperlink-in-word-document) diff --git a/Document-Processing/Word/Word-Library/NET/Working-with-Paragraph.md b/Document-Processing/Word/Word-Library/NET/Working-with-Paragraph.md index 17c59714a3..d333b3332c 100644 --- a/Document-Processing/Word/Word-Library/NET/Working-with-Paragraph.md +++ b/Document-Processing/Word/Word-Library/NET/Working-with-Paragraph.md @@ -7,7 +7,7 @@ documentation: UG --- # Working with Paragraph in Word Library -Paragraph is the basic element in a Word document that contains a textual and graphical contents. Each paragraph has its own formatting such as line spacing, alignment, indentation, and more. Within a paragraph, the contents are represented by one or more child elements such as [WTextRange](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WTextRange.html), [WPicture](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WPicture.html), and [Hyperlink](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.Hyperlink.html) and more. The [ParagraphItem](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.ParagraphItem.html) is the base class for the child elements of paragraph. The following elements can be the child elements of a paragraph: +Paragraph is the basic element in a Word document that contains textual and graphical content. Each paragraph has its own formatting such as line spacing, alignment, indentation, and more. Within a paragraph, the contents are represented by one or more child elements such as [WTextRange](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WTextRange.html), [WPicture](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WPicture.html), [Hyperlink](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.Hyperlink.html), and more. The [ParagraphItem](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.ParagraphItem.html) is the base class for the child elements of paragraph. The following elements can be the child elements of a paragraph: * Text: Represented by an instance of [WTextRange](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WTextRange.html). * Image: Represented by an instance of [WPicture](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WPicture.html). @@ -85,34 +85,37 @@ The following code example illustrates how to modify an existing paragraph. {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Paragraphs/Modify-an-existing-paragraph/.NET/Modify-an-existing-paragraph/Program.cs" %} -FileStream fileStream = new FileStream(@"Test.docx", FileMode.Open, FileAccess.ReadWrite); -//Loads the template document -WordDocument document = new WordDocument(fileStream, FormatType.Docx); -//Gets the text body of first section -WTextBody textBody = document.Sections[0].Body; -//Gets the paragraph at index 1 -WParagraph paragraph = textBody.Paragraphs[1]; -//Iterates through the child elements of paragraph -foreach (ParagraphItem item in paragraph.ChildEntities) +//Opens the file as Stream +using (FileStream fileStream = new FileStream(@"Test.docx", FileMode.Open, FileAccess.ReadWrite)) { - if (item is WTextRange) + //Loads the template document + WordDocument document = new WordDocument(fileStream, FormatType.Docx); + //Gets the text body of first section + WTextBody textBody = document.Sections[0].Body; + //Gets the paragraph at index 1 + WParagraph paragraph = textBody.Paragraphs[1]; + //Iterates through the child elements of paragraph + foreach (ParagraphItem item in paragraph.ChildEntities) { - WTextRange text = item as WTextRange; - //Modifies the character format of the text - text.CharacterFormat.Bold = true; - break; + if (item is WTextRange) + { + WTextRange text = item as WTextRange; + //Modifies the character format of the text + text.CharacterFormat.Bold = true; + break; + } } + //Saves the Word document to MemoryStream + MemoryStream stream = new MemoryStream(); + document.Save(stream, FormatType.Docx); + //Closes the Word document + document.Close(); } -///Saves the Word document to MemoryStream -MemoryStream stream = new MemoryStream(); -document.Save(stream, FormatType.Docx); -//Closes the Word document -document.Close(); {% endhighlight %} {% highlight c# tabtitle="C# [Windows-specific]" %} //Loads the template document -WordDocument document = new WordDocument("Template.docx"); +WordDocument document = new WordDocument("Test.docx"); //Gets the text body of first section WTextBody textBody = document.Sections[0].Body; //Gets the paragraph at index 1 @@ -136,7 +139,7 @@ document.Close(); {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} 'Loads the template document -Dim document As New WordDocument("Template.docx") +Dim document As New WordDocument("Test.docx") 'Gets the text body of first section Dim textBody As WTextBody = document.Sections(0).Body 'Gets the paragraph at index 1 @@ -423,6 +426,8 @@ A tab stop is a horizontal position that is set for aligning text of the paragra Each paragraph has its own tab stop collection where the new tab stop can be added and existing tab stop can be removed. +N> The tab position value is specified in points (1 inch = 72 points). + The following code example explains how to add tab stops to the paragraph. {% tabs %} @@ -496,6 +501,8 @@ You can download a complete working sample from [GitHub](https://github.com/Sync You can set RTL (Right-to-left) direction to the paragraph in a Word document. The following code example shows how to set RTL (Right-to-left) for a paragraph in Word document. +N> Setting RTL (Right-to-left) direction also affects the alignment of the paragraph. Set the `HorizontalAlignment` to `Right` for proper RTL alignment. + {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Paragraphs/RTL-paragraph/.NET/RTL-paragraph/Program.cs" %} @@ -761,6 +768,8 @@ You can remove the styles present in the existing document using the [Remove](ht The following code example explains how to remove the style from the word document. +N> Removing a style that is applied to paragraphs will revert those paragraphs to the default formatting. Built-in styles cannot be removed using this method. + {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Word-document/Remove-particular-style-from-document/.NET/Remove-particular-style-from-document/Program.cs" %} @@ -802,7 +811,7 @@ Dim styleCollection As IStyleCollection = document.Styles 'Finds the style with the name "Style1." Dim style As WParagraphStyle = CType(styleCollection.FindByName("Style1"), WParagraphStyle) 'Remove the "Style1" style from the Word document. -style.Remove +style.Remove() 'Saves and closes the document instance. document.Save("Sample.docx", FormatType.Docx) document.Close() @@ -831,7 +840,7 @@ IWParagraph firstParagraph = section.AddParagraph(); IWTextRange firstText = firstParagraph.AppendText("A new text is added to the paragraph."); firstText.CharacterFormat.FontSize = 14; firstText.CharacterFormat.Bold = true; -firstText.CharacterFormat.TextColor = Color.Green; +firstText.CharacterFormat.TextColor = Syncfusion.Drawing.Color.Green; //Saves the Word document to MemoryStream MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Docx); @@ -977,11 +986,11 @@ firstText.CharacterFormat.Shadow = true; firstText.CharacterFormat.SmallCaps = true; IWTextRange secondText = firstParagraph.AppendText("This the second text range"); //Apply formatting for second text range -secondText.CharacterFormat.HighlightColor = Color.GreenYellow; +secondText.CharacterFormat.HighlightColor = Syncfusion.Drawing.Color.GreenYellow; secondText.CharacterFormat.UnderlineStyle = UnderlineStyle.DotDash; secondText.CharacterFormat.Italic = true; secondText.CharacterFormat.FontName = "Times New Roman"; -secondText.CharacterFormat.TextColor = Color.Green; +secondText.CharacterFormat.TextColor = Syncfusion.Drawing.Color.Green; //Add new paragraph to the section IWParagraph secondParagraph = section.AddParagraph(); //Add new text to the paragraph @@ -1138,7 +1147,9 @@ For further information, click [here](https://help.syncfusion.com/document-proce ## Working with symbols -Symbols are used to add contents such as currencies, numbers, punctuations, etc. DocIO represents symbols with [WSymbol](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WSymbol.html) instance. Each symbol can be identified with their character codes. +Symbols are used to add contents such as currencies, numbers, punctuation, etc. DocIO represents symbols with [WSymbol](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WSymbol.html) instance. Each symbol can be identified with their character codes. + +N> The character code corresponds to the symbol's position in the selected font's character map. Refer the [WSymbol](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WSymbol.html) API for details on character codes and font names. The following code example explains how to add new symbol to the document. @@ -1232,7 +1243,7 @@ document.Close(); {% highlight c# tabtitle="C# [Windows-specific]" %} //Loads the template document -WordDocument document = new WordDocument("Sample.docx", FormatType.Docx); +WordDocument document = new WordDocument("Sample1.docx", FormatType.Docx); //Gets the textbody content WTextBody textbody = document.Sections[0].Body; //Iterates through the paragraphs @@ -1293,7 +1304,7 @@ Breaks allow the document contents to split into multiple parts to customize the * Page break: Starts the content on the next page. * Line break: Starts the content in a new line. * Column break: Starts the content in the next column. -* Text wrapping break: Starts the content below to the picture, table, or other items. +* Text wrapping break: Starts the content below the picture, table, or other items. The following code example explains how various types of breaks can be appended to the paragraphs. @@ -1397,7 +1408,7 @@ You can download a complete working sample from [GitHub](https://github.com/Sync ### Text wrapping break -When including images or other objects in a Word document, the text is wrapped around the objects as per wrapping behavior. If you wish to move the text below to the picture (as like caption), instead of adding an extra line break or empty paragraphs, you can add the text wrapping break to achieve it. +When including images or other objects in a Word document, the text is wrapped around the objects as per wrapping behavior. If you wish to move the text below the picture (as a caption), instead of adding an extra line break or empty paragraphs, you can add the text wrapping break to achieve it. The following code example illustrates how to insert a text wrapping break to move the text below to the picture. @@ -1475,7 +1486,7 @@ For further information, click [here](https://help.syncfusion.com/document-proce ## Working with Text Box -Text box contains a group of textual and graphical contents. DocIO supports to create and manipulate the text box and its formatting by using the [WTextBox](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WTextBox.html) instance. +Text box contains a group of textual and graphical contents. DocIO supports creating and manipulating the text box and its formatting by using the [WTextBox](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WTextBox.html) instance. The following code example explains how to add new text box to the paragraph. @@ -1495,10 +1506,12 @@ IWParagraph textboxParagraph = textbox.TextBoxBody.AddParagraph(); textboxParagraph.AppendText("Text inside text box"); textboxParagraph = textbox.TextBoxBody.AddParagraph(); //Adds new picture to textbox body -FileStream imagestream = new FileStream(@"Mountain-200.jpg", FileMode.Open, FileAccess.ReadWrite); -IWPicture picture = textboxParagraph.AppendPicture(imagestream); -picture.Height = 75; -picture.Width = 50; +using (FileStream imagestream = new FileStream(@"Mountain-200.jpg", FileMode.Open, FileAccess.ReadWrite)) +{ + IWPicture picture = textboxParagraph.AppendPicture(imagestream); + picture.Height = 75; + picture.Width = 50; +} //Saves the Word document to MemoryStream MemoryStream stream = new MemoryStream(); document.Save(stream, FormatType.Docx); @@ -1560,6 +1573,8 @@ Text box has its own formatting such as outline color, fill effects, text direct The following code example explains how to apply formatting and rotation for text box. +N> The valid value for `Rotation` ranges from 0 to 359 degrees. + {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Paragraphs/Format-and-rotate-text-box/.NET/Format-and-rotate-text-box/Program.cs" %} @@ -1701,7 +1716,6 @@ You can download a complete working sample from [GitHub](https://github.com/Sync * [How to find and modify hyperlink address in Word document?](https://support.syncfusion.com/kb/article/12198/find-and-modify-hyperlink-address-in-word-document) * [How to change the character/symbol used for bullet points in Word document?](https://support.syncfusion.com/kb/article/12099/how-to-change-the-character-symbol-used-for-bullet-points-in-word-document) * [How to resize list character in a Word document?](https://support.syncfusion.com/kb/article/12327/how-to-resize-list-character-in-a-word-document) -* [How to resize list character in a Word document?](https://support.syncfusion.com/kb/article/12327/how-to-resize-list-character-in-a-word-document) * [How to modify the formatting for the default format of sections, paragraphs, and tables in a Word document?](https://support.syncfusion.com/kb/article/15884/how-to-modify-the-formatting-for-the-default-format-of-sections-paragraphs-and-tables-in-a-word-document?) * [How to extract images from tables in a Word document?](https://support.syncfusion.com/kb/article/15812/how-to-extract-images-from-tables-in-a-word-document) * [How to replace all OLE objects with text in a Word document?](https://support.syncfusion.com/kb/article/15654/how-to-replace-all-ole-objects-with-text-in-a-word-document) diff --git a/Document-Processing/Word/Word-Library/NET/Working-with-Sections.md b/Document-Processing/Word/Word-Library/NET/Working-with-Sections.md index d73f3c6d3f..181be49e75 100644 --- a/Document-Processing/Word/Word-Library/NET/Working-with-Sections.md +++ b/Document-Processing/Word/Word-Library/NET/Working-with-Sections.md @@ -8,7 +8,7 @@ documentation: UG # Working with Sections -A section contains the contents present in Headers, Footers and main document through the instances of [WTextBody](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WTextBody.html). A section also has a specific set of properties used to define the page settings, number of columns, headers and footers and so on that decide how the text appears. [WTextBody](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WTextBody.html) represents group of paragraphs and tables etc. +A section contains the contents of the headers, footers, and main document body through the instances of [WTextBody](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WTextBody.html). A section also has a specific set of properties used to define the page settings, number of columns, headers and footers and so on that decide how the text appears. [WTextBody](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WTextBody.html) represents a group of paragraphs and tables, etc. N> Refer to the appropriate tabs in the code snippets section: ***C# [Cross-platform]*** for ASP.NET Core, Blazor, Xamarin, UWP, .NET MAUI, and WinUI; ***C# [Windows-specific]*** for WinForms and WPF; ***VB.NET [Windows-specific]*** for VB.NET applications. @@ -52,7 +52,7 @@ Dim section As IWSection = document.AddSection() Dim paragraph As IWParagraph = section.AddParagraph() 'Appends the text to the created paragraph paragraph.AppendText("AdventureWorks Cycles, the fictitious company on which the AdventureWorks sample databases are based, is a large, multinational manufacturing company.") -‘Saves and closes the Word document instance +'Saves and closes the Word document instance document.Save("Sample.docx", FormatType.Docx) document.Close() {% endhighlight %} @@ -61,9 +61,9 @@ document.Close() You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Sections/Add-sections-in-Word-document). -You can add the multiple sections into the document. When you add more than one section into the word document, the section starts from the next page by default. +You can add multiple sections to the document. When you add more than one section to the Word document, the section starts on a new page by default. -You can also add a new section that starts on a same page by specifying the [BreakCode](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WSection.html#Syncfusion_DocIO_DLS_WSection_BreakCode) as shown in following code example. +You can also add a new section that starts on the same page by specifying the [BreakCode](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WSection.html#Syncfusion_DocIO_DLS_WSection_BreakCode) as shown in the following code example. {% tabs %} @@ -132,7 +132,7 @@ section.BreakCode = SectionBreakCode.NoBreak paragraph = section.AddParagraph() 'Appends the text to the created paragraph paragraph.AppendText(paraText) -‘Saves and closes the Word document instance +'Saves and closes the Word document instance document.Save("Sample.docx", FormatType.Docx) document.Close() {% endhighlight %} @@ -209,7 +209,7 @@ section.PageSetup.OtherPagesTray = PrinterPaperTray.MiddleBin Dim paragraph As IWParagraph = section.AddParagraph() 'Appends the text to the created paragraph. paragraph.AppendText("AdventureWorks Cycles, the fictitious company on which the AdventureWorks sample databases are based, is a large, multinational manufacturing company.") -‘Saves and closes the Word document instance +'Saves and closes the Word document instance document.Save("Sample.docx", FormatType.Docx) document.Close() {% endhighlight %} @@ -218,7 +218,7 @@ document.Close() You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Sections/Page-setup-properties). -## Creating Multi-column document +## Creating a Multi-column Document You can split the contents into two or more columns by specifying the column width and spacing between columns. @@ -328,7 +328,7 @@ paragraph.AppendBreak(BreakType.ColumnBreak) paragraph = section.AddParagraph() 'Appends the text to the created paragraph paragraph.AppendText(paraText) -‘Saves and closes the Word document instance +'Saves and closes the Word document instance document.Save("Sample.docx", FormatType.Docx) document.Close() {% endhighlight %} @@ -339,7 +339,7 @@ You can download a complete working sample from [GitHub](https://github.com/Sync ## Creating document with different page settings -You can prefer to have more sections in a Word document when you need to have different page settings or headers and footers for a specific set of contents. The following code example illustrates how to create a Word document with multiple sections whose page orientation are portrait and landscape respectively. +You can prefer to have more sections in a Word document when you need to have different page settings or headers and footers for a specific set of contents. The following code example illustrates how to create a Word document with multiple sections whose page orientation is portrait and landscape, respectively. {% tabs %} @@ -430,7 +430,7 @@ section.PageSetup.PageSize = PageSize.A4; section.PageSetup.Orientation = PageOrientation.Landscape 'Appends the text to the paragraph paragraph.AppendText(paraText) -‘Saves and closes the Word document instance +'Saves and closes the Word document instance document.Save("Sample.docx", FormatType.Docx) document.Close() {% endhighlight %} @@ -538,7 +538,7 @@ paragraph.AppendText("[ Default Page Header ]") 'Inserts the default Page footer paragraph = section.HeadersFooters.OddFooter.AddParagraph() paragraph.AppendText("[ Default Page Footer ]") -‘Saves and closes the Word document instance +'Saves and closes the Word document instance document.Save("Sample.docx", FormatType.Docx) document.Close() {% endhighlight %} @@ -659,7 +659,7 @@ paragraph.AppendText("[ Default Page Header ]") 'Inserts the default page footer paragraph = section.HeadersFooters.OddFooter.AddParagraph() paragraph.AppendText("[ Default Page Footer ]") -‘Saves and closes the Word document instance +'Saves and closes the Word document instance document.Save("Sample.docx", FormatType.Docx) document.Close() {% endhighlight %} @@ -782,7 +782,7 @@ paragraph.AppendText("[Even Page Header ]") 'Inserts the even page footer paragraph = section.HeadersFooters.EvenFooter.AddParagraph() paragraph.AppendText("[ Even Page Footer ]") -‘Saves and closes the Word document instance +'Saves and closes the Word document instance document.Save("Sample.docx", FormatType.Docx) document.Close() {% endhighlight %} @@ -911,7 +911,7 @@ section.HeadersFooters.Footer.AddParagraph().AppendText("[ Third Section Footer 'Appends some text to the third page in document paragraph = section.AddParagraph() paragraph.AppendText(Convert.ToString(vbCr & vbCr & "[ Third Page ] " & vbCr & vbCr) & paraText) -‘Saves and closes the Word document instance +'Saves and closes the Word document instance document.Save("Sample.docx", FormatType.Docx) document.Close() {% endhighlight %} @@ -1180,7 +1180,7 @@ paragraph.AppendField("TotalNumberOfPages", FieldType.FieldNumPages) paragraph = section.AddParagraph() 'Appends the text to the created paragraph paragraph.AppendText("AdventureWorks Cycles, the fictitious company on which the AdventureWorks sample databases are based, is a large, multinational manufacturing company.") -‘Saves and closes the Word document instance +'Saves and closes the Word document instance document.Save("Sample.docx", FormatType.Docx) document.Close() {% endhighlight %} @@ -1287,7 +1287,7 @@ paragraph.AppendText("[ Default Page Header ]") 'Inserts the default page footer paragraph = section.HeadersFooters.OddFooter.AddParagraph() paragraph.AppendText("[ Default Page Footer ]") -‘Saves and closes the Word document instance +'Saves and closes the Word document instance document.Save("Sample.docx", FormatType.Docx) document.Close() {% endhighlight %} @@ -1366,11 +1366,11 @@ Using document As WordDocument = New WordDocument() section.PageSetup.Borders.Color = Color.Blue 'Set the linewidth of the borders. section.PageSetup.Borders.LineWidth = 0.75F - //Set the page border margins. - section.PageSetup.Borders.Top.Space = 5F; - section.PageSetup.Borders.Bottom.Space = 5F; - section.PageSetup.Borders.Right.Space = 5F; - section.PageSetup.Borders.Left.Space = 5F; + 'Set the page border margins. + section.PageSetup.Borders.Top.Space = 5F + section.PageSetup.Borders.Bottom.Space = 5F + section.PageSetup.Borders.Right.Space = 5F + section.PageSetup.Borders.Left.Space = 5F 'Add a paragraph to a section. Dim paragraph As IWParagraph = section.AddParagraph() paragraph.AppendText("AdventureWorks Cycles, the fictitious company on which the AdventureWorks sample databases are based, is a large, multinational manufacturing company.") @@ -1504,7 +1504,7 @@ document.Close(); Dim document As New WordDocument(inputFileName) 'Removes the second section from the collection document.Sections.RemoveAt(1) -‘Saves and closes the Word document instance +'Saves and closes the Word document instance document.Save("Sample.docx", FormatType.Docx) document.Close() {% endhighlight %} diff --git a/Document-Processing/Word/Word-Library/NET/Working-with-Shapes.md b/Document-Processing/Word/Word-Library/NET/Working-with-Shapes.md index 9ff2566e65..841cdd3d78 100644 --- a/Document-Processing/Word/Word-Library/NET/Working-with-Shapes.md +++ b/Document-Processing/Word/Word-Library/NET/Working-with-Shapes.md @@ -6,15 +6,13 @@ control: DocIO documentation: UG keywords: --- -# Working with Shapes for File-Formats Platform DocIO Control +# Working with Shapes in .NET Word (DocIO) Library -Shapes are drawing objects that include lines, curves, circles, rectangles, etc. It can be preset or custom geometry. You can create and manipulate the pre-defined shape in DOCX and WordML format documents. +Shapes are drawing objects that can include lines, curves, circles, rectangles, and so on. A shape can have preset or custom geometry. You can create and manipulate preset shapes in DOCX and WordML format documents. ## Adding shapes -The following code example illustrates how to add pre-defined shape to the document. - -N> Refer to the appropriate tabs in the code snippets section: ***C# [Cross-platform]*** for ASP.NET Core, Blazor, Xamarin, UWP, .NET MAUI, and WinUI; ***C# [Windows-specific]*** for WinForms and WPF; ***VB.NET [Windows-specific]*** for VB.NET applications. +The following code example illustrates how to add a preset shape to the document. {% tabs %} @@ -70,10 +68,10 @@ IWTextRange text = paragraph.AppendText("This text is in rounded rectangle shape text.CharacterFormat.TextColor = Color.Green; text.CharacterFormat.Bold = true; //Adds another shape to the document -paragraph = section.AddParagraph()as WParagraph; +paragraph = section.AddParagraph() as WParagraph; paragraph.AppendBreak(BreakType.LineBreak); Shape pentagon = paragraph.AppendShape(AutoShapeType.Pentagon, 100, 100); -paragraph = pentagon.TextBody.AddParagraph()as WParagraph; +paragraph = pentagon.TextBody.AddParagraph() as WParagraph; paragraph.AppendText("This text is in pentagon shape"); pentagon.HorizontalPosition = 72; pentagon.VerticalPosition = 200; @@ -121,7 +119,9 @@ You can download a complete working sample from [GitHub](https://github.com/Sync ### Format shapes -Shape can have formatting such as line color, fill color, positioning, wrap formats, etc. The following code example illustrates how to apply formatting options for shape. +A shape can have formatting such as line color, fill color, positioning, and wrap formats. The following code example illustrates how to apply formatting options to a shape. + +N> `FillFormat.Transparency` accepts a value from 0 to 100 (percentage). {% tabs %} @@ -230,7 +230,7 @@ text.CharacterFormat.Bold = True rectangle.FillFormat.Fill = True rectangle.FillFormat.Color = Color.LightGray 'Set transparency (opacity) to the shape fill color. -rectangle.FillFormat.Transparency = 75; +rectangle.FillFormat.Transparency = 75 'Apply wrap formats rectangle.WrapFormat.TextWrappingStyle = TextWrappingStyle.Square rectangle.WrapFormat.TextWrappingType = TextWrappingType.Right @@ -331,7 +331,7 @@ paragraph = TryCast(rectangle.TextBody.AddParagraph(), WParagraph) Dim text As IWTextRange = paragraph.AppendText("This text is in rounded rectangle shape") 'Saves and closes the Word document document.Save("Sample.docx", FormatType.Docx) -document.Close +document.Close() {% endhighlight %} {% endtabs %} @@ -340,20 +340,21 @@ You can download a complete working sample from [GitHub](https://github.com/Sync ## Grouping shapes -Word library now allows you to create or group multiple shapes, pictures, text boxes, and charts as a group shape in Word document (DOCX) and preserve it as in DOCX and WordML format conversions. +The .NET Word (DocIO) library allows you to group multiple shapes, pictures, text boxes, and charts as a single group shape in a Word document (DOCX). These group shapes are preserved in DOCX and WordML format conversions. -You can create a document with group shapes by using Microsoft Word. It provides an option to group a set of shapes and images as a single shape and a group shape as individual item. +Microsoft Word provides an option to group a set of shapes and images as a single shape and to later ungroup it back into individual items. ![Create Group shape in Microsoft Word](Working-with-Shapes_images/Working-with-Shapes_img1.jpeg) **Key Features:** -1. You can easily manage group of shapes, pictures, text boxes, or charts as a group shape. -2. You can move several shapes or images simultaneously and apply the same formatting properties for children of group shapes. +1. You can easily manage a group of shapes, pictures, text boxes, or charts as a group shape. +2. You can move several shapes or images simultaneously and apply the same formatting properties to the children of a group shape. -N> 1. While grouping the shapes or other objects, the shapes should be positioned relative to the “Page”. -N> 2. While grouping the shapes or other objects, the wrapping style should not be "In Line with Text". +N> The following constraints apply while grouping shapes or other objects: +N> 1. The shapes should be positioned relative to the "Page". +N> 2. The wrapping style should not be "In Line with Text". -The following code example illustrates how to create group shape in Word document. +The following code example illustrates how to create a group shape in a Word document. In the sample, an `Image.png` file must be present in the working directory (replace the path as needed). {% tabs %} @@ -490,67 +491,67 @@ document.Close(); {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} -‘Creates a new Word document +'Creates a new Word document Dim document As WordDocument = New WordDocument() -‘Adds new section to the document +'Adds new section to the document Dim section As IWSection = document.AddSection() -‘Adds new paragraph to the section +'Adds new paragraph to the section Dim paragraph As WParagraph = TryCast(section.AddParagraph(), WParagraph) -‘Creates new group shape +'Creates new group shape Dim groupShape As GroupShape = New GroupShape(document) -‘Adds group shape to the paragraph +'Adds group shape to the paragraph paragraph.ChildEntities.Add(groupShape) -‘Creates new shape +'Creates new shape Dim shape As Shape = New Shape(document, AutoShapeType.RoundedRectangle) -‘Sets height and width for shape +'Sets height and width for shape shape.Height = 100 shape.Width = 150 -‘Sets horizontal and vertical position +'Sets horizontal and vertical position shape.HorizontalPosition = 72 shape.VerticalPosition = 72 -‘Sets wrapping style for shape +'Sets wrapping style for shape shape.WrapFormat.TextWrappingStyle = TextWrappingStyle.InFrontOfText -‘Sets horizontal and vertical origin +'Sets horizontal and vertical origin shape.HorizontalOrigin = HorizontalOrigin.Page shape.VerticalOrigin = VerticalOrigin.Page -‘Adds the specified shape to group shape +'Adds the specified shape to group shape groupShape.Add(shape) -‘Creates new picture +'Creates new picture Dim picture As WPicture = New WPicture(document) picture.LoadImage(Image.FromFile("Image.png")) -‘Sets wrapping style for picture +'Sets wrapping style for picture picture.TextWrappingStyle = TextWrappingStyle.InFrontOfText -‘Sets height and width for the image +'Sets height and width for the image picture.Height = 100 picture.Width = 100 -‘Sets horizontal and vertical position +'Sets horizontal and vertical position picture.HorizontalPosition = 400 picture.VerticalPosition = 150 -‘Sets horizontal and vertical origin +'Sets horizontal and vertical origin picture.HorizontalOrigin = HorizontalOrigin.Page picture.VerticalOrigin = VerticalOrigin.Page -‘Adds the specified picture to group shape +'Adds the specified picture to group shape groupShape.Add(picture) -‘Creates new textbox +'Creates new textbox Dim textbox As WTextBox = New WTextBox(document) textbox.TextBoxFormat.Width = 150 textbox.TextBoxFormat.Height = 75 -‘Adds new text to the textbox body +'Adds new text to the textbox body Dim textboxParagraph As IWParagraph = textbox.TextBoxBody.AddParagraph() textboxParagraph.AppendText("Text inside text box") -‘Sets wrapping style for textbox +'Sets wrapping style for textbox textbox.TextBoxFormat.TextWrappingStyle = TextWrappingStyle.Behind -‘Sets horizontal and vertical position +'Sets horizontal and vertical position textbox.TextBoxFormat.HorizontalPosition = 200 textbox.TextBoxFormat.VerticalPosition = 200 -‘Sets horizontal and vertical origin +'Sets horizontal and vertical origin textbox.TextBoxFormat.VerticalOrigin = VerticalOrigin.Page textbox.TextBoxFormat.HorizontalOrigin = HorizontalOrigin.Page -‘Adds the specified textbox to group shape +'Adds the specified textbox to group shape groupShape.Add(textbox) -‘Saves the Word document +'Saves the Word document document.Save("Sample.docx", FormatType.Docx) -‘Closes the document +'Closes the document document.Close() {% endhighlight %} @@ -558,7 +559,7 @@ document.Close() You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Shapes/Add-group-shape-in-Word). -The following code example illustrates how to add collection of shapes or images as a group shape in Word document. +The following code example illustrates how to add a collection of shapes, text boxes, and charts as a group shape by passing an array of paragraph items to the `GroupShape` constructor. {% tabs %} @@ -579,7 +580,7 @@ shape.Width = 150; //Sets Wrapping style for shape shape.WrapFormat.TextWrappingStyle = TextWrappingStyle.InFrontOfText; //Sets horizontal and vertical position for shape -shape.HorizontalPosition = 7; +shape.HorizontalPosition = 72; shape.VerticalPosition = 72; //Sets horizontal and vertical origin for shape shape.HorizontalOrigin = HorizontalOrigin.Page; @@ -687,7 +688,7 @@ shape.Width = 150; //Sets Wrapping style for shape shape.WrapFormat.TextWrappingStyle = TextWrappingStyle.InFrontOfText; //Sets horizontal and vertical position for shape -shape.HorizontalPosition = 7; +shape.HorizontalPosition = 72; shape.VerticalPosition = 72; //Sets horizontal and vertical origin for shape shape.HorizontalOrigin = HorizontalOrigin.Page; @@ -768,7 +769,7 @@ chart.PrimaryCategoryAxis.CategoryLabels = chart.ChartData[2, 1, 11, 1]; paragraphItems[2] = chart; //Creates new group shape GroupShape groupShape = new GroupShape(document, paragraphItems); - groupShape.HorizontalPosition = 72; +groupShape.HorizontalPosition = 72; //Adds the group shape to the paragraph paragraph.ChildEntities.Add(groupShape); //Saves the Word document @@ -778,64 +779,64 @@ document.Close(); {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} -‘Creates a new Word document +'Creates a new Word document Dim document As WordDocument = New WordDocument() -‘Adds new section to the document +'Adds new section to the document Dim section As IWSection = document.AddSection() -‘Adds new paragraph to the section +'Adds new paragraph to the section Dim paragraph As WParagraph = TryCast(section.AddParagraph(), WParagraph) -‘Creates paragraph item collections to add child shapes +'Creates paragraph item collections to add child shapes Dim paragraphItems As ParagraphItem() = New ParagraphItem(2) {} -‘Creates new shape +'Creates new shape Dim shape As Shape = New Shape(document, AutoShapeType.RoundedRectangle) -‘Sets height and width for shape +'Sets height and width for shape shape.Height = 100 shape.Width = 150 -‘Sets Wrapping style for shape +'Sets Wrapping style for shape shape.WrapFormat.TextWrappingStyle = TextWrappingStyle.InFrontOfText -‘Sets horizontal and vertical position for shape -shape.HorizontalPosition = 7 +'Sets horizontal and vertical position for shape +shape.HorizontalPosition = 72 shape.VerticalPosition = 72 -‘Sets horizontal and vertical origin for shape +'Sets horizontal and vertical origin for shape shape.HorizontalOrigin = HorizontalOrigin.Page shape.VerticalOrigin = VerticalOrigin.Page -‘Sets the shape as paragraph item +'Sets the shape as paragraph item paragraphItems(0) = shape -‘Appends new textbox to the document +'Appends new textbox to the document Dim textbox As WTextBox = New WTextBox(document) -‘Sets height and width for textbox +'Sets height and width for textbox textbox.TextBoxFormat.Width = 150 textbox.TextBoxFormat.Height = 75 -‘Adds new text to the textbox body +'Adds new text to the textbox body Dim textboxParagraph As IWParagraph = textbox.TextBoxBody.AddParagraph() -‘Adds new text to the textbox paragraph +'Adds new text to the textbox paragraph textboxParagraph.AppendText("Text inside text box") -‘Sets wrapping style for textbox +'Sets wrapping style for textbox textbox.TextBoxFormat.TextWrappingStyle = TextWrappingStyle.Behind -‘Sets horizontal and vertical position for textbox +'Sets horizontal and vertical position for textbox textbox.TextBoxFormat.HorizontalPosition = 200 textbox.TextBoxFormat.VerticalPosition = 200 -‘Sets horizontal and vertical origin for textbox +'Sets horizontal and vertical origin for textbox textbox.TextBoxFormat.VerticalOrigin = VerticalOrigin.Page textbox.TextBoxFormat.HorizontalOrigin = HorizontalOrigin.Page -‘Sets the textbox as paragraph item +'Sets the textbox as paragraph item paragraphItems(1) = textbox -‘Appends new chart to the document +'Appends new chart to the document Dim chart As WChart = New WChart(document) -‘Sets height and width for chart +'Sets height and width for chart chart.Height = 270 chart.Width = 446 -‘Sets wrapping style for chart +'Sets wrapping style for chart chart.WrapFormat.TextWrappingStyle = TextWrappingStyle.InFrontOfText -‘Sets chart type +'Sets chart type chart.ChartType = OfficeChartType.Pie chart.VerticalPosition = 350 -‘Sets chart title -‘Sets font and size for chart title +'Sets chart title +'Sets font and size for chart title chart.ChartTitle = "Best Selling Products" chart.ChartTitleArea.FontName = "Calibri" chart.ChartTitleArea.Size = 14 -‘Sets data for chart +'Sets data for chart chart.ChartData.SetValue(1, 1, "") chart.ChartData.SetValue(1, 2, "Sales") chart.ChartData.SetValue(2, 1, "Phyllis Lapin") @@ -858,29 +859,29 @@ chart.ChartData.SetValue(10, 1, "Christina Berglund") chart.ChartData.SetValue(10, 2, 29.171) chart.ChartData.SetValue(11, 1, "Elizabeth Lincoln") chart.ChartData.SetValue(11, 2, 25.696) -‘Creates a new chart series with the name “Sales” +'Creates a new chart series with the name "Sales" Dim pieSeries As IOfficeChartSerie = chart.Series.Add("Sales") -‘Sets value for the chart series +'Sets value for the chart series pieSeries.Values = chart.ChartData(2, 2, 11, 2) -‘Sets data label +'Sets data label pieSeries.DataPoints.DefaultDataPoint.DataLabels.IsValue = True pieSeries.DataPoints.DefaultDataPoint.DataLabels.Position = OfficeDataLabelPosition.Outside -‘Sets background color +'Sets background color chart.ChartArea.Fill.ForeColor = Color.FromArgb(242, 242, 242) chart.PlotArea.Fill.ForeColor = Color.FromArgb(242, 242, 242) chart.ChartArea.Border.LinePattern = OfficeChartLinePattern.None -‘Sets category labels +'Sets category labels chart.PrimaryCategoryAxis.CategoryLabels = chart.ChartData(2, 1, 11, 1) -‘Sets the chart as paragraph item +'Sets the chart as paragraph item paragraphItems(2) = chart -‘Creates new group shape +'Creates new group shape Dim groupShape As GroupShape = New GroupShape(document, paragraphItems) groupShape.HorizontalPosition = 72 -‘Adds the group shape to the paragraph +'Adds the group shape to the paragraph paragraph.ChildEntities.Add(groupShape) -‘Saves the Word document +'Saves the Word document document.Save("Sample.docx", FormatType.Docx) -‘Closes the document +'Closes the document document.Close() {% endhighlight %} @@ -890,7 +891,7 @@ You can download a complete working sample from [GitHub](https://github.com/Sync ### Nested group shapes -The following code example illustrates how to group the nested group shapes as a group shape in Word document. +You can nest one group shape inside another. The following code example illustrates how to group nested group shapes as a single group shape in a Word document. {% tabs %} @@ -1073,91 +1074,91 @@ document.Close(); {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} -‘Creates a new Word document +'Creates a new Word document Dim document As WordDocument = New WordDocument() -‘Adds new section to the document +'Adds new section to the document Dim section As IWSection = document.AddSection() -‘Adds new paragraph to the section +'Adds new paragraph to the section Dim paragraph As WParagraph = TryCast(section.AddParagraph(), WParagraph) -‘Creates new group shape +'Creates new group shape Dim groupShape As GroupShape = New GroupShape(document) -‘Adds group shape to the paragraph +'Adds group shape to the paragraph paragraph.ChildEntities.Add(groupShape) -‘Appends new shape to the document +'Appends new shape to the document Dim shape As Shape = New Shape(document, AutoShapeType.RoundedRectangle) -‘Sets height and width for shape +'Sets height and width for shape shape.Height = 100 shape.Width = 150 -‘Sets Wrapping style for shape +'Sets Wrapping style for shape shape.WrapFormat.TextWrappingStyle = TextWrappingStyle.InFrontOfText -‘Sets horizontal and vertical position for shape +'Sets horizontal and vertical position for shape shape.HorizontalPosition = 72 shape.VerticalPosition = 72 -‘Sets horizontal and vertical origin for shape +'Sets horizontal and vertical origin for shape shape.HorizontalOrigin = HorizontalOrigin.Page shape.VerticalOrigin = VerticalOrigin.Page -‘Adds the specified shape to group shape +'Adds the specified shape to group shape groupShape.Add(shape) -‘Appends new picture to the document +'Appends new picture to the document Dim picture As WPicture = New WPicture(document) -‘Loads image from the file -picture.LoadImage(Image.FromFile("Image.jpg")) -‘Sets wrapping style for picture +'Loads image from the file +picture.LoadImage(Image.FromFile("Image.png")) +'Sets wrapping style for picture picture.TextWrappingStyle = TextWrappingStyle.InFrontOfText -‘Sets height and width for the picture +'Sets height and width for the picture picture.Height = 100 picture.Width = 100 -‘Sets horizontal and vertical position for the picture +'Sets horizontal and vertical position for the picture picture.HorizontalPosition = 400 picture.VerticalPosition = 150 -‘Sets horizontal and vertical origin for the picture +'Sets horizontal and vertical origin for the picture picture.HorizontalOrigin = HorizontalOrigin.Page picture.VerticalOrigin = VerticalOrigin.Page -‘Adds specified picture to the group shape +'Adds specified picture to the group shape groupShape.Add(picture) -‘Creates new nested group shape +'Creates new nested group shape Dim nestedGroupShape As GroupShape = New GroupShape(document) -‘Appends new textbox to the document +'Appends new textbox to the document Dim textbox As WTextBox = New WTextBox(document) -‘Sets width and height for the textbox +'Sets width and height for the textbox textbox.TextBoxFormat.Width = 150 textbox.TextBoxFormat.Height = 75 -‘Adds new text to the textbox body +'Adds new text to the textbox body Dim textboxParagraph As IWParagraph = textbox.TextBoxBody.AddParagraph() -‘Adds new text to the textbox paragraph +'Adds new text to the textbox paragraph textboxParagraph.AppendText("Text inside text box") -‘Sets wrapping style for the textbox +'Sets wrapping style for the textbox textbox.TextBoxFormat.TextWrappingStyle = TextWrappingStyle.Behind -‘Sets horizontal and vertical position for the textbox +'Sets horizontal and vertical position for the textbox textbox.TextBoxFormat.HorizontalPosition = 200 textbox.TextBoxFormat.VerticalPosition = 200 -‘Sets horizontal and vertical origin for the textbox +'Sets horizontal and vertical origin for the textbox textbox.TextBoxFormat.VerticalOrigin = VerticalOrigin.Page textbox.TextBoxFormat.HorizontalOrigin = HorizontalOrigin.Page -‘Adds specified textbox to the nested group shape +'Adds specified textbox to the nested group shape nestedGroupShape.Add(textbox) -‘Appends new shape to the document +'Appends new shape to the document shape = New Shape(document, AutoShapeType.Oval) -‘Sets height and width for the new shape +'Sets height and width for the new shape shape.Height = 100 shape.Width = 150 -‘Sets horizontal and vertical position for the shape +'Sets horizontal and vertical position for the shape shape.HorizontalPosition = 200 shape.VerticalPosition = 72 -‘Sets horizontal and vertical origin for the shape +'Sets horizontal and vertical origin for the shape shape.HorizontalOrigin = HorizontalOrigin.Page shape.VerticalOrigin = VerticalOrigin.Page -‘Sets horizontal and vertical position for the nested group shape +'Sets horizontal and vertical position for the nested group shape nestedGroupShape.HorizontalPosition = 72 nestedGroupShape.VerticalPosition = 72 -‘Adds specified shape to the nested group shape +'Adds specified shape to the nested group shape nestedGroupShape.Add(shape) -‘Adds nested group shape to the group shape of the paragraph +'Adds nested group shape to the group shape of the paragraph groupShape.Add(nestedGroupShape) groupShape.HorizontalPosition = 142 -‘Saves the Word document +'Saves the Word document document.Save("Sample.docx", FormatType.Docx) -‘Closes the document +'Closes the document document.Close() {% endhighlight %} @@ -1167,9 +1168,11 @@ You can download a complete working sample from [GitHub](https://github.com/Sync ## Ungrouping shapes -You can ungroup the group shapes in the Word document to preserve each shape as individual item. +You can ungroup group shapes in a Word document so that each shape is preserved as an individual item. + +N> The following example assumes that the template document (`Template.docx`) contains a `GroupShape` in its last paragraph. To locate group shapes in arbitrary documents, iterate through the paragraphs and paragraph items of each section. -The following code example illustrates how to ungroup the group shape in Word document. +The following code example illustrates how to ungroup a group shape in a Word document. {% tabs %} @@ -1245,7 +1248,7 @@ You can download a complete working sample from [GitHub](https://github.com/Sync ## Online Demo * Explore how to create a Word document with shapes using the [.NET Word Library](https://www.syncfusion.com/document-sdk/net-word-library) (DocIO) in a live demo [here](https://document.syncfusion.com/demos/word/autoshapes#/tailwind). -* See how to create a Word document with group shapes using the [.NET Word Library](https://www.syncfusion.com/document-sdk/net-word-library) (DocIO) in a live demo [here](https://document.syncfusion.com/demos/word/groupshapes#/tailwind). +* See how to create a Word document with group shapes using the [.NET Word Library](https://www.syncfusion.com/document-sdk/net-word-library) (DocIO) in a live demo [here](https://document.syncfusion.com/demos/word/groupshapes#/tailwind). ## See Also diff --git a/Document-Processing/Word/Word-Library/NET/Working-with-Tables.md b/Document-Processing/Word/Word-Library/NET/Working-with-Tables.md index cb1cad82f4..daa6b88b1d 100644 --- a/Document-Processing/Word/Word-Library/NET/Working-with-Tables.md +++ b/Document-Processing/Word/Word-Library/NET/Working-with-Tables.md @@ -5,14 +5,14 @@ platform: document-processing control: DocIO documentation: UG --- -# Working with Tables in Word document +# Working with Tables in a Word document A table in Word document is used to arrange document content in rows and columns. [WTable](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WTable.html) instance represents a table in Word document. A table must contain at least one row. 1. A row is a collection of cells and it is represented by an instance of [WTableRow](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WTableRow.html). Each row must contain at least one cell. 2. A cell can contain one or more paragraphs and tables. An instance of [WTableCell](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WTableCell.html) represents a table cell. Each table cell must contain at least one paragraph. -N> Adding more than 63 columns not supported in Word document using Microsoft Word application. It shows alert when you attempt to insert table with more than 64 columns, which is a one of the behaviors of Microsoft Word and Essential® DocIO does the same. +N> Adding more than 63 columns is not supported in Word document using Microsoft Word application. It shows an alert when you attempt to insert a table with more than 64 columns, which is one of the behaviors of Microsoft Word and Essential® DocIO does the same. The following image illustrates how a table in Word document is organized in EssentialDocIO’s DOM: @@ -364,7 +364,7 @@ nestedCell.Width = 200; nestedCell.AddParagraph().AppendText("Mango"); //Accesses the instance of the cell (second row, second cell) nestedCell = table.Rows[1].Cells[1]; -table[1, 1].AddParagraph().AppendText("85"); +nestedCell.AddParagraph().AppendText("85"); table[2, 0].AddParagraph().AppendText("Pomegranate"); table[2, 1].AddParagraph().AppendText("70"); //Saves the Word document to MemoryStream @@ -408,7 +408,7 @@ nestedCell.Width = 200; nestedCell.AddParagraph().AppendText("Mango"); //Accesses the instance of the cell (second row, second cell) nestedCell = table.Rows[1].Cells[1]; -table[1, 1].AddParagraph().AppendText("85"); +nestedCell.AddParagraph().AppendText("85"); table[2, 0].AddParagraph().AppendText("Pomegranate"); table[2, 1].AddParagraph().AppendText("70"); //Saves and closes the document instance @@ -450,7 +450,7 @@ nestedCell.Width = 200 nestedCell.AddParagraph().AppendText("Mango") 'Accesses the instance of the cell (second row, second cell) nestedCell = table.Rows(1).Cells(1) -table(1, 1).AddParagraph().AppendText("85") +nestedCell.AddParagraph().AppendText("85") table(2, 0).AddParagraph().AppendText("Pomegranate") table(2, 1).AddParagraph().AppendText("70") 'Saves and closes the document instance @@ -464,7 +464,7 @@ You can download a complete working sample from [GitHub](https://github.com/Sync ## Align text within a table -You can iterate the cells within a table and align text for each cell. Find more information about iterating the cells from [here](https://help.syncfusion.com/document-processing/word/word-library/net/working-with-tables#iterating-through-table-elements) +You can iterate the cells within a table and align text for each cell. Find more information about iterating the cells from [here](https://help.syncfusion.com/document-processing/word/word-library/net/working-with-tables#iterating-through-table-elements). The following code example illustrates how to align text within a table. @@ -680,7 +680,7 @@ End Using You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Tables/Insert-image-in-cell). -## Apply formatting to Table, Row and Cell +## Apply formatting to Table and Row The following code example illustrates how to load an existing document and apply table formatting options such as [Borders](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.RowFormat.html#Syncfusion_DocIO_DLS_RowFormat_Borders), [LeftIndent](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.RowFormat.html#Syncfusion_DocIO_DLS_RowFormat_LeftIndent), [Paddings](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.RowFormat.html#Syncfusion_DocIO_DLS_RowFormat_Paddings), [IsAutoResized](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.RowFormat.html#Syncfusion_DocIO_DLS_RowFormat_IsAutoResized), etc. @@ -692,9 +692,8 @@ N> 4. As in the Microsoft Word, DocIO supports [RowFormat.Borders](https://help. {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Tables/Apply-table-formatting/.NET/Apply-table-formatting/Program.cs" %} -//Creates an instance of WordDocument class (Empty Word Document) -FileStream fileStreamPath = new FileStream("Table.docx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //Opens an existing Word document into DocIO instance +FileStream fileStreamPath = new FileStream("Table.docx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); WordDocument document = new WordDocument(fileStreamPath, FormatType.Docx); //Accesses the instance of the first section in the Word document WSection section = document.Sections[0]; @@ -845,6 +844,8 @@ You can download a complete working sample from [GitHub](https://github.com/Sync Using DocIO, you can format table cells by setting text wrapping to control content flow and adjusting text direction for better readability. You can also customize cell borders, apply vertical alignment, and set a background color to enhance the table’s appearance. +N> In the following snippets, the `row` and `cell` variables are assumed to be obtained from an existing table (for example, `WTableRow row = table.Rows[0];` and `WTableCell cell = row.Cells[0];`). See the [Apply formatting to Table and Row](#apply-formatting-to-table-and-row) section for how to access a table and its rows. + #### Set cell background color The following code snippet illustrates how to specify the background color of a table cell using the [CellFormat.BackColor](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.CellFormat.html#Syncfusion_DocIO_DLS_CellFormat_BackColor) property. @@ -1054,15 +1055,15 @@ WordDocument document = new WordDocument(fileStreamPath, FormatType.Docx); WSection section = document.Sections[0]; //Accesses the instance of the first table in the section WTable table = section.Tables[0] as WTable; -//Resizes the table to fit the contents respect to the contents +//Resizes the table to fit its contents table.AutoFit(AutoFitType.FitToContent); //Accesses the instance of the second table in the section table = section.Tables[1] as WTable; -//Resizes the table to fit the contents respect to window/page width +//Resizes the table to fit the window/page width table.AutoFit(AutoFitType.FitToWindow); //Accesses the instance of the third table in the section table = section.Tables[2] as WTable; -//Resizes the table to fit the contents respect to fixed column width +//Resizes the table to fit the fixed column width table.AutoFit(AutoFitType.FixedColumnWidth); //Saves the Word document to MemoryStream MemoryStream stream = new MemoryStream(); @@ -1072,23 +1073,23 @@ document.Close(); {% endhighlight %} {% highlight c# tabtitle="C# [Windows-specific]" %} -//Creates an instance of WordDocument class (Empty Word Document)*'| markdownify }} +//Creates an instance of WordDocument class (Empty Word Document) WordDocument document = new WordDocument(); //Opens an existing Word document into DocIO instance -document.Open("Template", FormatType.Docx); +document.Open("Template.docx", FormatType.Docx); //Accesses the instance of the first section in the Word document WSection section = document.Sections[0]; //Accesses the instance of the first table in the section WTable table = section.Tables[0] as WTable; -//Resizes the table to fit the contents respect to the contents +//Resizes the table to fit its contents table.AutoFit(AutoFitType.FitToContent); //Accesses the instance of the second table in the section table = section.Tables[1] as WTable; -//Resizes the table to fit the contents respect to window/page width +//Resizes the table to fit the window/page width table.AutoFit(AutoFitType.FitToWindow); //Accesses the instance of the third table in the section table = section.Tables[2] as WTable; -//Resizes the table to fit the contents respect to fixed column width +//Resizes the table to fit the fixed column width table.AutoFit(AutoFitType.FixedColumnWidth); //Saves and closes the document instance document.Save("Sample.docx", FormatType.Docx); @@ -1099,18 +1100,18 @@ document.Close(); 'Creates an instance of WordDocument class (Empty Word Document) Dim document As WordDocument = New WordDocument 'Opens an existing Word document into DocIO instance -document.Open("Template", FormatType.Docx) +document.Open("Template.docx", FormatType.Docx) Dim section As WSection = document.Sections(0) Dim table As WTable = CType(section.Tables(0), WTable) -'Resizes the table to fit the contents respect to the contents +'Resizes the table to fit its contents table.AutoFit(AutoFitType.FitToContent) 'Accesses the instance of the second table in the section table = CType(section.Tables(1), WTable) -'Resizes the table to fit the contents respect to window/page width +'Resizes the table to fit the window/page width table.AutoFit(AutoFitType.FitToWindow) 'Accesses the instance of the third table in the section table = CType(section.Tables(2), WTable) -'Resizes the table to fit the contents respect to fixed column width +'Resizes the table to fit the fixed column width table.AutoFit(AutoFitType.FixedColumnWidth) 'Saves and closes the document instance document.Save("Sample.docx", FormatType.Docx) @@ -1127,7 +1128,7 @@ N> In ASP.NET Core, UWP, and Xamarin platforms, to apply autofit for table in a A table style defines a set of table, row, cell and paragraph level formatting that can be applied to a table. [WTableStyle](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WTableStyle.html) instance represents table style in a Word document. -N> Essential® DocIO currently provides support for table styles in DOCX and WordML formats alone. The visual appearance is also preserved in Word to PDF, Word to Image, and Word to HTML conversions. +N> Essential® DocIO currently provides support for table styles in DOCX and WordML formats only. The visual appearance is also preserved in Word to PDF, Word to Image, and Word to HTML conversions. The following code example illustrates how to apply the built-in table styles to the table. @@ -1180,7 +1181,7 @@ You can download a complete working sample from [GitHub](https://github.com/Sync Once you have applied a table style, you can enable or disable the special formatting of the table. There are six options: first column, last column, banded rows, banded columns, header row and last row. -The following code example illustrates how to enable and disable the special table formatting options of the table styles +The following code example illustrates how to enable and disable the special table formatting options of the table styles. {% tabs %} @@ -1372,11 +1373,11 @@ document.Close() You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Tables/Apply-custom-table-style). -### Apply Base Style +### Apply base style Table styles can be based on other table styles also. When applying a base style, the new style will inherit the values of the base style that are not explicitly redefined in the new style. You can apply a custom table style or a built-in table style as a base for the table style. -The following code example illustrates how to apply built-in and custom table styles as base styles for another custom table. +The following code example illustrates how to apply built-in and custom table styles as base styles for another custom table style. {% tabs %} @@ -1662,7 +1663,7 @@ IWSection section = document.AddSection(); section.AddParagraph().AppendText("Vertical merging of Table cells"); IWTable table = section.AddTable(); table.ResetCells(5, 5); -// Specifies the vertical merge to the third cell, from second row to fifth row +// Specifies the vertical merge to the third column, from second row to fifth row table.ApplyVerticalMerge(2, 1, 4); //Saves the Word document to MemoryStream MemoryStream stream = new MemoryStream(); @@ -1678,7 +1679,7 @@ IWSection section = document.AddSection(); section.AddParagraph().AppendText("Vertical merging of Table cells"); IWTable table = section.AddTable(); table.ResetCells(5, 5); -//Specifies the vertical merge to the third cell, from second row to fifth row +//Specifies the vertical merge to the third column, from second row to fifth row table.ApplyVerticalMerge(2, 1, 4); //Saves and closes the document instance document.Save("VerticalMerge.docx", FormatType.Docx); @@ -1692,7 +1693,7 @@ Dim section As IWSection = document.AddSection() section.AddParagraph().AppendText("Vertical merging of Table cells") Dim table As IWTable = section.AddTable() table.ResetCells(5, 5) -'Specifies the vertical merge to the third cell, from second row to fifth row +'Specifies the vertical merge to the third column, from second row to fifth row table.ApplyVerticalMerge(2, 1, 4) 'Saves and closes the document instance document.Save("VerticalMerge.docx", FormatType.Docx) @@ -1703,7 +1704,9 @@ document.Close() You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Tables/Apply-vertical-merge-to-cells). -The following code example illustrate how to create a table that contains horizontal merged cells. +To merge cells manually, set the [HorizontalMerge](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.CellFormat.html#Syncfusion_DocIO_DLS_CellFormat_HorizontalMerge) or [VerticalMerge](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.CellFormat.html#Syncfusion_DocIO_DLS_CellFormat_VerticalMerge) property of [CellFormat](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.CellFormat.html) to [CellMerge.Start](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.CellMerge.html) for the first cell of the merge range and to [CellMerge.Continue](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.CellMerge.html) for the cells being merged into it. + +The following code example illustrates how to create a table that contains horizontal merged cells. {% tabs %} @@ -1868,7 +1871,7 @@ You can specify one or more rows in a table to be repeated as header row at the * In the case of a single header row, it must be the first row in the table. * In the case of multiple header rows, then header rows must be consecutive from the first row of the table. -N> Heading rows do not have any effect with nested tables in Microsoft Word as well as DocIO +N> Header rows have no effect on nested tables in Microsoft Word or DocIO. The following code example illustrates how to create a table with a single header row. @@ -1962,7 +1965,7 @@ The following code example illustrates how to disable all the table rows from sp {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Tables/Disable-row-to-break-across-pages/.NET/Disable-row-to-break-across-pages/Program.cs" %} //Creates an instance of WordDocument class FileStream fileStreamPath = new FileStream("Template.docx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); -WordDocument document = new WordDocument(fileStreamPath); +WordDocument document = new WordDocument(fileStreamPath, FormatType.Docx); WSection section = document.Sections[0]; WTable table = section.Tables[0] as WTable; //Disables breaking across pages for all rows in the table. @@ -2027,7 +2030,7 @@ foreach (WTableRow row in table.Rows) //Iterates through the paragraphs of the cell foreach (WParagraph paragraph in cell.Paragraphs) { - //When the paragraph contains text Panda then apply green as back color to cell + //When the paragraph contains the text 'panda', apply green as the back color to the cell if (paragraph.Text.Contains("panda")) cell.CellFormat.BackColor = Color.Green; } @@ -2054,7 +2057,7 @@ foreach (WTableRow row in table.Rows) //Iterates through the paragraphs of the cell foreach (WParagraph paragraph in cell.Paragraphs) { - //When the paragraph contains text Panda then apply green as back color to cell + //When the paragraph contains the text 'panda', apply green as the back color to the cell if (paragraph.Text.Contains("panda")) cell.CellFormat.BackColor = Color.Green; } @@ -2076,7 +2079,7 @@ For Each row As WTableRow In table.Rows For Each cell As WTableCell In row.Cells 'Iterates through the paragraphs of the cell For Each paragraph As WParagraph In cell.Paragraphs - 'When the paragraph contains text Panda then apply green as back color to cell + 'When the paragraph contains the text 'panda', apply green as the back color to the cell If paragraph.Text.Contains("panda") Then cell.CellFormat.BackColor = Color.Green End If @@ -2234,7 +2237,6 @@ You can download a complete working sample from [GitHub](https://github.com/Sync * [How to split a table by columns in a Word document](https://support.syncfusion.com/kb/article/17714/how-to-split-a-table-by-columns-in-a-word-document) * [How to add rows with dynamic data into an existing table in Word document](https://support.syncfusion.com/kb/article/17819/how-to-add-rows-with-dynamic-data-into-an-existing-table-in-word-document) * [How to copy table from another Word document with its style?](https://support.syncfusion.com/kb/article/17897/how-to-copy-table-from-another-word-document-with-its-style) -* [How to copy table from another Word document with its style?](https://support.syncfusion.com/kb/article/17897/how-to-copy-table-from-another-word-document-with-its-style) * [How to Replace Field with Table in ASP.NET Core Word Document?](https://support.syncfusion.com/kb/article/17134/how-to-replace-field-with-table-in-aspnet-core-word-document?) * [How to extract tables and add to a new Document in ASP.NETCore Word?](https://support.syncfusion.com/kb/article/19585/how-to-extract-tables-and-add-to-a-new-document-in-aspnetcore-word?) * [How to remove multiple rows from a table in a Word Document?](https://support.syncfusion.com/kb/article/19642/how-to-remove-multiple-rows-from-a-table-in-a-word-document) diff --git a/Document-Processing/Word/Word-Library/NET/mail-merge/mail-merge-events.md b/Document-Processing/Word/Word-Library/NET/mail-merge/mail-merge-events.md index dd4639a7d6..5043f13d8c 100644 --- a/Document-Processing/Word/Word-Library/NET/mail-merge/mail-merge-events.md +++ b/Document-Processing/Word/Word-Library/NET/mail-merge/mail-merge-events.md @@ -8,15 +8,15 @@ documentation: UG # Event support for Mail merge -The [MailMerge](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html) class provides event support to customize the document contents and merging image data during the Mail merge process. The following events are supported by Essential® DocIO during Mail merge process: +The [MailMerge](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html) class provides event support to customize the document contents and merge image data during the Mail merge process. The following events are supported by Syncfusion® DocIO during Mail merge process: -* [MergeField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MergeFieldEventHandler.html)- occurs when a **Mail merge field** except image Mail merge field is encountered. +* [MergeField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MergeFieldEventHandler.html) — occurs when a **Mail merge field** except image Mail merge field is encountered. -* [MergeImageField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MergeImageFieldEventHandler.html)- occurs when an **image Mail merge field** is encountered. +* [MergeImageField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MergeImageFieldEventHandler.html) — occurs when an **image Mail merge field** is encountered. -* [BeforeClearField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BeforeClearFieldEventHandler.html)- occurs when an **unmerged field** is encountered. +* [BeforeClearField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BeforeClearFieldEventHandler.html) — occurs when an **unmerged field** is encountered. -* [BeforeClearGroupField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BeforeClearGroupFieldEventHandler.html)- occurs when an **unmerged group field** is encountered. +* [BeforeClearGroupField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BeforeClearGroupFieldEventHandler.html) — occurs when an **unmerged group field** is encountered. ## MergeField Event @@ -106,8 +106,8 @@ End Sub {% endtabs %} -N> 1. While executing mail merge, DocIO internally uses a copy of a particular region for populating the contents. Sometimes, unexpected problems may arise due to inserting multiple body items into the region through the mail merge process. So, to insert multiple body items using the merge field event handler, you are recommended to use this [approach](https://www.syncfusion.com/kb/11701/how-to-replace-merge-field-with-html-string-using-mail-merge) at your side. -N> 2. The [ExecuteGroup(DataTable)](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html#Syncfusion_DocIO_DLS_MailMerge_ExecuteGroup_System_Data_DataTable_) method is not supported on the UWP platform. +N> 1. While executing mail merge, DocIO internally uses a copy of a particular region for populating the contents. Sometimes, unexpected problems may arise due to inserting multiple body items into the region through the mail merge process. So, to insert multiple body items using the merge field event handler, we recommend using this [approach](https://www.syncfusion.com/kb/11701/how-to-replace-merge-field-with-html-string-using-mail-merge). +N> 2. The [ExecuteGroup(DataTable)](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html#Syncfusion_DocIO_DLS_MailMerge_ExecuteGroup_System_Data_DataTable_) method is not supported on the UWP platform. The cross-platform sample above is not valid for UWP; use an alternative data-binding approach on UWP. The following code example shows GetDataTable method which is used to get data for mail merge. @@ -170,7 +170,7 @@ You can download a complete working sample from [GitHub](https://github.com/Sync You can format the merged image like resizing the image and more during mail merge process using the [MergeImageField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MergeImageFieldEventHandler.html) Event. -N> The [MergeImageField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MergeImageFieldEventHandler.html) event triggers only for image merge fields. Ensure you have a valid image merge field in the template document, following the syntax: **{ MERGEFIELD Image:logo }**. +N> The [MergeImageField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MergeImageFieldEventHandler.html) event triggers only for image merge fields. Ensure you have a valid image merge field in the template document, following the syntax: **{ MERGEFIELD Image:Logo }**. The following code example shows how to use the [MergeImageField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MergeImageFieldEventHandler.html) event during Mail merge process. @@ -183,9 +183,9 @@ WordDocument document = new WordDocument(fileStreamPath, FormatType.Docx); //Uses the mail merge events handler for image fields document.MailMerge.MergeImageField += new MergeImageFieldEventHandler(MergeField_ProductImage); //Specifies the field names and field values -string[] fieldNames = new string[] { "Logo"}; -string[] fieldValues = new string[] { "Logo.png"}; -//Executes the mail merge with groups +string[] fieldNames = new string[] { "Logo" }; +string[] fieldValues = new string[] { "Logo.png" }; +//Executes the mail merge document.MailMerge.Execute(fieldNames, fieldValues); //Saves the Word document to MemoryStream MemoryStream stream = new MemoryStream(); @@ -200,9 +200,9 @@ WordDocument document = new WordDocument("Template.docx"); //Uses the mail merge events handler for image fields document.MailMerge.MergeImageField += new MergeImageFieldEventHandler(MergeField_ProductImage); //Specifies the field names and field values -string[] fieldNames = new string[] { "Logo"}; -string[] fieldValues = new string[] { "Logo.png"}; -//Executes the mail merge with groups +string[] fieldNames = new string[] { "Logo" }; +string[] fieldValues = new string[] { "Logo.png" }; +//Executes the mail merge document.MailMerge.Execute(fieldNames, fieldValues); //Saves and closes WordDocument instance document.Save("Sample.docx"); @@ -217,7 +217,7 @@ AddHandler document.MailMerge.MergeImageField, AddressOf MergeField_ProductImage 'Specifies the field names and field values Dim fieldNames As String() = New String() {"Logo"} Dim fieldValues As String() = New String() {"Logo.png"} -'Executes the mail merge with groups +'Executes the mail merge document.MailMerge.Execute(fieldNames, fieldValues) 'Saves and closes WordDocument instance document.Save("Sample.docx") @@ -298,10 +298,10 @@ The following code example shows how to use the [BeforeClearField](https://help. {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Mail-Merge/Event-to-bind-data-for-unmerged-fields/.NET/Event-to-bind-data-for-unmerged-fields/Program.cs" %} //Opens the template document FileStream fileStreamPath = new FileStream("Template.docx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); -WordDocument document = new WordDocument(fileStreamPath); -//Sets “ClearFields” to true to remove empty mail merge fields from document +WordDocument document = new WordDocument(fileStreamPath, FormatType.Docx); +//Sets “ClearFields” to false to keep empty mail merge fields in the document document.MailMerge.ClearFields = false; -//Uses the mail merge event to clear the unmerged field while perform mail merge execution +//Uses the mail merge event to clear the unmerged field while performing mail merge execution document.MailMerge.BeforeClearField += new BeforeClearFieldEventHandler(BeforeClearFieldEvent); //Execute mail merge document.MailMerge.ExecuteGroup(GetDataTable()); @@ -315,9 +315,9 @@ document.Close(); {% highlight c# tabtitle="C# [Windows-specific]" %} //Opens the template document WordDocument document = new WordDocument("Template.docx"); -//Sets “ClearFields” to true to remove empty mail merge fields from document +//Sets “ClearFields” to false to keep empty mail merge fields in the document document.MailMerge.ClearFields = false; -//Uses the mail merge event to clear the unmerged field while perform mail merge execution +//Uses the mail merge event to clear the unmerged field while performing mail merge execution document.MailMerge.BeforeClearField += new BeforeClearFieldEventHandler(BeforeClearFieldEvent); //Execute mail merge document.MailMerge.ExecuteGroup(GetDataTable()); @@ -329,10 +329,10 @@ document.Close(); {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} 'Opens the template document Dim document As WordDocument = New WordDocument("Template.docx") -'Sets “ClearFields” to true to remove empty mail merge fields from document +'Sets “ClearFields” to false to keep empty mail merge fields in the document document.MailMerge.ClearFields = False -'Uses the mail merge event to clear the unmerged field while perform mail merge execution -document.MailMerge.BeforeClearField += New BeforeClearFieldEventHandler(AddressOf BeforeClearField) +'Uses the mail merge event to clear the unmerged field while performing mail merge execution +AddHandler document.MailMerge.BeforeClearField, AddressOf BeforeClearFieldEvent 'Execute mail merge document.MailMerge.ExecuteGroup(GetDataTable()) 'Saves and closes the WordDocument instance @@ -559,13 +559,13 @@ document.Close(); {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} 'Opens the template document Dim document As WordDocument = New WordDocument("Template.docx") -'Sets “ClearFields” to true to remove empty mail merge fields from document +'Sets “ClearFields” to false to keep empty mail merge fields in the document document.MailMerge.ClearFields = False -'Uses the mail merge event to clear the unmerged field while perform mail merge execution +'Uses the mail merge event to clear the unmerged field while performing mail merge execution AddHandler document.MailMerge.BeforeClearGroupField, AddressOf BeforeClearFields 'Gets the employee details as “IEnumerable” collection Dim employeeList As List(Of Employees) = GetEmployees() -'Creates an instance of MailMergeDataTableby specifying mail merge group name and “IEnumerable” collection +'Creates an instance of MailMergeDataTable by specifying mail merge group name and “IEnumerable” collection Dim dataTable As MailMergeDataTable = New MailMergeDataTable("Employees", employeeList) 'Performs Mail merge document.MailMerge.ExecuteNestedGroup(dataTable) @@ -589,6 +589,7 @@ private static void BeforeClearFields(object sender, BeforeClearGroupFieldEventA string[] groupName = args.GroupName.Split(':'); if (groupName[groupName.Length - 1] == "Orders") { + //Gets the field names in the group string[] fields = args.FieldNames; List orderList = GetOrders(); //Binds the data to the unmerged fields in group as alternative values @@ -626,16 +627,16 @@ private static void BeforeClearFields(object sender, BeforeClearGroupFieldEventA {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} Private Sub BeforeClearFields(ByVal sender As Object, ByVal args As BeforeClearGroupFieldEventArgs) If Not args.HasMappedGroupInDataSource Then - ‘Gets the Current unmerged group name from the event argument + 'Gets the Current unmerged group name from the event argument Dim groupName As String() = args.GroupName.Split(":"c) If groupName(groupName.Length - 1) = "Orders" Then 'Gets the field names in the group Dim fields As String() = args.FieldNames Dim orderList As List(Of OrderDetails) = GetOrders() - ‘Binds the data to the unmerged fields in group as alternative values + 'Binds the data to the unmerged fields in group as alternative values args.AlternateValues = orderList Else - ‘If group value is empty, you can set whether the unmerged merge group field can be clear or not + 'If group value is empty, you can set whether the unmerged merge group field can be clear or not args.ClearGroup = True End If End If @@ -698,7 +699,7 @@ public static List GetEmployees() 'Gets orders list Private Shared Function GetOrders() As List(Of OrderDetails) Dim orders As List(Of OrderDetails) = New List(Of OrderDetails)() - orders.Add(New OrderDetails("10835", New DateTime(2015, 1, 5), New DateTime(2015, 1, 12), New DateTime(2015, 1, 21))) + orders.Add(New OrderDetails("10952", New DateTime(2015, 2, 5), New DateTime(2015, 2, 12), New DateTime(2015, 2, 21))) Return orders End Function diff --git a/Document-Processing/Word/Word-Library/NET/mail-merge/mail-merge-for-group.md b/Document-Processing/Word/Word-Library/NET/mail-merge/mail-merge-for-group.md index 220a6074e9..1c19ce5156 100644 --- a/Document-Processing/Word/Word-Library/NET/mail-merge/mail-merge-for-group.md +++ b/Document-Processing/Word/Word-Library/NET/mail-merge/mail-merge-for-group.md @@ -8,7 +8,7 @@ documentation: UG # Mail merge for a group -You can perform Mail merge and append multiple records from data source within a specified region to a template document. The region between start and end groups merge fields. It gets repeated for every record from the data source. +You can perform Mail merge and append multiple records from data source within a specified region to a template document. The region is bounded by start and end group merge fields. The region gets repeated for every record from the data source. The following table illustrates the supported mail merge overloads for ExecuteGroup method. @@ -38,11 +38,10 @@ The following table illustrates the supported mail merge overloads for ExecuteGr The region where the Mail merge operations are to be performed must be marked by two merge fields with the following names. * «TableStart:TableName» and «BeginGroup:GroupName» - For the entry point of the region. - * «TableEnd:TableName» and «EndGroup:GroupName» - For the end point of the region. - 1. *TableStart* and *TableEnd* region is preferred for performing Mail merge inside the table cell. - 2. *BeginGroup* and *EndGroup* region is preferred for performing Mail merge inside the document body contents. + * *TableStart* and *TableEnd* regions are preferred for performing Mail merge inside the table cell. + * *BeginGroup* and *EndGroup* regions are preferred for performing Mail merge inside the document body contents. For example, consider that you have a template document as shown. @@ -54,7 +53,7 @@ In this template, Employees is the group name and the same name should be used w The [MailMerge](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html) class provides various overloads for [ExecuteGroup](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html#Syncfusion_DocIO_DLS_MailMerge_ExecuteGroup_System_Data_DataTable_) method to perform Mail merge within a group from various data sources. -N> For group mail merge, declare a class with the field names, create a list, and pass it to [MailMergeDataTable](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html#Syncfusion_DocIO_DLS_MailMerge_ExecuteGroup_Syncfusion_DocIO_DLS_MailMergeDataTable_). Ensure that the property and field names in the input document match when creating the data table. +N> For group mail merge, declare a class with the field names, create a list, and pass it to [MailMergeDataTable](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMergeDataTable.html). Ensure that the property and field names in the input document match when creating the data table. The following code example shows how to perform Mail merge in the specific region with **data source retrieved from SQL connection**. @@ -108,8 +107,8 @@ private DataTable GetDataTable() adapter.Fill(dataset); adapter.Dispose(); conn.Close(); - System.Data.DataTable table = dataset.Tables[0]; - //Sets table name as Employees for template merge field reference. + DataTable table = dataset.Tables[0]; + //Sets the table name to "Employees" to match the template merge field. table.TableName = "Employees"; return table; } @@ -125,7 +124,7 @@ Private Function GetDataTable() As DataTable adapter.Dispose() conn.Close() Dim table As System.Data.DataTable = DataSet.Tables(0) - 'Sets table name as Employees for template merge field reference. + 'Sets the table name to "Employees" to match the template merge field. table.TableName = "Employees" Return table End Function @@ -149,9 +148,9 @@ You can perform Mail merge with .NET objects in a template document. The followi //Opens the template document FileStream fileStreamPath = new FileStream("Template.docx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); WordDocument document = new WordDocument(fileStreamPath, FormatType.Docx); -//Gets the employee details as “IEnumerable” collection +//Gets the employee details as IEnumerable collection List employeeList = GetEmployees(); -//Creates an instance of “MailMergeDataTable” by specifying mail merge group name and “IEnumerable” collection +//Creates an instance of MailMergeDataTable by specifying mail merge group name and IEnumerable collection MailMergeDataTable dataTable = new MailMergeDataTable("Employees", employeeList); //Uses the mail merge events handler for image fields. document.MailMerge.MergeImageField += new MergeImageFieldEventHandler(MergeField_EmployeeImage); @@ -179,9 +178,9 @@ private void MergeField_EmployeeImage(object sender, MergeImageFieldEventArgs ar {% highlight c# tabtitle="C# [Windows-specific]" %} //Opens the template document WordDocument document = new WordDocument("Template.docx"); -//Gets the employee details as “IEnumerable” collection +//Gets the employee details as IEnumerable collection List employeeList = GetEmployees(); -//Creates an instance of “MailMergeDataTable” by specifying mail merge group name and “IEnumerable” collection +//Creates an instance of MailMergeDataTable by specifying mail merge group name and IEnumerable collection MailMergeDataTable dataTable = new MailMergeDataTable("Employees", employeeList); //Uses the mail merge events handler for image fields. document.MailMerge.MergeImageField += new MergeImageFieldEventHandler(MergeField_EmployeeImage); @@ -207,9 +206,9 @@ private void MergeField_EmployeeImage(object sender, MergeImageFieldEventArgs ar {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} 'Opens the template document Dim document As New WordDocument("Template.docx") -'Gets the employee details as “IEnumerable” collection +'Gets the employee details as IEnumerable collection Dim employeeList As List(Of Employee) = GetEmployees() -'Creates an instance of “MailMergeDataTable” by specifying mail merge group name and “IEnumerable” collection +'Creates an instance of MailMergeDataTable by specifying mail merge group name and IEnumerable collection Dim dataTable As New MailMergeDataTable("Employees", employeeList) 'Uses the mail merge events handler for image fields. AddHandler document.MailMerge.MergeImageField, AddressOf MergeField_EmployeeImage diff --git a/Document-Processing/Word/Word-Library/NET/mail-merge/mail-merge-for-nested-groups.md b/Document-Processing/Word/Word-Library/NET/mail-merge/mail-merge-for-nested-groups.md index 1d35ce169b..7c2cb63ab0 100644 --- a/Document-Processing/Word/Word-Library/NET/mail-merge/mail-merge-for-nested-groups.md +++ b/Document-Processing/Word/Word-Library/NET/mail-merge/mail-merge-for-nested-groups.md @@ -6,9 +6,9 @@ control: DocIO documentation: UG --- -# Nested Mail merge for group +# Mail merge for nested groups -You can perform nested Mail merge with relational or hierarchical data source and independent data tables in a template document. +You can perform nested mail merge with relational or hierarchical data source and independent data tables in a template document. The following table illustrates the supported mail merge overloads for ExecuteNestedGroup method. @@ -43,9 +43,9 @@ The following table illustrates the supported mail merge overloads for ExecuteNe ## Create template for nested group mail merge -Nested Mail merge operation automatically replaces the merge field with immediate group data. You can also predefine the group data that is populated to a merge field. - -To execute nested mail merge, design your Word document template as follow. +Nested mail merge operation automatically replaces the merge field with immediate group data. You can also predefine the group data that is populated in a merge field. + +To execute nested mail merge, design your Word document template as follows. ![Word document template for nested groups](../MailMerge_images/file-formats-word-nested-group-mail-merge-template.png) @@ -53,13 +53,13 @@ In this template, Employees is the owner group and it has two child groups Custo ## Execute nested group mail merge -The [MailMerge](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html) class provides various overloads for the [ExecuteNestedGroup](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html#Syncfusion_DocIO_DLS_MailMerge_ExecuteNestedGroup_System_Data_Common_DbConnection_System_Collections_ArrayList_) method to perform Mail merge for nested groups or regions in the Word document. - -You need to define commands with the table name and expression for linking the multiple data tables **(explicit relation data)** during nested Mail merge process. You can use the “%TableName.ColumnName%” expression for getting the current value of specified column or field from the table. +The [MailMerge](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html) class provides various overloads for the [ExecuteNestedGroup](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html#Syncfusion_DocIO_DLS_MailMerge_ExecuteNestedGroup_System_Data_Common_DbConnection_System_Collections_ArrayList_) method to perform mail merge for nested groups or regions in the Word document. -The following code example shows how to perform a nested Mail merge. +The following code example shows how to perform a nested mail merge. -N> Refer to the appropriate tabs in the code snippets section: ***C# [Cross-platform]*** for ASP.NET Core, Blazor, Xamarin, UWP, .NET MAUI, and WinUI; ***C# [Windows-specific]*** for WinForms and WPF; ***VB.NET [Windows-specific]*** for VB.NET applications. +> **NOTE** +> `OleDbConnection` is supported only on Windows. It is not available on Linux or macOS, including in ASP.NET Core on non-Windows platforms. Use `Microsoft.ACE.OLEDB.12.0` instead of the deprecated `Microsoft.Jet.OLEDB.4.0` provider on modern Windows. +N> Refer to the appropriate tabs in the code snippets section: ***C# [Cross-platform]*** for ASP.NET Core, Blazor, .NET MAUI, and WinUI; ***C# [Windows-specific]*** for WinForms and WPF; ***VB.NET [Windows-specific]*** for VB.NET applications. {% tabs %} @@ -154,7 +154,7 @@ The resultant document looks as follows. Essential® DocIO allows you to perform Mail merge with the dynamic objects. The [ExpandoObject](https://docs.microsoft.com/en-us/dotnet/api/system.dynamic.expandoobject?view=net-6.0) is like a collection of key and value pairs, which means IDictionary. So, you can also use IDictionary collection instead of [ExpandoObject](https://docs.microsoft.com/en-us/dotnet/api/system.dynamic.expandoobject?view=net-6.0) to execute mail merge. -The following code snippet shows how to perform the Mail merge with dynamic objects ([ExpandoObject](https://docs.microsoft.com/en-us/dotnet/api/system.dynamic.expandoobject?view=net-6.0)). +The following code snippet shows how to perform the mail merge with dynamic objects ([ExpandoObject](https://learn.microsoft.com/en-us/dotnet/api/system.dynamic.expandoobject)). {% tabs %} @@ -170,7 +170,7 @@ dataSet.Add(dataTable); dataTable = new MailMergeDataTable("Orders", GetOrders()); dataSet.Add(dataTable); List commands = new List(); -//DictionaryEntry contain "Source table" (key) and "Command" (value) +//DictionaryEntry contains "Source table" (key) and "Command" (value) DictionaryEntry entry = new DictionaryEntry("Customers", string.Empty); commands.Add(entry); //Retrieves the customer details @@ -196,7 +196,7 @@ dataSet.Add(dataTable); dataTable = new MailMergeDataTable("Orders", GetOrders()); dataSet.Add(dataTable); List commands = new List(); -//DictionaryEntry contain "Source table" (key) and "Command" (value) +//DictionaryEntry contains "Source table" (key) and "Command" (value) DictionaryEntry entry = new DictionaryEntry("Customers", string.Empty); commands.Add(entry); //Retrieves the customer details @@ -220,7 +220,7 @@ dataSet.Add(dataTable) dataTable = New MailMergeDataTable("Orders", GetOrders()) dataSet.Add(dataTable) Dim commands As New List(Of DictionaryEntry)() -'DictionaryEntry contain "Source table" (key) and "Command" (value) +'DictionaryEntry contains "Source table" (key) and "Command" (value) Dim entry As New DictionaryEntry("Customers", String.Empty) commands.Add(entry) 'Retrieves the customer details @@ -361,23 +361,28 @@ You can download a complete working sample from [GitHub](https://github.com/Sync ## Mail merge with implicit relational data -You can perform **nested Mail merge with implicit relational data** objects without any explicit relational commands by using the [ExecuteNestedGroup](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html#Syncfusion_DocIO_DLS_MailMerge_ExecuteNestedGroup_Syncfusion_DocIO_DLS_MailMergeDataTable_) overload method. +You can perform **nested mail merge with implicit relational data** objects without any explicit relational commands by using the [ExecuteNestedGroup](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html#Syncfusion_DocIO_DLS_MailMerge_ExecuteNestedGroup_Syncfusion_DocIO_DLS_MailMergeDataTable_) overload method. + +DocIO automatically maps child collections to nested groups by matching the property name on the data object to the group name declared in the template (for example, a property named `Departments` on the `Organization` class maps to the `Departments` group region). Ensure property names match the group names used in the template. -### Map the field of ancestor group +### Map fields of ancestor groups -You can also merge any field in the nested group by **mapping the field or column of its ancestor group or table** in the data source. To achieve this, you need to add a corresponding group name or table name as a prefix to the merge field name along with “:” separator. +You can also merge any field in the nested group by **mapping the field or column of its ancestor group or table** in the data source. To achieve this, add the corresponding group name or table name as a prefix to the merge field name along with the `:` separator. For example: - * The merge field name should be like “TableName:Id” (<>) - * The merge field name should be like “Image:TableName:Photo” (<>) - -For example, consider that you have a template document as follow. + * The merge field name should be like `TableName:Id` (<>) + * The merge field name should be like `Image:TableName:Photo` (<>) + +> **NOTE** +> Image merge fields require the merge field to be configured with the `Image:` prefix in the template and the data value to be a byte array or `Image` instance. + +For example, consider that you have a template document as follows. ![Word document template to map the fields of ancestor group](../MailMerge_images/file-formats-word-mapping-template.png) -In the above template, Organizations is the owner group and it has two child groups Departments and Employees. The Supervisor merge field of Departments group is used in Employees group. +In the above template, Organizations is the owner group and it has two child groups Departments and Employees. The `Supervisor` merge field of the Departments group is used in the Employees group. -The following code example shows how to perform nested Mail merge with the implicit relational data objects. +The following code example shows how to perform nested mail merge with the implicit relational data objects. {% tabs %} @@ -385,9 +390,9 @@ The following code example shows how to perform nested Mail merge with the impli //Opens the template document FileStream fileStreamPath = new FileStream("Template.docx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); WordDocument document = new WordDocument(fileStreamPath, FormatType.Docx); -//Gets the organization details as “IEnumerable” collection +//Gets the organization details as IEnumerable collection List organizationList = GetOrganizations(); -//Creates an instance of “MailMergeDataTable” by specifying mail merge group name and “IEnumerable” collection +//Creates an instance of MailMergeDataTable by specifying mail merge group name and IEnumerable collection MailMergeDataTable dataTable = new MailMergeDataTable("Organizations", organizationList); //Performs Mail merge document.MailMerge.ExecuteNestedGroup(dataTable); @@ -401,9 +406,9 @@ document.Close(); {% highlight c# tabtitle="C# [Windows-specific]" %} //Opens the template document WordDocument document = new WordDocument("Template.docx"); -//Gets the organization details as “IEnumerable” collection +//Gets the organization details as IEnumerable collection List organizationList = GetOrganizations(); -//Creates an instance of “MailMergeDataTable” by specifying mail merge group name and “IEnumerable” collection +//Creates an instance of MailMergeDataTable by specifying mail merge group name and IEnumerable collection MailMergeDataTable dataTable = new MailMergeDataTable("Organizations", organizationList); //Performs Mail merge document.MailMerge.ExecuteNestedGroup(dataTable); @@ -415,9 +420,9 @@ document.Close(); {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} 'Opens the template document Dim document As WordDocument = New WordDocument("Template.docx") -'Gets the organization details as “IEnumerable” collection +'Gets the organization details as IEnumerable collection Dim organizationList As List(Of Organization) = GetOrganizations() -'Creates an instance of “MailMergeDataTable” by specifying mail merge group name and “IEnumerable” collection +'Creates an instance of MailMergeDataTable by specifying mail merge group name and IEnumerable collection Dim dataTable As MailMergeDataTable = New MailMergeDataTable("Organizations", organizationList) 'Performs Mail merge document.MailMerge.ExecuteNestedGroup(dataTable) @@ -477,7 +482,7 @@ public static List GetOrganizations() {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} -Public Function GetOrganizations() As List(Of Organization) +Public Shared Function GetOrganizations() As List(Of Organization) 'Creates Employee details Dim employees As List(Of EmployeeDetails) = New List(Of EmployeeDetails) employees.Add(New EmployeeDetails("Thomas Hardy", "1001", "05/27/1996")) diff --git a/Document-Processing/Word/Word-Library/NET/mail-merge/mail-merge-options.md b/Document-Processing/Word/Word-Library/NET/mail-merge/mail-merge-options.md index 3336f510f3..4b9f0556e0 100644 --- a/Document-Processing/Word/Word-Library/NET/mail-merge/mail-merge-options.md +++ b/Document-Processing/Word/Word-Library/NET/mail-merge/mail-merge-options.md @@ -8,11 +8,11 @@ documentation: UG # Mail merge options in Word Library -The [MailMerge](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html) class allows you to customize the Mail merge process with the following options. +The [MailMerge](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html) class allows you to customize the mail merge process with the following options. ## Field Mapping -The [MailMerge](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html) class can automatically **maps the merge field names with data source column names** during Mail merge process. You can also customize the field mapping when the merge field names in the template document varies with the column names in the data source by using [MappedFields](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html#Syncfusion_DocIO_DLS_MailMerge_MappedFields) collection. +The [MailMerge](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html) class can automatically **map the merge field names with data source column names** during mail merge process. You can also customize the field mapping when the merge field names in the template document vary with the column names in the data source by using [MappedFields](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html#Syncfusion_DocIO_DLS_MailMerge_MappedFields) collection. The following code example shows how to add mapping when a merge field name in a document and column name in data source have different names. @@ -132,29 +132,29 @@ The following code example shows how to retrieve the merge field names for a spe {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Mail-Merge/Retrieve-merge-field-names/.NET/Retrieve-merge-field-names/Program.cs" %} -//Gets the fields from the specified groups. +//Gets the fields from the specified group. string[] fieldNames = document.MailMerge.GetMergeFieldNames(groupName); {% endhighlight %} {% highlight c# tabtitle="C# [Windows-specific]" %} -//Gets the fields from the specified groups +//Gets the fields from the specified group string[] fieldNames = document.MailMerge.GetMergeFieldNames(groupName); {% endhighlight %} {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} -'Gets the fields from the specified groups +'Gets the fields from the specified group Dim fieldNames As String() = document.MailMerge.GetMergeFieldNames(groupName) {% endhighlight %} {% endtabs %} -You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Mail-Merge/Retrieve-merge-field-names). +You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Mail-Merge/Retrieve-merge-field-names). This sample demonstrates all three methods shown above (`GetMergeFieldNames`, `GetMergeGroupNames`, and `GetMergeFieldNames(groupName)`). ## Remove empty paragraphs -You can remove the empty paragraphs when the paragraph has only a merge field item, without any data during Mail merge process. +You can remove the empty paragraphs when the paragraph has only a merge field item, without any data during mail merge process. -The following code example shows how to remove the empty paragraphs during Mail merge process. +The following code example shows how to remove the empty paragraphs during mail merge process. {% tabs %} @@ -215,15 +215,15 @@ Essential® DocIO removes or keeps the unmerged merge fields in th When a merge field is considered as unmerged during mail merge process? -1. The merge field doesn't have mapping field in data source. +1. The merge field doesn't have a mapping field in data source. -2. The merge field has mapping field in data source, but the data is null or string.Empty. +2. The merge field has a mapping field in data source, but the data is null or string.Empty. -Mail merge operation automatically removes the unmerged merge fields since the default value of [ClearFields](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html#Syncfusion_DocIO_DLS_MailMerge_ClearFields) property is true. +The mail merge operation automatically removes the unmerged merge fields since the default value of the [ClearFields](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html#Syncfusion_DocIO_DLS_MailMerge_ClearFields) property is true. T> 1. Set [ClearFields](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html#Syncfusion_DocIO_DLS_MailMerge_ClearFields) property to false before the mail merge execution statement if your requirement is to keep the unmerged merge fields in the output document. T> 2. Modify the [ClearFields](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html#Syncfusion_DocIO_DLS_MailMerge_ClearFields) property before each mail merge execution statement while performing multiple mail merge executions if your requirement is to remove the unmerged merge fields in one mail merge execution and keep the unmerged merge fields in another mail merge execution. -T> 3. Order the mail merge executions with the [ClearFields](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html#Syncfusion_DocIO_DLS_MailMerge_ClearFields) property false as first to avoid removal merge fields that are required for next mail merge execution in the same document. +T> 3. Order the mail merge executions with the [ClearFields](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html#Syncfusion_DocIO_DLS_MailMerge_ClearFields) property false as first to avoid removal of merge fields that are required for next mail merge execution in the same document. T> 4. You can get the unmerged fields in your document, customize the mail merge process using the BeforeClearField Event. For further information, click [here](https://help.syncfusion.com/document-processing/word/word-library/net/mail-merge/mail-merge-events#beforeclearfield-event). The following code example shows how to keep the unmerged merge fields in the generated Word document. @@ -234,7 +234,7 @@ The following code example shows how to keep the unmerged merge fields in the ge //Opens the template document FileStream fileStreamPath = new FileStream("Template.docx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); WordDocument document = new WordDocument(fileStreamPath, FormatType.Docx); -//Sets “ClearFields” to true to remove empty mail merge fields from document +//Sets “ClearFields” to false to keep the unmerged mail merge fields in document document.MailMerge.ClearFields = false; string[] fieldNames = new string[] { "EmployeeId", "Phone", "City" }; string[] fieldValues = new string[] { "1001", "+91-9999999999", "London" }; @@ -250,7 +250,7 @@ document.Close(); {% highlight c# tabtitle="C# [Windows-specific]" %} //Opens the template document WordDocument document = new WordDocument("Template.docx"); -//Sets “ClearFields” to true to remove empty mail merge fields from document +//Sets “ClearFields” to false to keep the unmerged mail merge fields in document document.MailMerge.ClearFields = false; string[] fieldNames = new string[] { "EmployeeId", "Phone", "City" }; string[] fieldValues = new string[] { "1001", "+91-9999999999", "London" }; @@ -264,7 +264,7 @@ document.Close(); {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} 'Opens the template document Dim document As New WordDocument("Template.docx") -'Sets “ClearFields” to true to remove empty mail merge fields from document +'Sets “ClearFields” to false to keep the unmerged mail merge fields in document document.MailMerge.ClearFields = False Dim fieldNames As String() = New String() {"EmployeeId", "Phone", "City"} Dim fieldValues As String() = New String() {"1001", "+91-9999999999", "London"} @@ -281,7 +281,7 @@ You can download a complete working sample from [GitHub](https://github.com/Sync ## Remove empty group -You can remove the empty merge field groups which contains unmerged merge fields after executing mail merge for a group in a Word document. +You can remove the empty merge field groups which contain unmerged merge fields after executing mail merge for a group in a Word document. The following code example shows how to remove empty merge field group during mail merge process in a Word document. @@ -544,15 +544,15 @@ You can download a complete working sample from [GitHub](https://github.com/Sync ## Restart numbering in lists -You can restart the list numbering for each records while performing mail merge for a group in Word document. +You can restart the list numbering for each record while performing mail merge for a group in Word document by setting the [ImportOptions](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.ImportOptions.html) to [ListRestartNumbering](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.ImportOptions.html). -The following code example shows how to restart the list numbering in a Word documents while performing mail merge. +The following code example shows how to restart the list numbering in a Word document while performing mail merge. {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Mail-Merge/Restart-list-numbering-in-mail-merge/.NET/Restart-list-numbering-in-mail-merge/Program.cs" %} //Loads an existing Word document -FileStream fileStream = new FileStream("Template.docx", FileMode.Open); +FileStream fileStream = new FileStream("Template.docx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); WordDocument document = new WordDocument(fileStream, FormatType.Docx); //Sets ImportOptions to restart the list numbering document.ImportOptions = ImportOptions.ListRestartNumbering; @@ -583,7 +583,7 @@ employeeList.Add(new Employee("101", "Nancy Davolio", "Seattle, WA, USA")); employeeList.Add(new Employee("102", "Andrew Fuller", "Tacoma, WA, USA")); employeeList.Add(new Employee("103", "Janet Leverling", "Kirkland, WA, USA")); //Creates an instance of “MailMergeDataTable” by specifying mail merge group name and “IEnumerable” collection -MailMergeDataTable dataTable = new MailMergeDataTable("Employee", employeeList); +MailMergeDataTable dataTable = new MailMergeDataTable("Employees", employeeList); //Performs mail merge document.MailMerge.ExecuteGroup(dataTable); //Saves the Word document @@ -603,7 +603,7 @@ employeeList.Add(New Employee("101", "Nancy Davolio", "Seattle, WA, USA")) employeeList.Add(New Employee("102", "Andrew Fuller", "Tacoma, WA, USA")) employeeList.Add(New Employee("103", "Janet Leverling", "Kirkland, WA, USA")) 'Creates an instance of “MailMergeDataTable” by specifying mail merge group name and “IEnumerable” collection -Dim dataTable As MailMergeDataTable = New MailMergeDataTable("Employee", employeeList) +Dim dataTable As MailMergeDataTable = New MailMergeDataTable("Employees", employeeList) 'Performs mail merge document.MailMerge.ExecuteGroup(dataTable) 'Saves the Word document @@ -774,7 +774,7 @@ document.Close(); {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} 'Opens the template document -Dim document As WordDocument = New WordDocument("Data/Template.docx") +Dim document As WordDocument = New WordDocument("Template.docx") 'Creates a data table Dim table As DataTable = New DataTable("CompatibleVersions") table.Columns.Add("WordVersion") @@ -867,7 +867,7 @@ document.Close() {% endtabs %} -The following code example shows how to skip merging particular image during mail merge process using MergeImageFieldEventHandler. +The following code example shows how to skip merging particular image during mail merge process using [MergeImageFieldEventHandler](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MergeImageFieldEventHandler.html). For details on the event arguments, see [MergeImageFieldEventArgs](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MergeImageFieldEventArgs.html) (members: `Skip`, `FieldName`, `FieldValue`, `ImageStream`, `ImageFileName`, `Picture`). {% tabs %} @@ -876,7 +876,10 @@ private void MergeEmployeePhoto(object sender, MergeImageFieldEventArgs args) { //Skip to merge particular image if (args.FieldName == "Andrew") + { args.Skip = true; + return; + } //Sets image string ProductFileName = args.FieldValue.ToString(); FileStream imageStream = new FileStream(ProductFileName, FileMode.Open, FileAccess.Read); @@ -892,7 +895,10 @@ private void MergeEmployeePhoto(object sender, MergeImageFieldEventArgs args) { //Skip to merge particular image if (args.FieldName == "Andrew") + { args.Skip = true; + return; + } //Sets image args.ImageFileName = args.FieldValue.ToString(); } @@ -903,6 +909,7 @@ Private Sub MergeEmployeePhoto(ByVal sender As Object, ByVal args As MergeImageF 'Skip to merge particular image If args.FieldName = "Andrew" Then args.Skip = True + Return End If 'Sets image Dim ProductFileName As String = args.FieldValue.ToString() @@ -920,6 +927,8 @@ You can start a new page for each group of records while performing a mail merge The following code example illustrates how to start a new page for each group of records during the mail merge process. +N> The `GetInvoice` helper method and the `Invoice`, `Orders`, `Order`, and `OrderTotals` classes used by this snippet are shown below the tabs. + {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Mail-Merge/Start-at-new-page/.NET/Start-at-new-page/Program.cs" %} @@ -1105,7 +1114,7 @@ Public Function GetInvoice() As List(Of Invoice) invoices.Add(New Invoice(orders, order, orderTotals)) orders = New List(Of Orders)() - orders.Add(New Orders("10250", "Hanari Carnes", "Rua do Paço, 67", "Rio de Janeiro", "05454-876", "Brazil", "VINET", "Rua do Paço, "1996-07-04T00:00:00-04:00", "1996-08-01T00:00:00-04:00", "1996-07-16T00:00:00-04:00", "United Package")) + orders.Add(New Orders("10250", "Hanari Carnes", "Rua do Paço, 67", "Rio de Janeiro", "05454-876", "Brazil", "VINET", "Rua do Paço, 67", "51100", "Rio de Janeiro", "Brazil", "Margaret Peacock", "Hanari Carnes", "1996-07-04T00:00:00-04:00", "1996-08-01T00:00:00-04:00", "1996-07-16T00:00:00-04:00", "United Package")) order = New List(Of Order)() order.Add(New Order("65", "Louisiana Fiery Hot Pepper Sauce", "16.8", "15", "0.15", "214.2")) @@ -2020,7 +2029,7 @@ By executing the above code example, it generates the resultant Word document as ![Output Word document of start at new page](../mailmerge_images/generated-word-document-in-file-formats.png) -N> This [StartAtNewPage](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html#Syncfusion_DocIO_DLS_MailMerge_StartAtNewPage) property is valid for group mail merge and also that the corresponding group start and group end should be present in the text body of the Word document. This [StartAtNewPage](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html#Syncfusion_DocIO_DLS_MailMerge_StartAtNewPage) property is not valid when the group start and group end are present in the table, headers, and footers. +N> The [StartAtNewPage](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html#Syncfusion_DocIO_DLS_MailMerge_StartAtNewPage) property is valid only for group mail merge where the group start and group end are present in the text body of the Word document. It is not valid when the group start and group end are present inside a table, header, or footer. ## Remove mail merge settings @@ -2066,7 +2075,7 @@ Dim document As New WordDocument("Template.docx", FormatType.Docx) If document.MailMerge.Settings.HasData Then document.MailMerge.Settings.RemoveData() End If -Saves and closes the Word document instance +'Saves and closes the Word document instance document.Save("Sample.docx", FormatType.Docx) document.Close() {% endhighlight %} @@ -2081,6 +2090,8 @@ You can change the linked **data source file path from a Word mail merge main do The following code example shows how to change the data source file path in the template Word document. +N> The path can be relative or absolute and should point to a file format supported by Microsoft Word for mail merge (for example, `.txt`, `.csv`, `.xls`/`.xlsx`, or `.mdb`). + {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Mail-Merge/Change-mail-merge-data-source-path/.NET/Change-mail-merge-data-source-path/Program.cs" %} diff --git a/Document-Processing/Word/Word-Library/NET/mail-merge/mail-merge-troubleshooting-tips.md b/Document-Processing/Word/Word-Library/NET/mail-merge/mail-merge-troubleshooting-tips.md index 3598869836..efae8d65cd 100644 --- a/Document-Processing/Word/Word-Library/NET/mail-merge/mail-merge-troubleshooting-tips.md +++ b/Document-Processing/Word/Word-Library/NET/mail-merge/mail-merge-troubleshooting-tips.md @@ -1,25 +1,26 @@ --- -title: Troubleshooting tips for Mail merge | DocIO | Syncfusion +title: Troubleshooting tips for Mail Merge | DocIO | Syncfusion description: Learn how to troubleshoot Mail Merge issues in the .NET Word (DocIO) library, including common errors. platform: document-processing control: DocIO documentation: UG --- -# Troubleshooting Mail merge Issues in .NET Word Library +# Troubleshooting Mail Merge Issues in .NET Word Library ## Why is mail merge not working correctly in DocIO? Mail merge issues can arise due to incorrect merge fields, mismatched data sources, or missing fields in the template. Ensure the following: * Merge fields (<>) are used instead of plain text. -* **Data Source Check:** Ensure the required fields exist in the data source. -* **Match Field Names:** Sometimes, the field names in the Word document are different from the property names in your data source class. For example, if your document has "FirstName" and "LastName", but your Employee class uses different names, mail merge will not work correctly. +* **Data Source Check:** Ensure the required fields exist in the data source. Verify the data source column/property names against the merge field names in the Word template. +* **Match Field Names:** Sometimes, the field names in the Word document are different from the property names in your data source class. For example, if your document has "FirstName" and "LastName", but your Employee class uses different names, Mail Merge will not work correctly. **How to fix this:** - * The property names in your MergeField class should be exactly the same as the merge field names in your Word document. + * The property names in your data source class should be exactly the same as the merge field names in your Word document. * Field names are case-sensitive, so make sure they match exactly. - * You can press **Alt + F9** in Microsoft Word to see the actual field codes and check if they are correct. + +**How to verify the merge fields:** Press **Alt + F9** in Microsoft Word to reveal the actual field codes and confirm the merge field names are correct. **Example:** @@ -37,14 +38,6 @@ public class Employee } {% endhighlight %} -{% highlight c# tabtitle="C# [Windows-specific]" %} -public class Employee -{ - public string FirstName { get; set; } // Matches merge field name - public string LastName { get; set; } // Matches merge field name -} -{% endhighlight %} - {% highlight vb.net tabtitle="VB.NET [Windows-specific]" %} Public Class Employee 'Matches merge field name @@ -70,8 +63,11 @@ Mail merge only works with merge fields, not manually typed placeholders. If tex Refer to [Syncfusion® Documentation](https://help.syncfusion.com/document-processing/word/word-library/net/working-with-find-and-replace#find-and-replace-a-pattern-of-text-with-a-merge-field) for detailed implementation. -## Why is nested group mail merge not functioning correctly? +## Why is nested group Mail Merge not functioning correctly? + +Nested Mail Merge requires proper execution using the correct method and structure. +* Use the appropriate overload of the [`ExecuteNestedGroup`](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html) method to handle nested groups effectively. Supported overloads include: + * `ExecuteNestedGroup(MailMergeDataTable)` — for implicit relational data, where the child groups are nested within the parent table's data. + * `ExecuteNestedGroup(MailMergeDataSet, List)` — for explicit relational data, where the relations between parent and child groups are defined using command entries. +* Ensure the data structure follows the correct hierarchy for nested groups to maintain implicit relational data. Each child group must be represented as a relation between the parent table and the child table in the data source. -Nested mail merge requires proper execution using the correct method and structure. -* Use the appropriate overload of the ExecuteNestedGroup method to handle nested groups effectively. Refer to the Syncfusion documentation for supported overloads. -* Ensure the data structure follows the correct hierarchy for nested groups to maintain implicit relational data. diff --git a/Document-Processing/Word/Word-Library/NET/mail-merge/simple-mail-merge.md b/Document-Processing/Word/Word-Library/NET/mail-merge/simple-mail-merge.md index b0e6fec7af..e064cfc78b 100644 --- a/Document-Processing/Word/Word-Library/NET/mail-merge/simple-mail-merge.md +++ b/Document-Processing/Word/Word-Library/NET/mail-merge/simple-mail-merge.md @@ -1,12 +1,12 @@ --- -title: Simple Mail merge in C# | DocIO | Syncfusion -description: Learn how to Mail merge - replace all merge fields with data, by repeating whole document for each record in data source using the .NET Word (DocIO) library. +title: Simple mail merge in C# | DocIO | Syncfusion +description: Learn how to mail merge - replace all merge fields with data, by repeating whole document for each record in data source using the .NET Word (DocIO) library. platform: document-processing control: DocIO documentation: UG --- -# Simple Mail merge in Word document +# Simple mail merge in a Word document You can create a Word document template using Microsoft Word application or by adding merge fields in the Word document programmatically. For further information, click [here](https://help.syncfusion.com/document-processing/word/word-library/net/working-with-mail-merge#create-word-document-template). @@ -51,9 +51,9 @@ The following table illustrates the supported mail merge overloads for Execute m ## Mail merge with string arrays -The [MailMerge](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html) class provides various overloads for [Execute](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html#Syncfusion_DocIO_DLS_MailMerge_Execute_System_String___System_String___) method to perform Mail merge from various data sources. The Mail merge operation replaces the matching merge fields with the respective data. +The [MailMerge](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html) class provides various overloads for the [Execute](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html#Syncfusion_DocIO_DLS_MailMerge_Execute_System_String___System_String___) method to perform a mail merge from various data sources. The mail merge operation replaces the matching merge fields with the respective data. Unmatched merge fields are left unchanged in the output document by default. -### Create Word document template +### Create a Word document template The following code example shows how to create a Word template document with merge fields. @@ -78,9 +78,9 @@ document.LastParagraph.AppendText("\nPhone: "); document.LastParagraph.AppendField("Phone", FieldType.FieldMergeField); document.LastParagraph.AppendText("\nCity: "); document.LastParagraph.AppendField("City", FieldType.FieldMergeField); -//Saves the Word document to MemoryStream -MemoryStream stream = new MemoryStream(); -document.Save(stream, FormatType.Docx); +//Saves the Word document to a file +FileStream fileStream = new FileStream("Template.docx", FileMode.Create, FileAccess.ReadWrite); +document.Save(fileStream, FormatType.Docx); //Closes the Word document document.Close(); {% endhighlight %} @@ -139,8 +139,7 @@ The generated template document looks as follows. ### Execute mail merge -The following code example shows how to perform a simple Mail merge in the generated template document with string array as data source. - +The following code example shows how to perform a simple mail merge in the generated template document with a string array as the data source. {% tabs %} {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Mail-Merge/Mail-merge-with-string-arrays/.NET/Mail-merge-with-string-arrays/Program.cs" %} @@ -191,4 +190,10 @@ You can download a complete working sample from [GitHub](https://github.com/Sync The resultant document looks as follows. -![Mail merged Word document](../MailMerge_images/file-formats-word-simple-mail-merge-output.png) \ No newline at end of file +![Mail merged Word document](../MailMerge_images/file-formats-word-simple-mail-merge-output.png) + +## See also + +- [Mail merge using nested groups](https://help.syncfusion.com/document-processing/word/word-library/net/working-with-mail-merge#mail-merge-using-nested-groups) +- [Conditional merge fields](https://help.syncfusion.com/document-processing/word/word-library/net/working-with-mail-merge#conditional-merge-fields) +- [Mail merge for regions](https://help.syncfusion.com/document-processing/word/word-library/net/working-with-mail-merge#region-mail-merge) diff --git a/Document-Processing/Word/Word-Library/NET/working-with-lists.md b/Document-Processing/Word/Word-Library/NET/working-with-lists.md index fde55427a9..15ae799f59 100644 --- a/Document-Processing/Word/Word-Library/NET/working-with-lists.md +++ b/Document-Processing/Word/Word-Library/NET/working-with-lists.md @@ -26,7 +26,7 @@ WordDocument document = new WordDocument(); IWSection section = document.AddSection(); //Adds new paragraph to the section IWParagraph paragraph = section.AddParagraph(); -//Applies default numbered list style +//Applies default bulleted list style paragraph.ListFormat.ApplyDefBulletStyle(); //Adds text to the paragraph paragraph.AppendText("List item 1"); @@ -56,7 +56,7 @@ WordDocument document = new WordDocument(); IWSection section = document.AddSection(); //Adds new paragraph to the section IWParagraph paragraph = section.AddParagraph(); -//Applies default numbered list style +//Applies default bulleted list style paragraph.ListFormat.ApplyDefBulletStyle(); //Adds text to the paragraph paragraph.AppendText("List item 1"); @@ -85,7 +85,7 @@ Dim document As New WordDocument() Dim section As IWSection = document.AddSection() 'Adds new paragraph to the section Dim paragraph As IWParagraph = section.AddParagraph() -'Applies default numbered list style +'Applies default bulleted list style paragraph.ListFormat.ApplyDefBulletStyle() 'Adds text to the paragraph paragraph.AppendText("List item 1") @@ -109,7 +109,7 @@ document.Close() {% endtabs %} -By running the above code, you will generate a **Bullet List** as shown below. +By running the above code, you will generate a **Bulleted List** as shown below. ![List](Lists_images/CreateBulletedList.png) You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Paragraphs/Simple-bulleted-list). @@ -228,7 +228,7 @@ WordDocument document = new WordDocument(); IWSection section = document.AddSection(); //Adds new paragraph to the section IWParagraph paragraph = section.AddParagraph(); -//Applies default numbered list style +//Applies default bulleted list style paragraph.ListFormat.ApplyDefBulletStyle(); //Adds text to the paragraph paragraph.AppendText("List item 1 - Level 0"); @@ -262,7 +262,7 @@ WordDocument document = new WordDocument(); IWSection section = document.AddSection(); //Adds new paragraph to the section IWParagraph paragraph = section.AddParagraph(); -//Applies default numbered list style +//Applies default bulleted list style paragraph.ListFormat.ApplyDefBulletStyle(); //Adds text to the paragraph paragraph.AppendText("List item 1 - Level 0"); @@ -295,7 +295,7 @@ Dim document As New WordDocument() Dim section As IWSection = document.AddSection() 'Adds new paragraph to the section Dim paragraph As IWParagraph = section.AddParagraph() -'Applies default numbered list style +'Applies default bulleted list style paragraph.ListFormat.ApplyDefBulletStyle() 'Adds text to the paragraph paragraph.AppendText("List item 1 - Level 0") @@ -323,14 +323,14 @@ document.Close() {% endtabs %} -By running the above code, you will generate a **Multilevel Bullet List** as shown below. +By running the above code, you will generate a **Multilevel Bulleted List** as shown below. ![List](Lists_images/MultilevelBulletList.png) You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Paragraphs/Multilevel-bulleted-list). ## Create Multilevel Numbered List -The following code example explains how to create multilevel numbered list. +The following code example explains how to create a multilevel numbered list. {% tabs %} @@ -441,7 +441,7 @@ By running the above code, you will generate a **Multilevel Numbered List** as s You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Paragraphs/Multilevel-numbered-list). -## List number format +## List Number Format The ListPatternType enum in DocIO lets you customize how list numbers appear in Word documents. It supports 61 styles, including Arabic, Hebrew, and more. This is useful for creating region-specific documents or applying culturally appropriate numbering formats. @@ -515,7 +515,7 @@ levelOne.PatternType = ListPatternType.Hebrew1; levelOne.StartAt = 1; // Adds a heading paragraph for the Hebrew1 list. paragraph = section.AddParagraph(); -paragraph.AppendText("List pattern Herbrew"); +paragraph.AppendText("List pattern Hebrew"); // Adds first list item using Hebrew1 style. paragraph = section.AddParagraph(); paragraph.AppendText("List item 1"); @@ -604,7 +604,7 @@ levelOne.PatternType = ListPatternType.Hebrew1; levelOne.StartAt = 1; // Adds a heading paragraph for the Hebrew1 list. paragraph = section.AddParagraph(); -paragraph.AppendText("List pattern Herbrew"); +paragraph.AppendText("List pattern Hebrew"); // Adds first list item using Hebrew1 style. paragraph = section.AddParagraph(); paragraph.AppendText("List item 1"); @@ -716,7 +716,7 @@ document.Close() {% endtabs %} -By running the above code, you will generate a **List Numbered Format** as shown below. +By running the above code, you will generate a **List Number Format** as shown below. ![List](Lists_images/ListNumberFormat.png) You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Paragraphs/List-number-format). @@ -727,7 +727,7 @@ N> Except for the following [ListPatternType](https://help.syncfusion.com/cr/doc You can customize lists in Word documents using DocIO, allowing you to define numbering styles, bullet symbols, indentation levels, and list patterns to suit your formatting needs. -The following code example explains how to create user defined list styles. +The following code example explains how to create a user-defined numbered list style. For a user-defined bulleted list style, see [Bulleted List Styles](#bulleted-list-styles). {% tabs %} @@ -890,7 +890,7 @@ paragraph = section.AddParagraph(); paragraph.AppendText("Multilevel numbered list - Level 0"); //Continues last defined list paragraph.ListFormat.ContinueListNumbering(); -//Increases the level indent +//Decreases the level indent paragraph.ListFormat.DecreaseIndentLevel(); //Adds new paragraph paragraph = section.AddParagraph(); @@ -931,7 +931,7 @@ paragraph = section.AddParagraph(); paragraph.AppendText("Multilevel numbered list - Level 0"); //Continues last defined list paragraph.ListFormat.ContinueListNumbering(); -//Increases the level indent +//Decreases the level indent paragraph.ListFormat.DecreaseIndentLevel(); //Adds new paragraph paragraph = section.AddParagraph(); @@ -971,7 +971,7 @@ paragraph = section.AddParagraph() paragraph.AppendText("Multilevel numbered list - Level 0") 'Continues last defined list paragraph.ListFormat.ContinueListNumbering() -'Increases the level indent +'Decreases the level indent paragraph.ListFormat.DecreaseIndentLevel() 'Adds new paragraph paragraph = section.AddParagraph() @@ -988,7 +988,7 @@ document.Close() {% endtabs %} -By running the above code, you will generate a **Increase or Decrease List indent** as shown below. +By running the above code, you will generate the **Increase or Decrease List Indent** output as shown below. ![List](Lists_images/ChangeListLevels.png) You can download a complete working sample from [GitHub](https://github.com/SyncfusionExamples/DocIO-Examples/tree/main/Paragraphs/Increase-or-decrease-list-indent). @@ -1007,18 +1007,18 @@ IWSection section = document.AddSection(); //Add a new list style to the document. ListStyle listStyle = document.AddListStyle(ListType.Bulleted, "UserDefinedList"); WListLevel levelOne = listStyle.Levels[0]; -//Define the following character, pattern and start index for level 0. +//Define the pattern, bullet character, and start index for level 0. levelOne.PatternType = ListPatternType.Bullet; levelOne.BulletCharacter = "*"; levelOne.StartAt = 1; WListLevel levelTwo = listStyle.Levels[1]; -//Define the following character, pattern and start index for level 1. +//Define the pattern, bullet character, and start index for level 1. levelTwo.PatternType = ListPatternType.Bullet; levelTwo.BulletCharacter = "\u00A9"; levelTwo.CharacterFormat.FontName = "Wingdings"; levelTwo.StartAt = 1; WListLevel levelThree = listStyle.Levels[2]; -//Define the following character, pattern and start index for level 2. +//Define the pattern, bullet character, and start index for level 2. levelThree.PatternType = ListPatternType.Bullet; levelThree.BulletCharacter = "\u0076"; levelThree.CharacterFormat.FontName = "Wingdings"; @@ -1058,18 +1058,18 @@ IWSection section = document.AddSection(); //Add a new list style to the document. ListStyle listStyle = document.AddListStyle(ListType.Bulleted, "UserDefinedList"); WListLevel levelOne = listStyle.Levels[0]; -//Define the following character, pattern and start index for level 0. +//Define the pattern, bullet character, and start index for level 0. levelOne.PatternType = ListPatternType.Bullet; levelOne.BulletCharacter = "*"; levelOne.StartAt = 1; WListLevel levelTwo = listStyle.Levels[1]; -//Define the following character, pattern and start index for level 1. +//Define the pattern, bullet character, and start index for level 1. levelTwo.PatternType = ListPatternType.Bullet; levelTwo.BulletCharacter = "\u00A9"; levelTwo.CharacterFormat.FontName = "Wingdings"; levelTwo.StartAt = 1; WListLevel levelThree = listStyle.Levels[2]; -//Define the following character, pattern and start index for level 2. +//Define the pattern, bullet character, and start index for level 2. levelThree.PatternType = ListPatternType.Bullet; levelThree.BulletCharacter = "\u0076"; levelThree.CharacterFormat.FontName = "Wingdings"; @@ -1108,18 +1108,18 @@ Dim section As IWSection = document.AddSection() 'Add a new list style to the document. Dim listStyle As ListStyle = document.AddListStyle(ListType.Bulleted, "UserDefinedList") Dim levelOne As WListLevel = listStyle.Levels(0) -'Define the following character, pattern and start index for level 0. +'Define the pattern, bullet character, and start index for level 0. levelOne.PatternType = ListPatternType.Bullet levelOne.BulletCharacter = "*" levelOne.StartAt = 1 Dim levelTwo As WListLevel = listStyle.Levels(1) -'Define the following character, pattern and start index for level 1. +'Define the pattern, bullet character, and start index for level 1. levelTwo.PatternType = ListPatternType.Bullet levelTwo.BulletCharacter = ChrW(169) levelTwo.CharacterFormat.FontName = "Wingdings" levelTwo.StartAt = 1 Dim levelThree As WListLevel = listStyle.Levels(2) -'Define the following character, pattern and start index for level 2. +'Define the pattern, bullet character, and start index for level 2. levelThree.PatternType = ListPatternType.Bullet levelThree.BulletCharacter = ChrW(118) levelThree.CharacterFormat.FontName = "Wingdings" @@ -1159,7 +1159,7 @@ You can download a complete working sample from [GitHub](https://github.com/Sync ## Numbered List with Prefix -The following code example explains how to create numbered list with prefix from previous level. +The following code example explains how to create a numbered list with prefix from previous level. N> The [NumberPrefix](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WListLevel.html#Syncfusion_DocIO_DLS_WListLevel_NumberPrefix) value for the numbered list should meet the syntax "\u000N" to update the previous list level value as prefix to the current list level. For example, it should be represented as (“\u0000.” or “\u0000.\u0001.”). @@ -1184,7 +1184,7 @@ levelTwo.NumberPrefix = "\u0000."; levelTwo.PatternType = ListPatternType.Arabic; levelTwo.StartAt = 1; WListLevel levelThree = listStyle.Levels[2]; -//Defines the follow character, prefix from previous level, pattern, start index for level 1 +//Defines the follow character, prefix from previous level, pattern, start index for level 2 levelThree.FollowCharacter = FollowCharacterType.Nothing; levelThree.NumberPrefix = "\u0000.\u0001."; levelThree.PatternType = ListPatternType.Arabic; @@ -1235,7 +1235,7 @@ levelTwo.NumberPrefix = "\u0000."; levelTwo.PatternType = ListPatternType.Arabic; levelTwo.StartAt = 1; WListLevel levelThree = listStyle.Levels[2]; -//Defines the follow character, prefix from previous level, pattern, start index for level 1 +//Defines the follow character, prefix from previous level, pattern, start index for level 2 levelThree.FollowCharacter = FollowCharacterType.Nothing; levelThree.NumberPrefix = "\u0000.\u0001."; levelThree.PatternType = ListPatternType.Arabic; @@ -1285,7 +1285,7 @@ levelTwo.NumberPrefix = vbNullChar & "." levelTwo.PatternType = ListPatternType.Arabic levelTwo.StartAt = 1 Dim levelThree As WListLevel = listStyle.Levels(2) -'Defines the follow character, prefix from previous level, pattern, start index for level 1 +'Defines the follow character, prefix from previous level, pattern, start index for level 2 levelThree.FollowCharacter = FollowCharacterType.[Nothing] levelThree.NumberPrefix = vbNullChar & "." & ChrW(1) & "." levelThree.PatternType = ListPatternType.Arabic diff --git a/Document-Processing/Word/Word-Library/NET/working-with-mail-merge.md b/Document-Processing/Word/Word-Library/NET/working-with-mail-merge.md index a756e7dde0..3f03da5e4c 100644 --- a/Document-Processing/Word/Word-Library/NET/working-with-mail-merge.md +++ b/Document-Processing/Word/Word-Library/NET/working-with-mail-merge.md @@ -7,7 +7,7 @@ documentation: UG --- # Working with Mail merge -Mail merge is a process of merging data from data source to a Word template document. The [WMergeField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WMergeField.html) class provides support to bind template document and data source. The [WMergeField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WMergeField.html) instance is replaced with the actual data retrieved from data source for the given merge field name in a template document. +Mail merge is a process of merging data from a data source into a Word template document. The [WMergeField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WMergeField.html) class provides support to bind template document and data source. The [WMergeField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WMergeField.html) instance is replaced with the actual data retrieved from the data source for the given merge field name in a template document. ## Supported data sources @@ -16,7 +16,7 @@ The following data sources are supported by Essential® DocIO for - + @@ -98,12 +98,12 @@ The mail merge process involves three documents: 3. **Final merged document**: This resultant document is a combination of the template Word document and the data from data source. -T> 1. You can use conditional fields ([IF](https://support.microsoft.com/en-us/office/field-codes-if-field-9f79e82f-e53b-4ff5-9d2c-ae3b22b7eb5e?ui=en-us&rs=en-us&ad=us), [Formula](https://support.microsoft.com/en-us/office/field-codes-formula-field-32d5c9de-3516-4ec3-80ed-d1fc2b5bc21d?ui=en-us&rs=en-us&ad=us)) combined with merge fields, when you require intelligent decisions in addition to simple mail merge (replace merge fields with result text). To use conditional fields, execute mail merge and then update fields in the Word document using [UpdateDocumentFields](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WordDocument.html#Syncfusion_DocIO_DLS_WordDocument_UpdateDocumentFields) API. -T> 2. You can replace the fields ([IF](https://support.microsoft.com/en-us/office/field-codes-if-field-9f79e82f-e53b-4ff5-9d2c-ae3b22b7eb5e?ui=en-us&rs=en-us&ad=us), [Formula](https://support.microsoft.com/en-us/office/field-codes-formula-field-32d5c9de-3516-4ec3-80ed-d1fc2b5bc21d?ui=en-us&rs=en-us&ad=us)) combined with merge fields, with its most recent result and **generates the plain Word document** by unlinking the fields. Refer to this [link](https://help.syncfusion.com/document-processing/word/word-library/net/working-with-fields#unlink-fields) for more information. +T> 1. You can use conditional fields ([IF](https://support.microsoft.com/en-us/office/field-codes-if-field-9f79e82f-e53b-4ff5-9d2c-ae3b22b7eb5e?ui=en-us&rs=en-us&ad=us), [Formula](https://support.microsoft.com/en-us/office/field-codes-formula-field-32d5c9de-3516-4ec3-80ed-d1fc2b5bc21d?ui=en-us&rs=en-us&ad=us)) combined with merge fields, when you require intelligent decisions in addition to simple mail merge (i.e., replacing merge fields with result text). To use conditional fields, execute mail merge and then update fields in the Word document using [UpdateDocumentFields](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.WordDocument.html#Syncfusion_DocIO_DLS_WordDocument_UpdateDocumentFields) API. +T> 2. You can replace the fields ([IF](https://support.microsoft.com/en-us/office/field-codes-if-field-9f79e82f-e53b-4ff5-9d2c-ae3b22b7eb5e?ui=en-us&rs=en-us&ad=us), [Formula](https://support.microsoft.com/en-us/office/field-codes-formula-field-32d5c9de-3516-4ec3-80ed-d1fc2b5bc21d?ui=en-us&rs=en-us&ad=us)) combined with merge fields, with its most recent result and convert the field results to static text by unlinking the fields. Refer to this [link](https://help.syncfusion.com/document-processing/word/word-library/net/working-with-fields#unlink-fields) for more information. ### Create Word document template -You can create a template document with merge fields by using any Word editor application, like Microsoft Word. By using Word editor application, you can take the advantage of the visual interface to design unique layout, formatting, and more for your Word document template interactively. +You can create a template document with merge fields by using any Word editor application, like Microsoft Word. By using a Word editor application, you can take the advantage of the visual interface to design unique layout, formatting, and more for your Word document template interactively. The following screenshot shows how to insert a merge field in the Word document by **using the Microsoft Word.** @@ -111,9 +111,9 @@ The following screenshot shows how to insert a merge field in the Word document You need to add a prefix (“Image:”) to the merge field name for merging an image in the place of a merge field. -**For example:** The merge field name should be like “Image:Photo” (<>) +**For example:** The merge field name should be like "Image:Photo" (<>) -You can **create Word document template programmatically** by adding merge fields to the Word document using Essential® DocIO. +You can **create Word document template programmatically** by adding merge fields to the Word document using Essential® DocIO. DocIO supports the following template formats: `.docx`, `.doc`, `.rtf`, and `.dotx`. The following code example shows how to create a merge field in the Word document. @@ -123,16 +123,20 @@ N> Refer to the appropriate tabs in the code snippets section: ***C# [Cross-plat {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Mail-Merge/Create-merge-field/.NET/Create-merge-field/Program.cs" %} //Creates an instance of a WordDocument -WordDocument document = new WordDocument(); -//Adds a section and a paragraph in the document -document.EnsureMinimal(); -//Appends merge field to the last paragraph. -document.LastParagraph.AppendField("FullName", FieldType.FieldMergeField); -//Saves the Word document to MemoryStream -MemoryStream stream = new MemoryStream(); -document.Save(stream, FormatType.Docx); -//Closes the Word document -document.Close(); +using (WordDocument document = new WordDocument()) +{ + //Adds a section and a paragraph in the document + document.EnsureMinimal(); + //Appends merge field to the last paragraph. + document.LastParagraph.AppendField("FullName", FieldType.FieldMergeField); + //Saves the Word document to MemoryStream + using (MemoryStream stream = new MemoryStream()) + { + document.Save(stream, FormatType.Docx); + //Writes the Word document to a file + File.WriteAllBytes("Template.docx", stream.ToArray()); + } +} {% endhighlight %} {% highlight c# tabtitle="C# [Windows-specific]" %} @@ -171,17 +175,21 @@ The following code example shows how to perform mail merge in above Word documen {% highlight c# tabtitle="C# [Cross-platform]" playgroundButtonLink="https://raw.githubusercontent.com/SyncfusionExamples/DocIO-Examples/main/Mail-Merge/Getting-started-mail-merge/.NET/Getting-started-mail-merge/Program.cs" %} //Opens the template document -FileStream fileStreamPath = new FileStream("Template.docx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); -WordDocument document = new WordDocument(fileStreamPath, FormatType.Docx); -string[] fieldNames = new string[] { "FullName" }; -string[] fieldValues = new string[] { "Nancy Davolio" }; -//Performs the mail merge -document.MailMerge.Execute(fieldNames, fieldValues); -//Saves the Word document to MemoryStream -MemoryStream stream = new MemoryStream(); -document.Save(stream, FormatType.Docx); -//Closes the Word document -document.Close(); +using (FileStream fileStreamPath = new FileStream("Template.docx", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) +{ + WordDocument document = new WordDocument(fileStreamPath, FormatType.Docx); + string[] fieldNames = new string[] { "FullName" }; + string[] fieldValues = new string[] { "Nancy Davolio" }; + //Performs the mail merge + document.MailMerge.Execute(fieldNames, fieldValues); + //Saves the Word document to MemoryStream + using (MemoryStream stream = new MemoryStream()) + { + document.Save(stream, FormatType.Docx); + //Writes the Word document to a file + File.WriteAllBytes("Sample.docx", stream.ToArray()); + } +} {% endhighlight %} {% highlight c# tabtitle="C# [Windows-specific]" %} @@ -222,15 +230,15 @@ The [MailMerge](https://help.syncfusion.com/cr/document-processing/Syncfusion.Do ## Performing Mail merge for a group -You can perform Mail merge and append multiple records from data source within a specified region to a template document. For further information, click [here](https://help.syncfusion.com/document-processing/word/word-library/net/mail-merge/mail-merge-for-group). +You can perform Mail merge and append multiple records from the data source within a specified region to a template document. For further information, click [here](https://help.syncfusion.com/document-processing/word/word-library/net/mail-merge/mail-merge-for-group). -## Performing Nested Mail merge for group +## Performing Nested Mail merge for a group -You can perform nested Mail merge with relational or hierarchical data source and independent data tables in a template document. For further information, click [here](https://help.syncfusion.com/document-processing/word/word-library/net/mail-merge/mail-merge-for-nested-groups). +You can perform nested Mail merge with a relational or hierarchical data source and independent data tables in a template document. For further information, click [here](https://help.syncfusion.com/document-processing/word/word-library/net/mail-merge/mail-merge-for-nested-groups). ## Performing Mail merge with dynamic objects -Essential® DocIO allows you to perform Mail merge with the dynamic objects. For further information, click [here](https://help.syncfusion.com/document-processing/word/word-library/net/mail-merge/mail-merge-for-nested-groups#mail-merge-with-dynamic-objects). +Essential® DocIO allows you to perform Mail merge with dynamic objects. For further information, click [here](https://help.syncfusion.com/document-processing/word/word-library/net/mail-merge/mail-merge-for-nested-groups#mail-merge-with-dynamic-objects). ## Performing Mail merge with business objects @@ -242,9 +250,9 @@ Essential® DocIO supports performing nested Mail merge with impli ## Event support for mail merge -The [MailMerge](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html) class provides event support to customize the document contents and merging image data during the Mail merge process. The following events are supported by Essential® DocIO in Mail merge process: +The [MailMerge](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html) class provides event support to customize the document contents and merging image data during the Mail merge process. The following events are supported by Essential® DocIO in the Mail merge process: -* [MergeField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MergeFieldEventHandler.html): Occurs when a **Mail merge field** except image Mail merge field is encountered. +* [MergeField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MergeFieldEventHandler.html): Occurs when a **Mail merge field** except an image Mail merge field is encountered. * [MergeImageField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MergeImageFieldEventHandler.html): Occurs when an **image Mail merge field** is encountered. @@ -254,19 +262,19 @@ The [MailMerge](https://help.syncfusion.com/cr/document-processing/Syncfusion.Do ### MergeField event -You can customize the merging text during Mail merge process by using the [MergeField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MergeFieldEventHandler.html) event. For further information, click [here](https://help.syncfusion.com/document-processing/word/word-library/net/mail-merge/mail-merge-events#mergefield-event). +You can customize the merging text during the Mail merge process by using the [MergeField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MergeFieldEventHandler.html) event. For further information, click [here](https://help.syncfusion.com/document-processing/word/word-library/net/mail-merge/mail-merge-events#mergefield-event). ### MergeImageField event -You can customize the merging image during Mail merge process by using the [MergeImageField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MergeImageFieldEventHandler.html) event. For further information, click [here](https://help.syncfusion.com/document-processing/word/word-library/net/mail-merge/mail-merge-events#mergeimagefield-event). +You can customize the merging image during the Mail merge process by using the [MergeImageField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MergeImageFieldEventHandler.html) event. For further information, click [here](https://help.syncfusion.com/document-processing/word/word-library/net/mail-merge/mail-merge-events#mergeimagefield-event). ### BeforeClearField event -You can get the unmerged fields during Mail merge process by using the [BeforeClearField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BeforeClearFieldEventHandler.html) event. For further information, click [here](https://help.syncfusion.com/document-processing/word/word-library/net/mail-merge/mail-merge-events#beforeclearfield-event). +You can get the unmerged fields during the Mail merge process by using the [BeforeClearField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BeforeClearFieldEventHandler.html) event. For further information, click [here](https://help.syncfusion.com/document-processing/word/word-library/net/mail-merge/mail-merge-events#beforeclearfield-event). ### BeforeClearGroupField event -You can get the unmerged groups during Mail merge process by using the [BeforeClearGroupField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BeforeClearGroupFieldEventHandler.html) event. For further information, click [here](https://help.syncfusion.com/document-processing/word/word-library/net/mail-merge/mail-merge-events#beforecleargroupfield-event). +You can get the unmerged groups during the Mail merge process by using the [BeforeClearGroupField](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.BeforeClearGroupFieldEventHandler.html) event. For further information, click [here](https://help.syncfusion.com/document-processing/word/word-library/net/mail-merge/mail-merge-events#beforecleargroupfield-event). ## Mail merge options @@ -274,7 +282,7 @@ The [MailMerge](https://help.syncfusion.com/cr/document-processing/Syncfusion.Do ### Field mapping -You can automatically map the merge field names with data source column names during Mail merge process. For further information, click [here](https://help.syncfusion.com/document-processing/word/word-library/net/mail-merge/mail-merge-options#field-mapping). +You can automatically map the merge field names with the data source column names during the Mail merge process. For further information, click [here](https://help.syncfusion.com/document-processing/word/word-library/net/mail-merge/mail-merge-options#field-mapping). ### Retrieving the merge field names @@ -282,11 +290,11 @@ You can retrieve the merge field names and also merge field group names in the W ### Removing empty paragraphs -You can remove the empty paragraphs when the paragraph has a merge field item without any data during Mail merge process. For further information, click [here](https://help.syncfusion.com/document-processing/word/word-library/net/mail-merge/mail-merge-options#remove-empty-paragraphs). +You can remove the empty paragraphs when the paragraph has a merge field item without any data during the Mail merge process. For further information, click [here](https://help.syncfusion.com/document-processing/word/word-library/net/mail-merge/mail-merge-options#remove-empty-paragraphs). ### Removing empty merge fields -You can remove or keep the unmerged merge fields in the output document based on the [ClearFields](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html#Syncfusion_DocIO_DLS_MailMerge_ClearFields) property on each mail merge execution. For further information, click [here](https://help.syncfusion.com/document-processing/word/word-library/net/mail-merge/mail-merge-options#remove-empty-merge-fields). +You can remove or keep the unmerged merge fields in the output document based on the [ClearFields](https://help.syncfusion.com/cr/document-processing/Syncfusion.DocIO.DLS.MailMerge.html#Syncfusion_DocIO_DLS_MailMerge_ClearFields) property on each mail merge execution. The default value of `ClearFields` is `true`, which removes unmerged merge fields. For further information, click [here](https://help.syncfusion.com/document-processing/word/word-library/net/mail-merge/mail-merge-options#remove-empty-merge-fields). ### Restart numbering in lists
Data Source

Examples

Sample