Following code snippets demonstrate how to send an email with HTML body using Spire.Email in C# and VB.NET.

Step 1: Create an instance of MailMessage class and specify sender and recipient in its constructor.

MailAddress addressFrom = new MailAddress("jack.du@e-iceblue.com", "Jack Du");
MailAddress addressTo = new MailAddress("susanwong32@outlook.com");
MailMessage message = new MailMessage(addressFrom, addressTo);

Step 2: Set the creation date, subject and html body of the message.

message.Date = DateTime.Now;
message.Subject = "Sending Email with HTML Body";
string htmlString = @"<html>
                      <body>
                      <p>Dear Ms. Susan,</p>
                      <p>Thank you for your letter of yesterday inviting me to come for an interview on Friday afternoon, 5th July, at 2:30.
                              I shall be happy to be there as requested and will bring my diploma and other papers with me.</p>
                      <p>Sincerely,<br>-Jack</br></p>
                      </body>
                      </html>
                     ";   
message.BodyHtml = htmlString;

Step 3: Create a SmtpClient instance, set its properties, and send the email using SendOne() medthod.

SmtpClient client= new SmtpClient();
client.Host = "smtp.outlook.com";
client.Port = 587;
client.Username = addressFrom.Address;
client.Password = "password";
client.ConnectionProtocols = ConnectionProtocols.Ssl;
client.SendOne(message);

Output:

Send Email with HTML Body in C#, VB.NET

Full Code:

