Headers or footers are added to a worksheet to deliver some extra information about each page. By default, the headers or footers on odd and even pages are the same. However, we are able to set different headers or footers for odd and even pages to display different information.

Following sections demonstrate how to create different odd and even page headers/footers using Spire.XLS.

Code Snippet:

Step 1: Initialize an instance of Workbook and get the first worksheet.

Workbook wb = new Workbook();
Worksheet sheet = wb.Worksheets[0];

Step 2: Set the value of DifferentOddEven as 1, which indicates that headers/footers for odd and even pages are different.

sheet.PageSetup.DifferentOddEven = 1;

Step 3: Set header and footer string for odd pages, and format the string.

sheet.PageSetup.OddHeaderString = "&\"Arial\"&12&B&KFFC000Odd_Header";
sheet.PageSetup.OddFooterString = "&\"Arial\"&12&B&KFFC000Odd_Footer";

Step 4: Set different header and footer string for even pages, and format the string with different color.

sheet.PageSetup.EvenHeaderString = "&\"Arial\"&12&B&KFF0000Even_Header";
sheet.PageSetup.EvenFooterString = "&\"Arial\"&12&B&KFF0000Even_Footer";

Step 5: Save the file.

wb.SaveToFile("OddEvenHeaderFooter.xlsx", ExcelVersion.Version2013);

Output:


How to Set Different Header or Footer for Odd and Even Pages in Excel in C#, VB.NET

Full Code:

[C#]
using Spire.Xls;
namespace SetDifferentHeaderorFooter 
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook wb = new Workbook();
            Worksheet sheet = wb.Worksheets[0];

            sheet.Range["A1"].Text = "Page 1";
            sheet.Range["J1"].Text = "Page 2";

            sheet.PageSetup.DifferentOddEven = 1;
            sheet.PageSetup.OddHeaderString = "&\"Arial\"&12&B&KFFC000Odd_Header";
            sheet.PageSetup.OddFooterString = "&\"Arial\"&12&B&KFFC000Odd_Footer";
            sheet.PageSetup.EvenHeaderString = "&\"Arial\"&12&B&KFF0000Even_Header";
            sheet.PageSetup.EvenFooterString = "&\"Arial\"&12&B&KFF0000Even_Footer";

            wb.SaveToFile("OddEvenHeaderFooter.xlsx", ExcelVersion.Version2013);
        }
    }
}
[VB.NET]
Imports Spire.Xls
Namespace SetDifferentHeaderorFooter
	Class Program
		Private Shared Sub Main(args As String())
			Dim wb As New Workbook()
			Dim sheet As Worksheet = wb.Worksheets(0)

			sheet.Range("A1").Text = "Page 1"
			sheet.Range("J1").Text = "Page 2"

			sheet.PageSetup.DifferentOddEven = 1
			sheet.PageSetup.OddHeaderString = "&""Arial""&12&B&KFFC000Odd_Header"
			sheet.PageSetup.OddFooterString = "&""Arial""&12&B&KFFC000Odd_Footer"
			sheet.PageSetup.EvenHeaderString = "&""Arial""&12&B&KFF0000Even_Header"
			sheet.PageSetup.EvenFooterString = "&""Arial""&12&B&KFF0000Even_Footer"

			wb.SaveToFile("OddEvenHeaderFooter.xlsx", ExcelVersion.Version2013)
		End Sub
	End Class
End Namespace

To make the text within a cell diverse, we can apply different font to different range of characters. Spire.XLS also provides the ability to apply multiple fonts in a single cell by using RichText.SetFont() method. This article presents how to create different fonts in a workbook and apply them to a certain cell in C# and VB.NET.

Code Snippet:

Step 1: Initialize an instance of Workbook class and get the first worksheet.

Workbook wb = new Workbook();
Worksheet sheet = wb.Worksheets[0];

Step 2: Create a font object in workbook, setting the font color, size and type.

ExcelFont font1 = wb.CreateFont();
font1.KnownColor = ExcelColors.LightBlue;
font1.IsBold = true;
font1.Size = 10;

Step 3: Create another font object specifying its properties.

ExcelFont font2 = wb.CreateFont();
font2.KnownColor = ExcelColors.Red;
font2.IsBold = true;
font2.IsItalic = true;
font2.FontName = "Times New Roman";
font2.Size = 11;

