Encrypt PDF Document in C#/VB.NET

2011-07-04 08:19:41 Written by Koohji

Encrypting PDF is a way people commonly used to protect PDF. Whether for a company or for individual, using PDF encryption to place some certain restrictions is indispensable. In order to make the PDF document available to read but unable to modify by unauthorized users, two passwords are required for an encrypted PDF document: owner password and user password. This section will particularly introduce a simple solution to quickly encrypt PDF with C#, VB.NET via Spire.PDF for .NET.

Spire.PDF for .NET as a .NET PDF component, can encrypt your PDF by owner and user password. Owner password is provided to fully access to PDF file such as reset password and restrictions. While user password allows users to open the document as well as subject to the restrictions placed by owner.

In the encryption solution, an object of the PDFSecurity class which is included in the namespace Spire.PDFDocument.Security is used to set the owner and user password. Please feel free to download Spire.PDF for .NET and load your PDF file and then protect it.

Protect PDF by setting password and specify document restrictions.

Step 1: Set PDF key size by the enum."Spire.Pdf.Security.PdfEncryptionKeySize".Three kinds of key size are available here: Key128Bit, Key256Bit and Key40Bit, you can use any one among the three.

[C#]
doc.Security.KeySize = PdfEncryptionKeySize.Key256Bit;
[VB.NET]
doc.Security.KeySize = PdfEncryptionKeySize.Key256Bit 

Step 2: Encrypt PDF file by setting owner and user password. The password size you set should not be over the key size.

[C#]
doc.Security.OwnerPassword = "e-iceblue";
doc.Security.UserPassword = "pdfcomponent";
[VB.NET]
doc.Security.OwnerPassword = "e-iceblue"
doc.Security.UserPassword = "pdfcomponent" 

Step 3: Specify access restrictions of user password. There are nine permissions are available in the solution. You can see them as below picture.

Encrypt PDF Document

[C#]
doc.Security.Permissions = PdfPermissionsFlags.Print | PdfPermissionsFlags.CopyContent;
[VB.NET]
doc.Security.Permissions = PdfPermissionsFlags.Print Or PdfPermissionsFlags. CopyContent

After running your project, you will be requested a password when you open this encrypted PDF file. Please look at the effective screenshot below:

Encrypt PDF Document

Marker Designer

2011-07-01 02:51:40 Written by Koohji

Introduction

A Marker Designer represents a single data point or value that gives a mean to Spire.XLS to place relevant data into different cells of the worksheet in a workbook. We make use of Designer spreadsheets in which we write marker designers into different cells. Normally a marker designer consists of DataSource and a Field Name and starts with "&=". The DataSource can be a DataSet, DataTable, DataView or an Object variable etc. You can also make use of dynamic formulas that allows you to insert MS Excel's formulas into cells even when the formula must reference rows that will be inserted during the export process. Moreover, you may calculate totals and sub totals of any data field too.

Marker designer is a way to let Spire.XLS know that what information you wish to place in an Excel designer spreadsheet. Marker designers allow you to create templates that contain only relevant information and are formatted to meet your needs.

Designer Spreadsheet and Marker Designers

Designer spreadsheets are standard Excel files that contain the visual formatting, formulas and marker designers. They can contain marker designers that reference one or more data sources such as information from a project and information for related contacts. Marker designers are written into cells where you want information to be filled in.

All marker designers start with "&=", without the quotes. An example of a data marker is &=Party.FullName. If the data marker results in more than one item, i.e. row then following rows will be moved down automatically to make room for all of the new information. Thus sub-totals and totals can be placed on the following row after the data marker to make calculations based on inserted data. In order to make calculations on the rows that are inserted, you must use Dynamic Formulas.

Marker designers consist of the Data Source and Field Name parts for most information. Special information may also be passed with variables and variable arrays. Variables always fill only one cell whereas variable arrays may fill several ones. You may only use one data marker per cell. Unused marker designers will be removed.

Marker designer may also contain parameters. Parameters allow you to modify how the information will be laid out. They are appended to the end of marker designer in parenthesis as a comma separated list.

Marker designer Options

&=DataSource.FieldName 
&=[Data Source].[Field Name] 
&=VariableName

Formulas

Formulas allow you to insert Excel's formulas into cells even when the formula must reference rows that will be inserted during the export process. And they can repeat for each inserted row or use only the cell where the data marker is placed for it.

If value of a cell referred to other cells, such as (copy:rc6), it means the value of the cell will be referred by cells of column 6. Multiple refer can be used like this: (copy:rc5,copy:rc7).

Note: Separate them with comma

Cell "G6" contains the formula = D6*E6, cell "G7" contains = D7*E7 and cell "G8" contains = D8*E8, etc.

The following illustrates a repeating dynamic formula and the resulting Excel worksheet.

Excel Marker Designer

Result:

Excel Marker Designer

Sum and Subtotal

Below is showing you how to use these 2 formulas:

Excel Marker Designer

Result:

Excel Marker Designer

Code:

          Workbook workbook = new Workbook();

            workbook.LoadFromFile(@"..\..\..\..\..\..\Data\MarkerDesignerSample1.xls");
			DataTable dt = (DataTable)dataGrid1.DataSource;

			Worksheet sheet = workbook.Worksheets[0];
            //fill parameter
            workbook.MarkerDesigner.AddParameter("Variable1", 1234.5678);
            //fill DataTable
			workbook.MarkerDesigner.AddDataTable("Country",dt);
			workbook.MarkerDesigner.Apply();

            //AutoFit
			sheet.AllocatedRange.AutoFitRows();
			sheet.AllocatedRange.AutoFitColumns();

			workbook.SaveToFile("Sample.xls",ExcelVersion.Version97to2003);

Marker Designer Full Demo

Add PDF Footer in C#/VB.NET

2011-06-24 05:51:59 Written by Koohji

A PDF header or footer presents consistent information (For example: a date, page numbering, the title of the overall document, or author’s name) in the page margins throughout a PDF. In this article, you will learn to add text and automatic page numbering to footer space when creating a PDF document from scratch.

Spire.PDF has a class named PdfPageTemplateElement, which represents a page template element that can be used as header, footer, watermark or stamp. The template can contain text, image as well as dynamic fields like PdfPageCountField, PdfPageNumberField, etc.

Step 1: Define a custom function CreateFooterTemplate() to create a page template element that servers as footer, and return a PdfPageDocumentElement object.

static PdfPageTemplateElement CreateFooterTemplate(PdfDocument doc, PdfMargins margins)
{
    //get page size
    SizeF pageSize = doc.PageSettings.Size;

    //create a PdfPageTemplateElement object which works as footer space
    PdfPageTemplateElement footerSpace = new PdfPageTemplateElement(pageSize.Width, margins.Bottom);
    footerSpace.Foreground = false;

    //declare two float variables
    float x = margins.Left;
    float y = 0;

    //draw line in footer space
    PdfPen pen = new PdfPen(PdfBrushes.Gray, 1);
    footerSpace.Graphics.DrawLine(pen, x, y, pageSize.Width - x, y);

    //draw text in footer space
    y = y + 5;
    PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Impact", 10f), true);
    PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Left);
    String footerText = "E-iceblue Technology Co., Ltd.\nTel:028-81705109\nWebsite:http://www.e-iceblue.com";
    footerSpace.Graphics.DrawString(footerText, font, PdfBrushes.Gray, x, y, format);

    //draw dynamic field in footer space
    PdfPageNumberField number = new PdfPageNumberField();
    PdfPageCountField count = new PdfPageCountField();
    PdfCompositeField compositeField = new PdfCompositeField(font, PdfBrushes.Gray, "Page {0} of {1}", number, count);
    compositeField.StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Top);
    SizeF size = font.MeasureString(compositeField.Text);
    compositeField.Bounds = new RectangleF(pageSize.Width - x , y, size.Width, size.Height);
    compositeField.Draw(footerSpace.Graphics);

    //return footerSpace
    return footerSpace;
}

Step 2: Create a PDF document, call the method CreateFooterTemplate() to create a footer template and apply it to the document.

static void Main(string[] args)
{
    //create a PDF document
    PdfDocument doc = new PdfDocument();
    doc.PageSettings.Size = PdfPageSize.A4;

    //reset the default margins to 0
    doc.PageSettings.Margins = new PdfMargins(0);

    //create a PdfMargins object, the parameters indicate the page margins you want to set
    PdfMargins margins = new PdfMargins(60, 60, 60, 60);

    //create a footer template with content and apply it to bottom page template
    doc.Template.Bottom = CreateFooterTemplate(doc, margins);

    //apply blank templates to other parts of page template
    doc.Template.Top = new PdfPageTemplateElement(doc.PageSettings.Size.Width, margins.Top);
    doc.Template.Left = new PdfPageTemplateElement(margins.Left, doc.PageSettings.Size.Height);
    doc.Template.Right = new PdfPageTemplateElement(margins.Right, doc.PageSettings.Size.Height);

    //add two pages in the document
    doc.Pages.Add();
    doc.Pages.Add();

    //save the file
    doc.SaveToFile("PdfFooter.pdf");
}

Output:

Add PDF Footer in C#, VB.NET

Full Code:

[C#]
using Spire.Pdf;
using Spire.Pdf.AutomaticFields;
using Spire.Pdf.Graphics;
using System;
using System.Drawing;


namespace AddPDFFooter
{
    class Program
    {
        static void Main(string[] args)
        {
            //create a PDF document
            PdfDocument doc = new PdfDocument();
            doc.PageSettings.Size = PdfPageSize.A4;

            //reset the default margins to 0
            doc.PageSettings.Margins = new PdfMargins(0);

            //create a PdfMargins object, the parameters indicate the page margins you want to set
            PdfMargins margins = new PdfMargins(60, 60, 60, 60);

            //create a footer template with content and apply it to page template
            doc.Template.Bottom = CreateFooterTemplate(doc, margins);

            //apply blank templates to other parts of page template
            doc.Template.Top = new PdfPageTemplateElement(doc.PageSettings.Size.Width, margins.Top);
            doc.Template.Left = new PdfPageTemplateElement(margins.Left, doc.PageSettings.Size.Height);
            doc.Template.Right = new PdfPageTemplateElement(margins.Right, doc.PageSettings.Size.Height);

            //add two pages in the document
            doc.Pages.Add();
            doc.Pages.Add();

            //save the file
            doc.SaveToFile("PdfFooter.pdf");
        }
        static PdfPageTemplateElement CreateFooterTemplate(PdfDocument doc, PdfMargins margins)
        {
            //get page size
            SizeF pageSize = doc.PageSettings.Size;

            //create a PdfPageTemplateElement object which works as footer space
            PdfPageTemplateElement footerSpace = new PdfPageTemplateElement(pageSize.Width, margins.Bottom);
            footerSpace.Foreground = false;

            //declare two float variables
            float x = margins.Left;
            float y = 0;

            //draw line in footer space
            PdfPen pen = new PdfPen(PdfBrushes.Gray, 1);
            footerSpace.Graphics.DrawLine(pen, x, y, pageSize.Width - x, y);

            //draw text in footer space
            y = y + 5;
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Impact", 10f), true);
            PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Left);
            String footerText = "E-iceblue Technology Co., Ltd.\nTel:028-81705109\nWebsite:http://www.e-iceblue.com";
            footerSpace.Graphics.DrawString(footerText, font, PdfBrushes.Gray, x, y, format);

            //draw dynamic field in footer space
            PdfPageNumberField number = new PdfPageNumberField();
            PdfPageCountField count = new PdfPageCountField();
            PdfCompositeField compositeField = new PdfCompositeField(font, PdfBrushes.Gray, "Page {0} of {1}", number, count);
            compositeField.StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Top);
            SizeF size = font.MeasureString(compositeField.Text);
            compositeField.Bounds = new RectangleF(pageSize.Width - x, y, size.Width, size.Height);
            compositeField.Draw(footerSpace.Graphics);

            //return footerSpace
            return footerSpace;
        }
    }
}
[VB.NET]
Imports Spire.Pdf
Imports Spire.Pdf.AutomaticFields
Imports Spire.Pdf.Graphics
Imports System.Drawing