[C#]
MailAddress addressFrom = new MailAddress("jack.du@e-iceblue.com", "Jack Du");
MailAddress addressTo = new MailAddress("susanwong32@outlook.com");
MailMessage message = new MailMessage(addressFrom, addressTo);

message.Date = DateTime.Now;
message.Subject = "Sending Email with HTML Body";
string htmlString = @"<html>
                      <body>
                      <p>Dear Ms. Susan,</p>
                      <p>Thank you for your letter of yesterday inviting me to come for an interview on Friday afternoon, 5th July, at 2:30.
                              I shall be happy to be there as requested and will bring my diploma and other papers with me.</p>
                      <p>Sincerely,<br>-Jack</br></p>
                      </body>
                      </html>
                     ";   
message.BodyHtml = htmlString;

SmtpClient client= new SmtpClient();
client.Host = "smtp.outlook.com";
client.Port = 587;
client.Username = addressFrom.Address;
client.Password = "password";
client.ConnectionProtocols = ConnectionProtocols.Ssl;
client.SendOne(message);

Console.WriteLine("Sent Successfully!");
Console.Read();
[VB.NET]
Dim addressFrom As MailAddress =  New MailAddress("jack.du@e-iceblue.com","Jack Du") 
Dim addressTo As MailAddress =  New MailAddress("susanwong32@outlook.com") 
Dim message As MailMessage =  New MailMessage(addressFrom,addressTo) 
 
message.Date = DateTime.Now
message.Subject = "Sending Email with HTML Body"
String htmlString = "<html>
                      <body>
                      <p>Dear Ms. Susan,</p>
                      <p>Thank you for your letter of yesterday inviting me to come for an interview on Friday afternoon, 5th July, at 2:30.
                              I shall be happy to be there as requested and will bring my diploma and other papers with me.</p>
                      <p>Sincerely,<br>-Jack</br></p>
                      </body>
                      </html>
                     "   
message.BodyHtml = htmlString
 
Dim client As SmtpClient =  New SmtpClient() 
client.Host = "smtp.outlook.com"
client.Port = 587
client.Username = addressFrom.Address
client.Password = "password"
client.ConnectionProtocols = ConnectionProtocols.Ssl
client.SendOne(message)
 
Console.WriteLine("Sent Successfully!")
Console.Read()
Thursday, 29 June 2017 07:19

Send Email with Attachment in C#, VB.NET

This article illustrates how to create an email message with attachment and send it using Spire.Email component in C# and VB.NET.

Detail steps:

Step 1: Declare and assign three MailAddress objects.

MailAddress addressFrom = "Alice.yang@e-iceblue.com";
MailAddress addressTo = "leondavisld@outlook.com";
MailAddress adressCC = "Shawn_Smithhh@outlook.com";

Step 2: Create an email message.

MailMessage message = new MailMessage(addressFrom, addressTo);

Step 3: Set subject, text body and creation time for the message.

message.Subject = "Spire.Email Component";
message.BodyText = "Hi!\r\n"+
                "Spire.Email for .NET is a professional .NET Email library specially designed for developers to create, read and manipulate emails on any .NET (C#, VB.NET, ASP.NET) platform.";
message.Date = DateTime.Now;

Step 4: Add an attachment and the second receiver to cc.

message.Attachments.Add(new Attachment("Hydrangeas.jpg"));
message.Cc.Add(adressCC.Address);

Step 5: Create a SmtpClient instance and send the email message.

SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.outlook.com";
smtp.ConnectionProtocols = ConnectionProtocols.Ssl;
smtp.Username = addressFrom.Address;
smtp.Password = "password";
smtp.Port = 587;
smtp.SendOne(message);

Screenshot:

Send Email with Attachment in C#, VB.NET

Full code:

[C#]
using System;
using System.Globalization;
using Spire.Email;
using Spire.Email.IMap;
using Spire.Email.Smtp;

namespace Send_Email
{
    class Program
    {
        static void Main(string[] args)
        {
            MailAddress addressFrom = "Alice.yang@e-iceblue.com";
            MailAddress addressTo = "LeonDavisLD@outlook.com";
            MailAddress adressCC = "Shawn_Smithhh@outlook.com";

            MailMessage message = new MailMessage(addressFrom, addressTo);            

            message.Subject = "Spire.Email Component";
            message.BodyText = "Hi!\r\n"+
                "Spire.Email for .NET is a professional .NET Email library specially designed for developers to create, read and manipulate emails on any .NET (C#, VB.NET, ASP.NET) platform.";
            message.Date = DateTime.Now;

            message.Attachments.Add(new Attachment("Hydrangeas.jpg"));
            message.Cc.Add(adressCC.Address);
            
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.outlook.com";
            smtp.ConnectionProtocols = ConnectionProtocols.Ssl;
            smtp.Username = addressFrom.Address;
            smtp.Password = "password";
            smtp.Port = 587;

            Console.WriteLine("From   : " + message.From.ToString());
            Console.WriteLine("To     : " + message.To.ToString());
            Console.WriteLine("Date   : " + message.Date.ToString(CultureInfo.InvariantCulture));
            Console.WriteLine("Subject: " + message.Subject);
            Console.WriteLine("Attachment: " + message.Attachments.Count);
            Console.WriteLine("------------------- BODY -----------------");
            Console.WriteLine(message.BodyText);            
            Console.WriteLine("------------------- END ------------------");
            smtp.SendOne(message);

            Console.WriteLine("Message Sent.");
            Console.ReadLine();    
        }
    }
}
[VB.NET]
Imports System.Globalization
Imports Spire.Email
Imports Spire.Email.IMap
Imports Spire.Email.Smtp

Namespace Send_Email
	Class Program
		Private Shared Sub Main(args As String())
			Dim addressFrom As MailAddress = "Alice.yang@e-iceblue.com"
			Dim addressTo As MailAddress = "LeonDavisLD@outlook.com"
			Dim adressCC As MailAddress = "Shawn_Smithhh@outlook.com"

			Dim message As New MailMessage(addressFrom, addressTo)

			message.Subject = "Spire.Email Component"
			message.BodyText = "Hi!" & vbCr & vbLf + "Spire.Email for .NET is a professional .NET Email library specially designed for developers to create, read and manipulate emails on any .NET (C#, VB.NET, ASP.NET) platform."
			message.[Date] = DateTime.Now

			message.Attachments.Add(New Attachment("Hydrangeas.jpg"))
			message.Cc.Add(adressCC.Address)

			Dim smtp As New SmtpClient()
			smtp.Host = "smtp.outlook.com"
			smtp.ConnectionProtocols = ConnectionProtocols.Ssl
			smtp.Username = addressFrom.Address
			smtp.Password = "password"
			smtp.Port = 587

			Console.WriteLine("From   : " + message.From.ToString())
			Console.WriteLine("To     : " + message.To.ToString())
			Console.WriteLine("Date   : " + message.Date.ToString(CultureInfo.InvariantCulture))
			Console.WriteLine("Subject: " + message.Subject)
			Console.WriteLine("Attachment: " + message.Attachments.Count)
			Console.WriteLine("------------------- BODY -----------------")
			Console.WriteLine(message.BodyText)
			Console.WriteLine("------------------- END ------------------")
			smtp.SendOne(message)

			Console.WriteLine("Message Sent.")
			Console.ReadLine()
		End Sub
	End Class
End Namespace
Wednesday, 28 June 2017 08:40

How to Scan Barcode in C#

We have already demonstrated how to generate 1D barcode and 2D barcodes by using Spire.Barcode. This article will demonstrate how to scan the barcode images with Spire.Barcode. Spire.Barcode supports scanning the barcode image in .bmp, .png and .jpg image format. We will use Spire.Barcode to scan both 1D barcode and 2D barcode for example.

Scan Code39 barcode image:

string[] data = Spire.Barcode.BarcodeScanner.Scan("Code39.png",
Spire.Barcode.BarCodeType.Code39);

How to Scan Barcode in C#

Scan QRCode barcode image:

string[] data = Spire.Barcode.BarcodeScanner.Scan("QRCode.png", Spire.Barcode.BarCodeType.QRCode);

How to Scan Barcode in C#

Spire.Doc provides the ability to find the words that match a specific regular expression in a Word document and replace the matched words with a new string. This following code snippets give an example.

Step 1: Create an object of Document and load a test document.

Document doc = new Document();
doc.LoadFromFile("example.docx");

Step 2: Define a regular expression for the words that start with #.

Regex regex = new Regex(@"\#\w+\b");

Step 3: Call Document.Repalce(Regex pattern, string replace) method to replace the matched text with a new string.

doc.Replace(regex, "Spire.Doc");

Step 4: Save the file.

doc.SaveToFile("output.docx", FileFormat.Docx2013);

Result:

How to Find and Replace Text by Regular Expressions in Word in C#, VB.NET

Full Code:

[C#]
Document doc = new Document();
doc.LoadFromFile("example.docx");
Regex regex = new Regex(@"\#\w+\b");
doc.Replace(regex, "Spire.Doc");
doc.SaveToFile("output.docx", FileFormat.Docx2013);
[VB.NET]
Dim doc As New Document()
doc.LoadFromFile("example.docx")
Dim regex As New Regex("\#\w+\b")
doc.Replace(regex, "Spire.Doc")
doc.SaveToFile("output.docx", FileFormat.Docx2013)

Document variables are used to preserve macro settings in between macro sessions. Spire.Doc allows adding variables, counting the number of variables, retrieving the name and value of variables, and removing specific variables in a Word document.

Add a Variable

Use the Add method to add a variable to a document. The following example adds a document variable named "A1" with a value of 12 to the document.

//Instantiate a document object
Document document = new Document();
//Add a section
Section section = document.AddSection();
//Add a paragraph
Paragraph paragraph = section.AddParagraph();
//Add a DocVariable Filed
paragraph.AppendField("A1", FieldType.FieldDocVariable);
//Add a document variable to the DocVariable Filed
document.Variables.Add("A1", "12");
 //Update fields
document.IsUpdateFields = true;
//Save and close the document object
document.SaveToFile("AddVariable.docx", FileFormat.Docx2013);
document.Close();

Add, Count, Retrieve and Remove Variables in a Word document Using C#

Count the number of Variables

Use the Count property to return the number of variables in a document.

//Load the document
Document document = new Document("AddVariable.docx");
//Get the number of variables in the document
int number = document.Variables.Count;

Console.WriteLine(number);

Add, Count, Retrieve and Remove Variables in a Word document Using C#

Retrieve Name and Value of a Variable

Use the GetNameByIndex and GetValueByIndex methods to retrieve the name and value of the variable by index, and the Variables[String Name] to retrieve or set the value of the variable by name.

//Load the document
Document document = new Document("AddVariable.docx");

// Retrieve name of the variable by index
string s1 = document.Variables.GetNameByIndex(0);

// Retrieve value of the variable by index
string s2 = document.Variables.GetValueByIndex(0);

// Retrieve or set value of the variable by name
string s3 = document.Variables["A1"];

Console.WriteLine("{0} {1} {2}", s1, s2, s3);

Add, Count, Retrieve and Remove Variables in a Word document Using C#

Remove a specific Variable

Use the Remove method to remove the variable from the document.

//Load the document
Document document = new Document("AddVariable.docx");

//Remove the variable by name
document.Variables.Remove("A1");

//Save and close the document object
document.SaveToFile("RemoveVariable.docx", FileFormat.Docx2013);
document.Close();

When we operate the data on an Excel worksheet, we may need to delete text from a cell in a spreadsheet document and sometimes even remove all the contents with format from the cell range. This article will demonstrate how to remove the value and format from Excel Cell range with the help of Spire.XLS.

Step 1: Create an instance of Excel workbook and load the document from file.

Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");

Step 2: Get the first worksheet from the workbook.

Worksheet sheet = workbook.Worksheets[0];

Step 3: Set the value as null to remove the original content from the Excel Cell.

sheet.Range["A1"].Value = "";

Step 4: Clear the contents to remove the original content from the Excel Cell.

sheet.Range["A3"].ClearContents();

Step 5: Remove the contents with format from the Excel cell.

sheet.Range["B1"].ClearAll();

Step 6: Save document to file.

workbook.SaveToFile("result.xlsx",FileFormat.Version2010);

Effective screenshot of remove the value and format from Excel Cell range:

How to remove the value and format from Excel Cell range

Full codes:

static void Main(string[] args)
{
     
    Workbook workbook = new Workbook();
    workbook.LoadFromFile("Sample.xlsx");

    Worksheet sheet = workbook.Worksheets[0];

    sheet.Range["A1"].Value = "";

    sheet.Range["A3"].ClearContents();

    sheet.Range["B1"].ClearAll();
    

    workbook.SaveToFile("result.xlsx",FileFormat.Version2010);
}
Friday, 16 June 2017 06:20

How to Create PDF417 Barcode in C#

The PDF417 barcode, also known as Portable Data File 417 or PDF417 Truncated, is a two-dimensional (2D), high-density symbology capable of encoding text, numbers, files and actual data bytes.

Compaction Modes

The data is encoded using one of three compaction modes: Text compaction mode, Binary compaction mode, and Numeric compaction mode.

  • Text: It allows encoding all printable ASCII characters, i.e. values from 32 to 126 inclusive in accordance with ISO/IEC 646, as well as selected control characters such as TAB (horizontal tab ASCII 9), LF (NL line feed, new line ASCII 10) and CR (carriage return ASCII 13).
  • Binary: It allows encoding all 256 possible 8-bit byte values. This includes all ASCII characters value from 0 to 127 inclusive and provides for international character set support.
  • Numeric: It allows efficient encoding of numeric data strings.
  • Auto: It switches between Text, Binary and Numeric modes in order to minimize the number of codewords to be encoded.

PDF417 Error Correction Levels

Error correction allows the symbol to endure some damage without causing loss of data. The error correction level depends on the amount of data that needs to be encoded, the size and the amount of symbol damage that could occur. The error correction levels range from 0 to 8.

EC Level 0 1 2 3 4 5 6 7 8
EC Codewords Generated 2 4 6 8 16 32 64 128 512
Data Codewords 1-40 41-160 161-320 321-863
Data Bytes Encoded 1-56 57-192 193-384 385-1035

Following code snippets show how to create a PDF417 barcode image using Spire.Barcode.

Step 1: Create an instance of BarcodeSetting class.

BarcodeSettings settings = new BarcodeSettings();

Step 2: Set the barode type as Pdf417 and set the data to be encoded.

settings.Type = BarCodeType.Pdf417;
settings.Data = "123456789";

Step 3: Set the data mode as numeric.

settings.Pdf417DataMode = Pdf417DataMode.Numeric;

Step 4: Set the error correction level as level 2.

settings.Pdf417ECL = Pdf417ECL.Level2;

Step 5: Initialize an instance of BarcodeGenerator and generate an image based on the settings.

BarCodeGenerator generator = new BarCodeGenerator(settings);
Image image = generator.GenerateImage();   

Step 6: Save the image in .png format.

image.Save("PDF417Code.png");

Output:

How to Create PDF417 Barcode in C#

Full Code:

BarcodeSettings settings = new BarcodeSettings();
settings.Type = BarCodeType.Pdf417;
settings.Data = "123456789";
settings.Data2D = "123456789";
settings.Pdf417DataMode = Pdf417DataMode.Numeric;
settings.Pdf417ECL = Pdf417ECL.Level2;
BarCodeGenerator generator = new BarCodeGenerator(settings);
Image image = generator.GenerateImage();
image.Save("PDF417Code.png");
Wednesday, 14 June 2017 07:27

Create a QR Code in C#

QR code (abbreviated from Quick Response Code) is a two dimensional (2D) barcode symbology first designed for the automotive industry in Japan. A QR code is readable from all directions and can use a variety of encoding modes such as numeric, alphanumeric and byte/binary to efficiently store data.

The following code example shows how to create a QR Barcode using Spire.Barcode.

Step 1: Instantiate a BarcodeSettings object.

BarcodeSettings settings = new BarcodeSettings();

Step 2: Set barcode type as QR code.

settings.Type = BarCodeType.QRCode;

Step 3: Set data and display text for the code.

settings.Data = "Hello 123456789";
settings.Data2D = "Hello 123456789";

Step 4: Set encode mode.

settings.QRCodeDataMode = QRCodeDataMode.AlphaNumber;

Step 5: Set width of the barcode bar module.

settings.X = 1.0f;

Step 6: Set error correction level of the barcode.

settings.QRCodeECL = QRCodeECL.H;

Step 7: Instantiate a BarCodeGenerator object.

BarCodeGenerator generator = new BarCodeGenerator(settings);

Step 8: Generate the barcode image.

Image image = generator.GenerateImage();

Step 9: Save the barcode image.

image.Save("QRCode.png");

The produced QR barcode image looks as follows.

Create a QR Code in C#

Full Code:

BarcodeSettings settings = new BarcodeSettings();
settings.Type = BarCodeType.QRCode;

settings.Data = "Hello 123456789";
settings.Data2D = "Hello 123456789";
settings.QRCodeDataMode = QRCodeDataMode.AlphaNumber;
settings.X = 1.0f;
settings.QRCodeECL = QRCodeECL.H;

BarCodeGenerator generator = new BarCodeGenerator(settings);
Image image = generator.GenerateImage();
image.Save("QRCode.png");
Monday, 12 June 2017 07:45

How to create Code39 barcodes in C#

Code39 is also known as Alpha39, Code 3 of 9, Code 3/9, Type 39, USS Code 39, USD-3. This article will show you how to use Spire.Barcode to create Code39 barcode. It supports 43 characters, consisting of uppercase letters (A through Z), numeric digits (0 through 9) and a number of special characters (*, -, $, /, +, %, and space). Usually Code39 starts and ends with “*”. Here comes to the steps of how to create Code39 barcodes.

Step 1: Create a BarcodeSettings instance.

BarcodeSettings bs = new BarcodeSettings();

Step 2: Set the BarcodeType property to Code39

bs.Type = BarCodeType.Code39;

Step 3: Set the data for the barcode.

bs.Data = "*ABC 12345* ";

Step 4: Generate barcode image using BarCodeGenerator.

BarCodeGenerator bg = new BarCodeGenerator(bs);
bg.GenerateImage().Save("Code39Code.png");    

Effective screenshot of Code39 barcode image:

How to create Code39 barcodes in C#

Full codes:

{
BarcodeSettings bs = new BarcodeSettings();

    bs.Type = BarCodeType.Code39;
    bs.Data = "*ABC 12345* ";

               
BarCodeGenerator bg = new BarCodeGenerator(bs);

    bg.GenerateImage().Save("Code39Code.png");               
    System.Diagnostics.Process.Start("Code39Code.png");
}
Friday, 09 June 2017 06:41

Convert PDF Page to SVG in C#, VB.NET

Spire.PDF allows us to convert a PDF document, a single page or a range of pages in a PDF document to SVG file format. We have introduced how to convert a PDF document to SVG, in this tutorial, we are going to demonstrate how to convert a PDF page to SVG.

Below is the source PDF file we used in this example:

Convert PDF Page to SVG in C#, VB.NET

Code snippets:

Step 1: Instantiate an object of PdfDocument class and load the PDF document.

PdfDocument doc = new PdfDocument();
doc.LoadFromFile("Test.pdf");

Step 2: Convert the first page of the PDF document to SVG using the SaveToFile(string filename, int startIndex, int endIndex, FileFormat fileFormat) method.

doc.SaveToFile("Result.svg", 0, 0, FileFormat.SVG);

The resultant SVG file looks as follows:

Convert PDF Page to SVG in C#, VB.NET

Full code:

[C#]
using Spire.Pdf;

namespace PDF_Page_to_SVG
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile("Test.pdf");
            doc.SaveToFile("Result.svg", 0, 0, FileFormat.SVG);
        }
    }
}
[VB.NET]
Imports Spire.Pdf

Namespace PDF_Page_to_SVG
	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As New PdfDocument()
			doc.LoadFromFile("Test.pdf")
			doc.SaveToFile("Result.svg", 0, 0, FileFormat.SVG)
		End Sub
	End Class
End Namespace