Step 4: Write a RichText string to the cell 'A1', and set the font for the specific range of characters using RichText.SetFont() method.

RichText richText = sheet.Range["A1"].RichText;
richText.Text = "This document was created with Spire.XLS for .NET.";
richText.SetFont(0, 29, font1);
richText.SetFont(31, 48, font2);

Step 5: Save the file.

wb.SaveToFile("MultiFonts.xlsx", ExcelVersion.Version2010);

Output:

How to Apply Multiple Fonts in a Single Cell in C#, VB.NET

Full Code:

[C#]
using Spire.Xls;
namespace ApplyMutipleFont
{
    class Program
    {

        static void Main(string[] args)
        {
            Workbook wb = new Workbook();
            Worksheet sheet = wb.Worksheets[0];

            ExcelFont font1 = wb.CreateFont();
            font1.KnownColor = ExcelColors.LightBlue;
            font1.IsBold = true;
            font1.Size = 10;

            ExcelFont font2 = wb.CreateFont();
            font2.KnownColor = ExcelColors.Red;
            font2.IsBold = true;
            font2.IsItalic = true;
            font2.FontName = "Times New Roman";
            font2.Size = 11;

            RichText richText = sheet.Range["A1"].RichText;
            richText.Text = "This document was created with Spire.XLS for .NET.";
            richText.SetFont(0, 29, font1);
            richText.SetFont(31, 48, font2);

            wb.SaveToFile("MultiFonts.xlsx", ExcelVersion.Version2010);
        }
    }
}
[VB.NET]
Imports Spire.Xls
Namespace ApplyMutipleFont
	Class Program

		Private Shared Sub Main(args As String())
			Dim wb As New Workbook()
			Dim sheet As Worksheet = wb.Worksheets(0)

			Dim font1 As ExcelFont = wb.CreateFont()
			font1.KnownColor = ExcelColors.LightBlue
			font1.IsBold = True
			font1.Size = 10

			Dim font2 As ExcelFont = wb.CreateFont()
			font2.KnownColor = ExcelColors.Red
			font2.IsBold = True
			font2.IsItalic = True
			font2.FontName = "Times New Roman"
			font2.Size = 11

			Dim richText As RichText = sheet.Range("A1").RichText
			richText.Text = "This document was created with Spire.XLS for .NET."
			richText.SetFont(0, 29, font1)
			richText.SetFont(31, 48, font2)

			wb.SaveToFile("MultiFonts.xlsx", ExcelVersion.Version2010)
		End Sub
	End Class
End Namespace

How to add signature field to PDF

2016-09-14 09:08:42 Written by Koohji

Except for creating signature, Spire.PDF also allows us to add signature field to PDF using the PdfSignatureField class and the PdfFieldCollection.Add (PdfField field) method in Spire.Pdf.Fields namespace. Once added, we can click on the field to add signature manually to the PDF document.

This article explains how to add a signature field to the specified page of a PDF document using Spire.PDF.

Detail steps and code snippets:

Step 1: Create a new PDF document and add a page to it.

PdfDocument pdfdoc = new PdfDocument();
PdfPageBase page = pdfdoc.Pages.Add();

Step 2: Use PdfSignatureField class to add a named signature field to the specified page by passing two parameters: page and name of the signature field.

PdfSignatureField signaturefield = new PdfSignatureField(page, "Signature");

Step 3: Set border width, style, color, highlight mode and bounds for the signature field.

signaturefield.BorderWidth = 1.0f;
signaturefield.BorderStyle = PdfBorderStyle.Solid;
signaturefield.BorderColor = new PdfRGBColor(System.Drawing.Color.Black);
signaturefield.HighlightMode = PdfHighlightMode.Outline;
signaturefield.Bounds = new RectangleF(100, 100, 100, 100);

Step 4: Add the signature field to the document's root fields.

pdfdoc.Form.Fields.Add(signaturefield);

Step 5: Save the document.

pdfdoc.SaveToFile("AddSignField.pdf", FileFormat.PDF);

After running the code, we'll get the result PDF file with a signature field on the first page, effective screenshot as shown below:

How to add signature field to PDF

Full codes:

using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Fields;
using Spire.Pdf.Graphics;

namespace Add_Signature_Filed_to_PDF
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument pdfdoc = new PdfDocument();
            PdfPageBase page = pdfdoc.Pages.Add();

            PdfSignatureField signaturefield = new PdfSignatureField(page, "Signature");
            signaturefield.BorderWidth = 1.0f;
            signaturefield.BorderStyle = PdfBorderStyle.Solid;
            signaturefield.BorderColor = new PdfRGBColor(System.Drawing.Color.Black);
            signaturefield.HighlightMode = PdfHighlightMode.Outline;
            signaturefield.Bounds = new RectangleF(100, 100, 100, 100);
            pdfdoc.Form.Fields.Add(signaturefield);
            pdfdoc.SaveToFile("AddSignField.pdf", FileFormat.PDF);
        }
    }
}