Namespace AddPDFFooter
	Class Program
		Private Shared Sub Main(args As String())
			'create a PDF document
			Dim doc As New PdfDocument()
			doc.PageSettings.Size = PdfPageSize.A4

			'reset the default margins to 0
			doc.PageSettings.Margins = New PdfMargins(0)

			'create a PdfMargins object, the parameters indicate the page margins you want to set
			Dim margins As New PdfMargins(60, 60, 60, 60)

			'create a footer template with content and apply it to page template
			doc.Template.Bottom = CreateFooterTemplate(doc, margins)

			'apply blank templates to other parts of page template
			doc.Template.Top = New PdfPageTemplateElement(doc.PageSettings.Size.Width, margins.Top)
			doc.Template.Left = New PdfPageTemplateElement(margins.Left, doc.PageSettings.Size.Height)
			doc.Template.Right = New PdfPageTemplateElement(margins.Right, doc.PageSettings.Size.Height)

			'add two pages in the document
			doc.Pages.Add()
			doc.Pages.Add()

			'save the file
			doc.SaveToFile("PdfFooter.pdf")
		End Sub
		Private Shared Function CreateFooterTemplate(doc As PdfDocument, margins As PdfMargins) As PdfPageTemplateElement
			'get page size
			Dim pageSize As SizeF = doc.PageSettings.Size

			'create a PdfPageTemplateElement object which works as footer space
			Dim footerSpace As New PdfPageTemplateElement(pageSize.Width, margins.Bottom)
			footerSpace.Foreground = False

			'declare two float variables
			Dim x As Single = margins.Left
			Dim y As Single = 0

			'draw line in footer space
			Dim pen As New PdfPen(PdfBrushes.Gray, 1)
			footerSpace.Graphics.DrawLine(pen, x, y, pageSize.Width - x, y)

			'draw text in footer space
			y = y + 5
			Dim font As New PdfTrueTypeFont(New Font("Impact", 10F), True)
			Dim format As New PdfStringFormat(PdfTextAlignment.Left)
			Dim footerText As [String] = "E-iceblue Technology Co., Ltd." & vbLf & "Tel:028-81705109" & vbLf & "Website:http://www.e-iceblue.com"
			footerSpace.Graphics.DrawString(footerText, font, PdfBrushes.Gray, x, y, format)

			'draw dynamic field in footer space
			Dim number As New PdfPageNumberField()
			Dim count As New PdfPageCountField()
			Dim compositeField As New PdfCompositeField(font, PdfBrushes.Gray, "Page {0} of {1}", number, count)
			compositeField.StringFormat = New PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Top)
			Dim size As SizeF = font.MeasureString(compositeField.Text)
			compositeField.Bounds = New RectangleF(pageSize.Width - x, y, size.Width, size.Height)
			compositeField.Draw(footerSpace.Graphics)

			'return footerSpace
			Return footerSpace
		End Function
	End Class
End Namespace

Spire.PDF for .NET is a professional PDF API applied to creating, writing, editing, handling and reading PDF files without any external dependencies within .NET (C#, VB.NET, ASP.NET, .NET Core, .NET 5.0, .NET 6.0, .NET 7.0, MonoAndroid and Xamarin.iOS) application. Using this .NET PDF library, you can implement rich capabilities to create PDF files from scratch or process existing PDF documents entirely through C#/VB.NET without installing Adobe Acrobat.

Many rich features can be supported by the .NET PDF API, such as adding digital signature, including timestamp in signature, adding dynamic/image stamp, adding text/image watermark, creating PDF Portfolio, extracting text/attachment/images, PDF merging/spliting, metadata updating, section, graph/image drawing and inserting, table creation and processing, cropping pages, copying pages, and importing data etc.

cover page of converting html to pdf with c#

Converting HTML to PDF is a common task for developers who need to generate printable documents or preserve web content offline. With Spire.PDF for .NET, developers can achieve this conversion through multiple approaches that suit different environments. Whether you prefer using the built-in HTML-to-PDF capabilities with the QT plugin, or you want more control through ChromeHtmlConverter, Spire.PDF provides flexible solutions. This tutorial covers several ways to convert HTML to PDF using C# in .NET applications.

Method Best For Features
1. Convert HTML/URL to PDF With QT Plugin Developers who seek quick setup with minimal customization Login session support; Shorter code with faster conversion process
2. ChromeHtmlConverter with Output Logs Developers who need high-fidelity output and diagnostics Pixel-perfect rendering; Executes JS and dynamic content; Logs useful for debugging

Convert HTML/URL to PDF with QT Plugin

Before guiding you to the specific code sample of how to convert HTML files to PDF format, let me introduce Spire.PDF for .NET to you. It is a powerful C# library designed for creating, editing, and converting PDF documents. Except for HTML to PDF conversion, you can also use it to add digital signatures, create PDF Portfolios, extract elements like texts and images, and PDF file merging and splitting.

More reasons to help you choose Spire.PDF for .NET:

  • Compress PDF files from 10 – 100 times to reduce file size
  • Widely compatibility of C# environments
  • Add encryption to PDF files to protect your file privacy
  • More features waiting for you to explore...

To run the conversion process smoothly, you should use the C# API with QT plugin. In the following content, you will learn the step-by-step tutorial.

Step 1. Download Spire.PDF for .NET code library from the official download page to add it in your C# program.

Tip: To unlock all powerful functions of Spire.PDF, please request a 30-day trial license for yourself.

Step 2. Download the plugin on your computer. You can click the following link according to your own computer system.

Step 3. After downloading, unzip package somewhere on your disk to get the "plugins" folder like the pic shows below.

result of converting word to pdf with spire doc for java

We recommend that you set the "Platform target" of your project to x64 or x86 accordingly.

result of converting word to pdf with spire doc for java

Step 4. After adding the plugin, you just need to copy the following code sample to manage the conversion process.

If you have the original HTML file, copy the following code to your C# program:

using System.IO;
using Spire.Additions.Qt; 
using System.Drawing;
using Spire.Pdf.Graphics;

namespace ConvertHtmlStringToPdfWithPlugin
{
    class Program
    {
        static void Main(string[] args)
        {
            //Get the HTML string from a .html file
            string htmlString = File.ReadAllText(@"C:\Users\Administrator\Desktop\Document\Html\Sample.html");

            //Specify the output file path
            string fileName = "HtmlStringToPdf.pdf";

            //Specify the plugin path
            string pluginPath = "F:\\Libraries\\Plugin\\plugins-windows-x64\\plugins";

            //Set plugin path
            HtmlConverter.PluginPath = pluginPath;

            //Convert HTML string to PDF
            HtmlConverter.Convert(htmlString, fileName, true, 100000, new Size(1080, 1000), new PdfMargins(0), LoadHtmlType.SourceCode);       
        }
    }
}

If you only get the URL, the code sample below is what you need:

using Spire.Pdf.Graphics;
using Spire.Additions.Qt; 
using System.Drawing;

namespace ConvertUrlToPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            //Specify the URL path
            string url = "https://www.wikipedia.org/";

            //Specify the output file path
            string fileName = "UrlToPdf.pdf";

            //Specify the plugin path
             string pluginPath = "F:\\Libraries\\Plugin\\plugins-windows-x64\\plugins";

            //Set the plugin path
             HtmlConverter.PluginPath = pluginPath;

            //Convert URL to PDF
            HtmlConverter.Convert(url, fileName, true, 100000, new Size(1080, 1000), new PdfMargins(0));
        }
    }
}