Sometimes, we need to extract the OLE Objects that are embedded in a word document. With Spire.Doc, we can easily achieve this task with a few lines of code. This article explains how to extract the embedded PDF document and Excel workbook from a word document using Spire.Doc and C#.

Below is the screenshot of the word document:

How to Extract OLE Objects from a Word Document

Detail steps:

Step 1: Instantiate a Document object and load the word document.

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

Step 2: Traverse through the word document, find the Ole Objects, then get the Object type of each Ole Object to determine if the Ole Object is PDF document or Excel workbook and write the native data of the Ole object into a new PDF document or an Excel workbook.

//Traverse through all sections of the word document           
foreach (Section sec in doc.Sections)
{
    //Traverse through all Child Objects in the body of each section
    foreach (DocumentObject obj in sec.Body.ChildObjects)
    {
        if (obj is Paragraph)
        {
            Paragraph par = obj as Paragraph;
            //Traverse through all Child Objects in Paragraph
            foreach (DocumentObject o in par.ChildObjects)
            {
                //Find the Ole Objects and Extract
                if (o.DocumentObjectType == DocumentObjectType.OleObject)
                {
                    DocOleObject Ole = o as DocOleObject;
                    string s = Ole.ObjectType;
                    //If s == "AcroExch.Document.11", means it’s a PDF document
                    if (s == "AcroExch.Document.11")
                    {
                        File.WriteAllBytes("Result.pdf", Ole.NativeData);
                    }
                    //If s == " Excel.Sheet.12", means it’s an Excel workbook
                    else if (s == "Excel.Sheet.12")
                    {
                        File.WriteAllBytes("Result.xlsx", Ole.NativeData);
                    }
                }
            }
        }
    }
}

Below is the screenshot of the extracted PDF file and Excel workbook after running the code:

How to Extract OLE Objects from a Word Document

How to Extract OLE Objects from a Word Document

Full codes:

using System.IO;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace Extract_OLEObjects_from_Word
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("OleObject.docx");
        
            foreach (Section sec in doc.Sections)
            {
                foreach (DocumentObject obj in sec.Body.ChildObjects)
                {
                    if (obj is Paragraph)
                    {
                        Paragraph par = obj as Paragraph;
                        foreach (DocumentObject o in par.ChildObjects)
                        {
                            if (o.DocumentObjectType == DocumentObjectType.OleObject)
                            {
                                DocOleObject Ole = o as DocOleObject;
                                string s = Ole.ObjectType;
                                if (s == "AcroExch.Document.11")
                                {
                                    File.WriteAllBytes("Result.pdf", Ole.NativeData);
                                }
                                else if (s == "Excel.Sheet.12")
                                {
                                    File.WriteAllBytes("Result.xlsx", Ole.NativeData);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

Form fields are often used in documents like surveys, registration forms, or feedback forms to collect data from users. Extracting form field values allows you to gather and consolidate the submitted data for further analysis or processing. In this article, we will demonstrate how to extract form field values from PDF documents in C# and VB.NET using Spire.PDF for .NET.

Install Spire.PDF for .NET

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

PM> Install-Package Spire.PDF

Extract Form Field Values from PDF in C# and VB.NET

In a PDF document, you may encounter various types of form fields, such as textboxes, checkboxes, radio buttons, list boxes, and combo boxes (drop-down lists). Before extracting form field values, it is crucial to identify the specific type of each form field. Once identified, you can utilize corresponding properties tailored for each form field type to accurately extract their values. The detailed steps are as follows:

  • Initialize an instance of the PdfDocument instance.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Initialize an instance of the StringBuilder class for storing the extract form field values.
  • Get the form from the document using PdfDocument.Form property.
  • Iterate through all form fields in the form.
  • Determine the types of the form fields, then get the names and values of the form fields using the corresponding properties and append them to the StringBuilder instance.
  • Write the content of the StringBuilder instance into a text file.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Fields;
using Spire.Pdf.Widget;
using System.IO;
using System.Text;

namespace ExtractFormFieldValues
{
    internal class Program
    {
        static void Main(string[] args)
        {            
            //Initialize an instance of the PdfDocument instance
            PdfDocument doc = new PdfDocument();
            //Load a PDF document
            doc.LoadFromFile(@"Forms.pdf");

            //Initialize an instance of the StringBuilder class
            StringBuilder sb = new StringBuilder();

            //Get the form from the document
            PdfFormWidget formWidget = doc.Form as PdfFormWidget;

            //Iterate through all fields in the form
            for (int i = 0; i < formWidget.FieldsWidget.List.Count; i++)
            {
                PdfField field = formWidget.FieldsWidget.List[i] as PdfField;

                //Get the name and value of textbox field
                if (field is PdfTextBoxFieldWidget)
                {
                    PdfTextBoxFieldWidget textBoxField = field as PdfTextBoxFieldWidget;                    
                    string name = textBoxField.Name;
                    string value = textBoxField.Text;
                    sb.Append("Textbox Name: " + name + "\r\n");
                    sb.Append("Textbox Value: " + value + "\r\n");
                }

                //Get the name, items and selected item of list box field
                if (field is PdfListBoxWidgetFieldWidget)
                {
                    PdfListBoxWidgetFieldWidget listBoxField = field as PdfListBoxWidgetFieldWidget;
                    string name = listBoxField.Name;
                    sb.Append("Listbox Name: " + name + "\r\n");
                    sb.Append("Listbox Items: \r\n");

                    PdfListWidgetItemCollection items = listBoxField.Values;

                    foreach (PdfListWidgetItem item in items)
                    {
                        sb.Append(item.Value + "\r\n");
                    }
                    string selectedValue = listBoxField.SelectedValue;
                    sb.Append("Listbox Selected Value: " + selectedValue + "\r\n");
                }

                //Get the name, items and selected item of combo box field
                if (field is PdfComboBoxWidgetFieldWidget)
                {
                    PdfComboBoxWidgetFieldWidget comBoxField = field as PdfComboBoxWidgetFieldWidget;
                    string name = comBoxField.Name;
                    sb.Append("Combobox Name: " + name + "\r\n");
                    sb.Append("Combobox Items: \r\n");
                    PdfListWidgetItemCollection items = comBoxField.Values;

                    foreach (PdfListWidgetItem item in items)
                    {
                        sb.Append(item.Value + "\r\n");
                    }
                    string selectedValue = comBoxField.SelectedValue;
                    sb.Append("Combobox Selected Value: " + selectedValue + "\r\n");

                }

                //Get the name and selected item of radio button field
                if (field is PdfRadioButtonListFieldWidget)
                {
                    PdfRadioButtonListFieldWidget radioBtnField = field as PdfRadioButtonListFieldWidget;
                    string name = radioBtnField.Name;
                    sb.Append("Radio Button Name: " + name + "\r\n");
                    string selectedValue = radioBtnField.SelectedValue;
                    sb.Append("Radio Button Selected Value: " + selectedValue + "\r\n");
                }

                //Get the name and status of checkbox field
                if (field is PdfCheckBoxWidgetFieldWidget)
                {
                    PdfCheckBoxWidgetFieldWidget checkBoxField = field as PdfCheckBoxWidgetFieldWidget;
                    string name = checkBoxField.Name;
                    sb.Append("Checkbox Name: " + name + "\r\n");
                    bool status = checkBoxField.Checked;
                    if (status)
                    {
                        sb.Append("Checkbox Status: Checked \r\n");
                    }
                    else
                    {
                        sb.Append("Checkbox Status: Unchecked \r\n");
                    }
                }

                sb.Append("\n");
            }

            //Write the content of the StringBuilder into a text file
            File.WriteAllText("GetAllValues.txt", sb.ToString());
            doc.Dispose();
        }
    }
}

C#/VB.NET: Extract Form Field Values from PDF

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.

An image watermark is usually a logo or sign that appears on the background of digital documents, indicating the copyright owner of the content. Watermarking your PDF document with an image can prevent your data from being reused or modified. This article demonstrates how to add an image watermark to PDF in C# and VB.NET using Spire.PDF for .NET.

Install Spire.PDF for .NET

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

  • Package Manager
PM> Install-Package Spire.PDF 

Add an Image Watermark to PDF

The following are the main steps to add an image watermark to a PDF document.

  • Create a PdfDocument object, and load a sample PDF file using PdfDocument.LoadFromFile() method.
  • Load an image file using Image.FromFile() method.
  • Loop through the pages in the document, and get the specific page through PdfDocument.Pages[] property.
  • Set the image as background/watermark image of the current page through PdfPageBase.BackgroundImage property. Set the image position and size through PdfPageBase.BackgroundRegion property.
  • Save the document to a different PDF file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using System.Drawing;

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

            //Load a sample PDF document
            document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf");

            //Load an image
            Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\logo.png");

            //Get the image width and height
            int imgWidth = image.Width;
            int imgHeight = image.Height;
         
            //Loop through the pages
            for (int i = 0; i < document.Pages.Count; i++)
            {
                //Get the page width and height
                float pageWidth = document.Pages[i].ActualSize.Width;
                float pageHeight = document.Pages[i].ActualSize.Height;

                //Set the background opacity
                document.Pages[i].BackgroudOpacity = 0.3f;

                //Set the background image of current page
                document.Pages[i].BackgroundImage = image;

                //Position the background image at the center of the page
                Rectangle rect = new Rectangle((int)(pageWidth - imgWidth) / 2, (int)(pageHeight - imgHeight) / 2, imgWidth, imgHeight);
                document.Pages[i].BackgroundRegion = rect;
            }

            //Save the document to file
            document.SaveToFile("AddImageWatermark.pdf");
            document.Close();
        }
    }
}
Imports Spire.Pdf
Imports System.Drawing
 
Namespace AddImageWatermark
    Class Program
        Shared  Sub Main(ByVal args() As String)
            'Create a PdfDocument object
            Dim document As PdfDocument =  New PdfDocument() 
 
            'Load a sample PDF document
            document.LoadFromFile("C:\Users\Administrator\Desktop\sample.pdf")
 
            'Load an image
            Dim image As Image =  Image.FromFile("C:\Users\Administrator\Desktop\logo.png") 
 
            'Get the image width and height
            Dim imgWidth As Integer =  image.Width 
            Dim imgHeight As Integer =  image.Height 
 
            'Loop through the pages
            Dim i As Integer
            For  i = 0 To  document.Pages.Count- 1  Step  i + 1
                'Get the page width and height
                Dim pageWidth As single =  document.Pages(i).ActualSize.Width 
                Dim pageHeight As single =  document.Pages(i).ActualSize.Height 
 
                'Set the background opacity
                document.Pages(i).BackgroudOpacity = 0.3f
 
                'Set the background image of current page
                document.Pages(i).BackgroundImage = image
 
                Dim rect As Rectangle = New Rectangle(CInt((pageWidth - imgWidth) / 2), CInt((pageHeight - imgHeight) / 2), imgWidth, imgHeight)
                document.Pages(i).BackgroundRegion = rect
            Next
 
            'Save the document to file
            document.SaveToFile("AddImageWatermark.pdf")
            document.Close()
        End Sub
    End Class
End Namespace

C#/VB.NET: Add Image Watermarks to PDF

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.

Spire.XLS provides a class named Worksheet, it contains a MergedCells property which makes it easy for us to obtain the merged cells in a worksheet. This property will return an array of the merged cell ranges, after that we can do any desired operations such as unmerge and apply formatting on the cells in the ranges. This article explains how to detect all merged cells in a worksheet and unmerge them once using Spire.XLS.

Here we used a template Excel file which has some merged cells:

How to detect merged cells in a worksheet

Detail steps:

Step 1: Instantiate a Workbook object and load the Excel file.

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

Step 2: Access the first worksheet by passing its sheet index.

Worksheet sheet = workbook.Worksheets[0];

Step 3: Get the merged cell ranges in the first worksheet and put them into a CellRange array.

CellRange[] range = sheet.MergedCells;

Step 4: Traverse through the array and unmerge the merged cells.

foreach (CellRange cell in range)
{
    cell.UnMerge();
}

Step 5: Save the file.

workbook.SaveToFile("Output.xlsx",ExcelVersion.Version2010);

After executing the code, we'll get the following output file:

How to detect merged cells in a worksheet

Full codes:

[C#]
using Spire.Xls;

namespace Detect_Merged_Cells
{
    class Program
    {
        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Sample.xlsx");
            Worksheet sheet = workbook.Worksheets[0];

            CellRange[] range = sheet.MergedCells;
            foreach (CellRange cell in range)
            {
                cell.UnMerge();
            }
            workbook.SaveToFile("Output.xlsx",ExcelVersion.Version2010);
        }
    }
}
[VB.NET]
Imports Spire.Xls

Namespace Detect_Merged_Cells
	Class Program
		Private Shared Sub Main(args As String())
			Dim workbook As New Workbook()
			workbook.LoadFromFile("Sample.xlsx")
			Dim sheet As Worksheet = workbook.Worksheets(0)

			Dim range As CellRange() = sheet.MergedCells
			For Each cell As CellRange In range
				cell.UnMerge()
			Next
			workbook.SaveToFile("Output.xlsx",ExcelVersion.Version2010)
		End Sub
	End Class
End Namespace

With the help of Spire.PDF, we have already demonstrated how to add text with different styles to a PDF file. By using the method canvas.drawstring offered by Spire.PDF, we can set the position, font, brush and style for the adding texts. With the PdfFontStyle, we can set the style to underline, bold, italic, regular and strikeout. Sometimes we may need to set multiple font style for the same texts within one paragraph, such as bold and italic together.

Here comes to the code snippet of how to apply two kinds of font styles together for the text on PDF in C#.

Step 1: Create a new PDF document.

PdfDocument pdf = new PdfDocument();

Step 2: Add a new page to the PDF file.

PdfPageBase page = pdf.Pages.Add(PdfPageSize.A4, new PdfMargins());

Step 3: Create the PdfFont as Helvetica with size 10f, apply two font styles for it.

PdfFont font = new PdfFont(PdfFontFamily.Helvetica,10f,PdfFontStyle.Italic | PdfFontStyle.Underline);
PdfFont font2 = new PdfFont(PdfFontFamily.Helvetica, 10f, PdfFontStyle.Bold | PdfFontStyle.Strikeout);
PdfFont font3 = new PdfFont(PdfFontFamily.Helvetica, 10f, PdfFontStyle.Bold | PdfFontStyle.Underline);

Step 4: Create a brush and set its color.

PdfSolidBrush brush = new PdfSolidBrush(Color.Blue);
PdfSolidBrush brush2 = new PdfSolidBrush(Color.Gray);
PdfSolidBrush brush3 = new PdfSolidBrush(Color.Green);

Step 5: Draw the text string at the specified location with the specified Brush and Font objects.

page.Canvas.DrawString("This sentence is Italic and underline", font, brush, new PointF(10, 10));
page.Canvas.DrawString("This sentence is Bold and strikeout", font2,brush2, new PointF(10, 40));
page.Canvas.DrawString("This sentence is Bold and underline",font3,brush3,new PointF(10, 70));

Step 6: Save the document to file.

pdf.SaveToFile("reslut.pdf");

Please check the effective screenshot as below:

How to apply multiple font styles for the text on PDF in C#

Full codes:

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


namespace MultipleFontStyles
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument pdf = new PdfDocument();
            PdfPageBase page = pdf.Pages.Add(PdfPageSize.A4, new PdfMargins());

            PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 10f, PdfFontStyle.Italic | PdfFontStyle.Underline);
            PdfFont font2 = new PdfFont(PdfFontFamily.Helvetica, 10f, PdfFontStyle.Bold | PdfFontStyle.Strikeout);
            PdfFont font3 = new PdfFont(PdfFontFamily.Helvetica, 10f, PdfFontStyle.Bold | PdfFontStyle.Underline);

            PdfSolidBrush brush = new PdfSolidBrush(Color.Blue);
            PdfSolidBrush brush2 = new PdfSolidBrush(Color.Gray);
            PdfSolidBrush brush3 = new PdfSolidBrush(Color.Green);

            page.Canvas.DrawString("This sentence is Italic and underline", font, brush, new PointF(10, 10));
            page.Canvas.DrawString("This sentence is Bold and strikeout", font2, brush2, new PointF(10, 40));
            page.Canvas.DrawString("This sentence is Bold and underline", font3, brush3, new PointF(10, 70));

            pdf.SaveToFile("reslut.pdf");
        }
    }
}