RESULT:

result of converting word to pdf with spire doc for java

Convert HTML to PDF using ChromeHtmlConverter with Output Logs

Unlike standard conversion methods that rely solely on engine defaults or basic libraries, ChromeHtmlConverter leverages the power of a headless Chrome browser to render HTML content exactly as it appears in a real browser environment. It provides output logs, which are essential for diagnosing rendering issues, monitoring conversion performance, or maintaining compliance in production environments.

Let's now look at the specific code to use Spire.PDF for .NET and ChromeHtmlConverter to manage this conversion:

using Spire.Additions.Chrome;

namespace ConvertHtmlToPdfUsingChrome
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Specify the input URL and output PDF file path
            string inputUrl = @"https://www.e-iceblue.com/Tutorials/Spire.PDF/Spire.PDF-Program-Guide/C-/VB.NET-Convert-Image-to-PDF.html";
            string outputFile = @"HtmlToPDF.pdf";

            // Specify the log file path
            string logFilePath = @"Logs.txt";

            //Specify the path to the Chrome plugin
            string chromeLocation = @"C:\Program Files\Google\Chrome\Application\chrome.exe";

            //Create an instance of the ChromeHtmlConverter class
            ChromeHtmlConverter converter = new ChromeHtmlConverter(chromeLocation);
            //Enable logging
            converter.Logger = new Logger(logFilePath);

            //Create an instance of the ConvertOptions class
            ConvertOptions options = new ConvertOptions();
            //Set conversion timeout
            options.Timeout = 10 * 3000;
            //Set paper size and page margins of the converted PDF
            options.PageSettings = new PageSettings()
            {
                PaperWidth = 8.27,
                PaperHeight = 11.69,
                MarginTop = 0,
                MarginLeft = 0,
                MarginRight = 0,
                MarginBottom = 0

            };

            //Convert the URL to PDF
            converter.ConvertToPdf(inputUrl, outputFile, options);
        }
    }
}

The output log looks like below:

main interface of cloudxdocs online word to pdf converter

Read more details with the following post:

Convert HTML to PDF using ChromeHtmlConverter

Conclusion:

Spire.PDF for .NET offers a range of tools to convert HTML/URL to PDF in C#, whether you're dealing with local HTML files or remote web pages. Depending on your project requirements—such as rendering complexity, output quality, or dependency preferences, you can select the most suitable method.

C#: Mail Merge in Word Documents

2024-05-08 03:21:00 Written by Administrator

Mail Merge is a powerful feature in Microsoft Word that allows you to create multiple documents such as letters, labels, envelopes, and even e-mails from a single template document and a data source. It's particularly useful for tasks like sending personalized correspondence to a large number of recipients without having to write each letter individually.

In this article, you will learn how to perform a mail merge in a Word document using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Understanding the Components of Mail Merge

  • Main Document: This is the template file where you design your letter, label, or other types of documents with placeholders (also known as merge fields) that will be filled in by data from the data source.
  • Data Source: This is the spreadsheet or database containing the information you want to use to populate your main document. It can be an Excel sheet, Access database, CSV file, XML file or even a simple text file.
  • Merge Fields: These are placeholders in the main document that will be replaced with data from the corresponding record in the data source.

Create a Template Word Document