Textbox in Excel is a special kind of graphic object, which allows users to add some text in it. Moreover, textbox can be filled with solid color, gradient, pattern or a picture so that it looks more attractive. This article presents how to add a picture fill to Excel textbox and adjust the position of the picture as well.

Code Snippets:

Step 1: Create a new instance of Workbook class and get the first worksheet.

Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];

Step 2: Add a textbox shape into the worksheet.

ITextBoxShape shape = sheet.TextBoxes.AddTextBox(2, 2, 200, 300);

Step 3: Fill the textbox with a 160x160 pixels picture.

shape.Fill.CustomPicture(@"C:\Users\Administrator\Desktop\logo.png");
shape.Fill.FillType = ShapeFillType.Picture;

Step 4: Save the file.

workbook.SaveToFile("PicFill.xlsx", ExcelVersion.Version2013);

When we add a picture fill to a textbox using above code, the picture will stretch to fill the shape, like below screenshot.

Adding Picture to Excel Textbox in C#, VB.NET

If you want to prevent the image from stretching, you can adjust the size of the textbox or change the position of the picture, for example, place the image at the central position of the textbox. Following code snippet demonstrates how to center align the picture fill.

//If the height of textbox is larger than the height of original picture, set the picture into vertical center
if (textbox.Height > textbox.Fill.Picture.Height)
{            
    int difH = textbox.Height - textbox.Fill.Picture.Height;
    (textbox.Fill as XlsShapeFill).PicStretch.Top = difH * 100 / (textbox.Height * 2);
    (textbox.Fill as XlsShapeFill).PicStretch.Bottom = difH * 100 / (textbox.Height * 2);
}
//If the width of textbox is larger than the width of original picture, set the picture into horizontal center
if (textbox.Width > textbox.Fill.Picture.Width)
{
    int difW = textbox.Width - textbox.Fill.Picture.Width;
    (textbox.Fill as XlsShapeFill).PicStretch.Left = difW * 100 / (textbox.Width * 2);
    (textbox.Fill as XlsShapeFill).PicStretch.Right = difW * 100 / (textbox.Width * 2);
}