To generate a template Word document with merge fields, it’s recommended that you use Word editors such as Microsoft Word. The visual interface of the Word editor allows you to design a unique layout, formatting, and other elements interactively for your template.

The following screenshot shows the addition of merge fields to a Word document using MS Word. Remember to use the "Image:FieldName" format if you want to merge an image into a merge field.

C#: Mail Merge in Word Documents

If you wish to create a template Word document using C# code, you can follow these steps.

  • Create a Document object.
  • Add a section.
  • Add a paragraph to the section.
  • Add merge fields to the paragraph using Paragraph.AppendField() method.
  • Save the document to a Word file.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;

namespace CreateTemplate
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document document = new Document();

            // Add a section
            Section section = document.AddSection();

            // Add a paragraph
            Paragraph paragraph = section.AddParagraph();

            // Add text and mail merge fields to the paragraph
            paragraph.AppendText("Full Name: ");
            paragraph.AppendField("Name", FieldType.FieldMergeField);
            paragraph.AppendBreak(BreakType.LineBreak);
            paragraph.AppendText("Email Address: ");
            paragraph.AppendField("Email", FieldType.FieldMergeField);
            paragraph.AppendBreak(BreakType.LineBreak);
            paragraph.AppendText("Avatar: ");
            paragraph.AppendField("Image:Avatar", FieldType.FieldMergeField);

            // Save the document
            document.SaveToFile("Template.docx", FileFormat.Docx2019);

            // Dispose resources
            document.Dispose();
        }
    }
}

Simple Mail Merge in a Word Document

Spire.Doc offers the MailMerge.Execute() method to perform the specified mail merge operation in a Word document. This method has 6 overloads allowing users to perform a mail merge from different data sources, such as DataTable, DataView, and string arrays.

The steps to perform a mail merge using data provided in arrays are as follows.

  • Create a Document object.
  • Load a template Word document from a specified file path.
  • Define an array to hold the field names.
  • Define an array to hold the values that will be used to fill the fields
  • Mail merge data into the fields using MailMerge.Execute() method.
  • Save the document to a different Word file.
  • C#
using Spire.Doc;
using Spire.Doc.Reporting;
using System.Drawing;

namespace MailMergeInDocument
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document document = new Document();

            // Load the template Word document
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx");

            // Specify field names
            String[] fieldNames = {

                "Name",
                "Email",
                "Avatar"
            };

            // Specify values that'll be used to fill the fields
            String[] fieldValues = {

                "John Smith",
                "john.smith@e-iceblue.com",
                "C:\\Users\\Administrator\\Desktop\\avatar.png"
            };

            // Register an event which occurs when merging the image filed
            document.MailMerge.MergeImageField += new MergeImageFieldEventHandler(MailMerge_MergeImageField);

            // Mail merge data to the document  
            document.MailMerge.Execute(fieldNames, fieldValues);

            // Save the document  
            document.SaveToFile("MailMerge.docx", FileFormat.Docx2019);

            // Dispose resources
            document.Dispose();
        }

        // Fill an image field with a picture
        private static void MailMerge_MergeImageField(object sender, MergeImageFieldEventArgs field)
        {
            string filePath = field.FieldValue as string;

            if (!string.IsNullOrEmpty(filePath))
            {
                field.Image = Image.FromFile(filePath);
            }
        }
    }
}