Adding Picture to Excel Textbox in C#, VB.NET

Full Code:

[C#]
using Spire.Xls;
using Spire.Xls.Core;
using Spire.Xls.Core.Spreadsheet.Shapes;
namespace AddingPicture
{
    class Program
    {

        static void Main(string[] args)
        {
            //load Excel file
            Workbook workbook = new Workbook();
            Worksheet sheet = workbook.Worksheets[0];
            ITextBoxShape textbox = sheet.TextBoxes.AddTextBox(2, 2, 200, 300);

            textbox.Fill.CustomPicture(@"C:\Users\Administrator\Desktop\logo.png");
            textbox.Fill.FillType = ShapeFillType.Picture;

            //If the height of textbox is larger than the height of original picture, set the picture into vertical center
            if (textbox.Height > textbox.Fill.Picture.Height)
            {
                int difH = textbox.Height - textbox.Fill.Picture.Height;
                (textbox.Fill as XlsShapeFill).PicStretch.Top = difH * 100 / (textbox.Height * 2);
                (textbox.Fill as XlsShapeFill).PicStretch.Bottom = difH * 100 / (textbox.Height * 2);
            }
            //If the width of textbox is larger than the width of original picture, set the picture into horizontal center
            if (textbox.Width > textbox.Fill.Picture.Width)
            {
                int difW = textbox.Width - textbox.Fill.Picture.Width;
                (textbox.Fill as XlsShapeFill).PicStretch.Left = difW * 100 / (textbox.Width * 2);
                (textbox.Fill as XlsShapeFill).PicStretch.Right = difW * 100 / (textbox.Width * 2);
            }

            workbook.SaveToFile("PicFill.xlsx", ExcelVersion.Version2013);
        }
    }
}
[VB.NET]
Imports Spire.Xls
Imports Spire.Xls.Core
Imports Spire.Xls.Core.Spreadsheet.Shapes
Namespace AddingPicture
	Class Program

		Private Shared Sub Main(args As String())
			'load Excel file
			Dim workbook As New Workbook()
			Dim sheet As Worksheet = workbook.Worksheets(0)
			Dim textbox As ITextBoxShape = sheet.TextBoxes.AddTextBox(2, 2, 200, 300)

			textbox.Fill.CustomPicture("C:\Users\Administrator\Desktop\logo.png")
			textbox.Fill.FillType = ShapeFillType.Picture

			'If the height of textbox is larger than the height of original picture, set the picture into vertical center
			If textbox.Height > textbox.Fill.Picture.Height Then
				Dim difH As Integer = textbox.Height - textbox.Fill.Picture.Height
				TryCast(textbox.Fill, XlsShapeFill).PicStretch.Top = difH * 100 / (textbox.Height * 2)
				TryCast(textbox.Fill, XlsShapeFill).PicStretch.Bottom = difH * 100 / (textbox.Height * 2)
			End If
			'If the width of textbox is larger than the width of original picture, set the picture into horizontal center
			If textbox.Width > textbox.Fill.Picture.Width Then
				Dim difW As Integer = textbox.Width - textbox.Fill.Picture.Width
				TryCast(textbox.Fill, XlsShapeFill).PicStretch.Left = difW * 100 / (textbox.Width * 2)
				TryCast(textbox.Fill, XlsShapeFill).PicStretch.Right = difW * 100 / (textbox.Width * 2)
			End If

			workbook.SaveToFile("PicFill.xlsx", ExcelVersion.Version2013)
		End Sub
	End Class
End Namespace

How to set text direction in Word

2016-08-24 08:23:07 Written by Koohji

We can use the TextDirection enumeration in Spire.Doc.Documents namespace to set the direction of text in a word document. This enumeration contains six members: LeftToRight, TopToBottom, LeftToRightRotated, TopToBottomRotated, RightToLeft and RightToLeftRotated. The following example shows how to set text direction for all text and a part of text in a section.

Detail steps:

Step 1: Initialize a new instance of Document class and load the word document.

Document document = new Document();
document.LoadFromFile("Word.docx");

Step 2: Set text direction for all text in a section.

//Get the first section and set its text direction
Section section = document.Sections[0];
section.TextDirection = TextDirection.RightToLeftRotated;

To set text direction for a part of text, we can put the text in a table and then set text direction, as shown in the following step:

Step 3: Add a new section to the document and a table to the section, get the target table cell and set text direction for it, afterwards append text to the cell.

//Add a new section to the document
Section sec = document.AddSection();
//Add a table to the new section
Table table = sec.AddTable();
//Add one row and one column to the table
table.ResetCells(1, 1);
//Get the table cell
TableCell cell = table.Rows[0].Cells[0];
table.Rows[0].Height = 150;
table.Rows[0].Cells[0].Width = 10;
//Set text direction for the cell and append some text
cell.CellFormat.TextDirection = TextDirection.RightToLeftRotated;
cell.AddParagraph().AppendText("Hello,world: vertical style");

Add a new paragraph to check if above settings will affect the text direction of other text in this section:

sec.AddParagraph().AppendText("New Paragraph");

Step 4: Save the document.

document.SaveToFile("result.docx", FileFormat.Docx);

Result:

Set text direction for all text in a section:

How to set text direction in Word

Set text direction for a part of text:

How to set text direction in Word

Full codes:

using Spire.Doc;
using Spire.Doc.Documents;

namespace Set_text_direction_in_Word
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();
            document.LoadFromFile("Word.docx");
            //Set text direction for all text in a section
            Section section = document.Sections[0];
            section.TextDirection = TextDirection.RightToLeftRotated;

            // Set text direction for a part of text
            Section sec = document.AddSection();
            Table table = sec.AddTable();
            table.ResetCells(1, 1);
            TableCell cell = table.Rows[0].Cells[0];
            table.Rows[0].Height = 150;
            table.Rows[0].Cells[0].Width = 10;
            cell.CellFormat.TextDirection = TextDirection.RightToLeftRotated;
            cell.AddParagraph().AppendText("Hello,world: vertical style");

            sec.AddParagraph().AppendText("New Paragraph");

            //Save the document
            document.SaveToFile("result.docx", FileFormat.Docx);
        }
    }
}
page 35