C#: Mail Merge in Word Documents

Mail Merge with a Region

A region refers to a specific area within a document where you want to insert data from your data source. Mail Merge will repeat that region for each record in the data source. Spire.Doc offers the MailMerge.ExecuteWidthRegion() method to execute mail merge with a region.

The steps to perform a mail merge with a region using the data provided by a DataTable are as follows.

  • Create a Document object.
  • Load a template Word document from a specified file path.
  • Create a DataTable object, which will be used as the data source.
  • Execute mail merge with the region using MailMerge.ExecuteWidthRegion() method.
  • Save the document to a different Word file.
  • C#
using Spire.Doc;
using System.Data;

namespace MailMergeWithGroup
{
    class Program
    {
        static void Main(string[] args)
        {

            // Create a Document object
            Document document = new Document();

            // Load a template Word document
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx");

            // Create a datatable, specifying table name
            DataTable table = new DataTable("Employee");

            // Add sample data to table
            table.Columns.Add("Name");
            table.Columns.Add("Address");
            table.Columns.Add("City");
            table.Rows.Add("John Doe", "123 Main St", "New York");
            table.Rows.Add("Jane Smith", "456 Elm St", "Los Angeles");
            table.Rows.Add("Bob Johnson", "789 Oak St", "Chicago");

            // Mail merge within the region
            document.MailMerge.ExecuteWidthRegion(table);

            // Save the document  
            document.SaveToFile("MailMergeWithRegion.docx", FileFormat.Docx2019);

            // Dispose resources
            document.Dispose();
        }
    }
}

C#: Mail Merge in Word Documents

Mail Merge with Nested Regions

Mail merge for nested groups works by replacing merge fields within nested regions with data that is organized in a hierarchical structure. Nested regions allow you to create more complex layouts where the content of one region depends on the data in another region.

The steps to perform a mail merge with nested regions using the data from an XML file are as follows.

  • Create a Document object.
  • Load a template Word document from a specified file path.
  • Read data from an XML file to a DataSet object.
  • Create a List<DictionaryEntry> object to store the merge field information.
  • Create DicitionaryEntry objects and add them to the list, which specify the merge field names and associated expressions.
  • Execute mail merge with the nested regions using MailMerge.ExecuteWidthNestedRegion() method.
  • Save the document to a different Word file.
  • C#
using Spire.Doc;
using System.Collections;
using System.Data;

namespace MailMergeWithNestedRegions
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document document = new Document();

            // Load a template Word document
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Template.docx");

            // Read data from an XML file to a DataSet object
            DataSet dataSet = new DataSet();
            dataSet.ReadXml("C:\\Users\\Administrator\\Desktop\\Orders.xml");

            // Create a List object to store the merge field information
            List list = new List();

            // Create two DicitionaryEntry objects and add them to the list (each object specifies the merge field name and associated expression)
            DictionaryEntry dictionaryEntry = new DictionaryEntry("Customer", string.Empty);
            list.Add(dictionaryEntry);

            dictionaryEntry = new DictionaryEntry("Order", "Customer_Id = %Customer.Customer_Id%");
            list.Add(dictionaryEntry);

            // Perform the mail merge operation with the nested region
            document.MailMerge.ExecuteWidthNestedRegion(dataSet, list);

            // Save to file
            document.SaveToFile("MailMergeWithNestedRegions.docx", FileFormat.Docx2019);

            // Dispose resources
            document.Dispose();
        }
    }
}

C#: Mail Merge in Word Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

PDF Split in C#, VB.NET

2011-04-06 09:53:44 Written by Administrator

The sample demonstrates how to split one PDF document to multiple PDF documents.

(NO screenshot)

PDF Merge in C#, VB.NET

2011-04-06 09:50:38 Written by Administrator

The sample demonstrates how to merge multiple PDF documents to one PDF document.

(NO screenshot)

PDF Extract in C#, VB.NET

2011-04-06 09:47:25 Written by Administrator

The sample demonstrates how to extract images and text from PDF document.

(NO screenshot)

page 84