C#: Replace Text in a PDF Document

2024-03-20 09:49:00 Written by Koohji

People often need to replace text in a PDF document for a variety of reasons. It could be to correct errors or typos, update outdated information, customize the content for a specific audience or purpose, or comply with legal or regulatory requirements. By replacing text in a PDF, individuals can ensure accuracy, maintain document integrity, and enhance the overall quality and relevance of the information presented.

In this article, you will learn how to replace text in a PDF document in C# by using the Spire.PDF for .NET library.

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 DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Replace Text in a Specific PDF Page in C#

Spire.PDF for .NET offers the PdfTextReplacer.ReplaceAllText() method, allowing users to replace all occurrences of target text in a page with new text. The following are the steps to replace text in a specific page using C#.

  • Create a PdfDocument object.
  • Load a PDF file for a specified path.
  • Get a specific page from the document.
  • Create a PdfTextReplaceOptions object, and specify the replace options using ReplaceType property of the object.
  • Create a PdfTextReplacer object, and apply the replace options using Options property of it.
  • Replace all occurrences of the target text in the page with new text using PdfTextReplacer.ReplaceAllText() method.
  • Save the document to a different PDF file.
  • C#
using Spire.Pdf;
using Spire.Pdf.Texts;

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

            // Load a PDF file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf");

            // Create a PdfTextReplaceOptions object
            PdfTextReplaceOptions textReplaceOptions = new PdfTextReplaceOptions();

            // Specify the options for text replacement
            textReplaceOptions.ReplaceType = PdfTextReplaceOptions.ReplaceActionType.IgnoreCase;
            textReplaceOptions.ReplaceType = PdfTextReplaceOptions.ReplaceActionType.WholeWord;
            textReplaceOptions.ReplaceType = PdfTextReplaceOptions.ReplaceActionType.AutofitWidth;

            // Get a specific page
            PdfPageBase page = doc.Pages[0];

            // Create a PdfTextReplacer object based on the page
            PdfTextReplacer textReplacer = new PdfTextReplacer(page);

            // Set the replace options
            textReplacer.Options = textReplaceOptions;

            // Replace all occurrences of target text with new text
            textReplacer.ReplaceAllText(".NET Framework", "New Content");

            // Save the document to a different PDF file
            doc.SaveToFile("ReplaceTextInPage.pdf");

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

C#: Replace Text in a PDF Document

Replace Text in an Entire PDF Document in C#

In order to replace all occurrences of target text in the entire document with new text, you need to iterate through pages in the document and replace text on each page using the PdfTextReplacer.ReplaceAllText() method.

The following are the steps to replace text in an entire PDF document using C#.

  • Create a PdfDocument object.
  • Load a PDF file for a specified path.
  • Create a PdfTextReplaceOptions object, and specify the replace options using ReplaceType property of the object.
  • Iterate through the pages in the document.
    • Create a PdfTextReplacer object based on a specified page, and apply the replace options using Options property of it.
    • Replace all occurrences of the target text in the page with new text using PdfTextReplacer.ReplaceAllText() method.
  • Save the document to a different PDF file.
  • C#
using Spire.Pdf;
using Spire.Pdf.Texts;

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

            // Load a PDF file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf");

            // Create a PdfTextReplaceOptions object
            PdfTextReplaceOptions textReplaceOptions = new PdfTextReplaceOptions();

            // Specify the options for text replacement
            textReplaceOptions.ReplaceType = PdfTextReplaceOptions.ReplaceActionType.IgnoreCase;
            textReplaceOptions.ReplaceType = PdfTextReplaceOptions.ReplaceActionType.WholeWord;
            textReplaceOptions.ReplaceType = PdfTextReplaceOptions.ReplaceActionType.AutofitWidth;

            for (int i = 0; i < doc.Pages.Count; i++) {

                // Get a specific page
                PdfPageBase page = doc.Pages[i];

                // Create a PdfTextReplacer object based on the page
                PdfTextReplacer textReplacer = new PdfTextReplacer(page);

                // Set the replace options
                textReplacer.Options = textReplaceOptions;

                // Replace all occurrences of target text with new text
                textReplacer.ReplaceAllText(".NET Framework", "New Content");
            }
            

            // Save the document to a different PDF file
            doc.SaveToFile("ReplaceTextInDocument.pdf");

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

Replace the First Occurrence of the Target Text in C#

Instead of replacing all text on a page, you can only replace the first occurrence of the target text by utilizing the ReplaceText() method of the PdfTextReplacer class.

The following are the steps to replace the first occurrence of the target text using C#.

  • Create a PdfDocument object.
  • Load a PDF file for a specified path.
  • Get a specific page from the document.
  • Create a PdfTextReplaceOptions object, and specify the replace options using ReplaceType property of the object.
  • Create a PdfTextReplacer object, and apply the replace options using Options property of it.
  • Replace the first occurrence of the target text in the page with new text using PdfTextReplacer.ReplaceText() method.
  • Save the document to a different PDF file.
  • C#
using Spire.Pdf;
using Spire.Pdf.Texts;

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

            // Load a PDF file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf");

            // Create a PdfTextReplaceOptions object
            PdfTextReplaceOptions textReplaceOptions = new PdfTextReplaceOptions();

            // Specify the options for text replacement
            textReplaceOptions.ReplaceType = PdfTextReplaceOptions.ReplaceActionType.IgnoreCase;
            textReplaceOptions.ReplaceType = PdfTextReplaceOptions.ReplaceActionType.WholeWord;
            textReplaceOptions.ReplaceType = PdfTextReplaceOptions.ReplaceActionType.AutofitWidth;

            // Get a specific page
            PdfPageBase page = doc.Pages[1];

            // Create a PdfTextReplacer object based on the page
            PdfTextReplacer textReplacer = new PdfTextReplacer(page);

            // Set the replace options
            textReplacer.Options = textReplaceOptions;

            // Replace the first occurrence of target text with new text
            textReplacer.ReplaceText(".NET Framework", "New Content");

            // Save the document to a different PDF file
            doc.SaveToFile("ReplaceFirstOccurance.pdf");

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

C#: Replace Text in a PDF Document

Replace Text Based on a Regular Expression in C#

Regular expressions are powerful and versatile patterns used for matching and manipulating text. With Spire.PDF, you utilize regular expressions to search for specific text patterns in a PDF and replace them with new strings.

The steps to replace text in PDF based on a regular expression are as follows.

  • Create a PdfDocument object.
  • Load a PDF file for a specified path.
  • Get a specific page from the document.
  • Create a PdfTextReplaceOptions object.
  • Specify the replace type as Regex using PdfTextReplaceOptions.ReplaceType property.
  • Create a PdfTextReplacer object, and apply the replace options using Options property of it.
  • Find and replace the text that matches a specified regular expression using PdfTextReplacer.ReplaceAllText() method.
  • Save the document to a different PDF file.
  • C#
using Spire.Pdf;
using Spire.Pdf.Texts;

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

            // Load a PDF file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf");

            // Create a PdfTextReplaceOptions object
            PdfTextReplaceOptions textReplaceOptions = new PdfTextReplaceOptions();

            // Set the replace type as Regex
            textReplaceOptions.ReplaceType = PdfTextReplaceOptions.ReplaceActionType.Regex;

            // Get a specific page
            PdfPageBase page = doc.Pages[1];

            // Create a PdfTextReplacer object based on the page
            PdfTextReplacer textReplacer = new PdfTextReplacer(page);

            // Set the replace options
            textReplacer.Options = textReplaceOptions;

            // Specify the regular expression
            string regularExpression = @"\bC\w*?R\b";

            // Replace all occurrences that match the regular expression with new text
            textReplacer.ReplaceAllText(regularExpression, "NEW");

            // Save the document to a different PDF file
            doc.SaveToFile("ReplaceWithRegularExpression.pdf");

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

C#: Replace Text in a PDF Document

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.

This article demonstrates how to add tooltip to the text on an existing PDF document in C#. Spire.PDF for .NET supports to create tooltips by adding invisible button over the searched text from the PDF file.

Step 1: Load the sample document file.

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

Step 2: Searched the text “Add tooltip to PDF” from the first page of the sample document and get the position of it.

PdfPageBase page = doc.Pages[0];
PdfTextFinder finder = new PdfTextFinder(page);
finder.Options.Parameter =TextFindParameter.WholeWord;
List⁢PdfTextFragment> result = finder.Find("Add tooltip to PDF");
RectangleF rec = result[0].Bounds[0];

Step 3: Create invisible button on text position

PdfButtonField field1 = new PdfButtonField(page, "field1");
field1.Bounds = rec;

field1.ToolTip = "E-iceblue Co. Ltd., a vendor of .NET, Java and WPF development components";
field1.BorderWidth = 0;
field1.BackColor = Color.Transparent;
field1.ForeColor = Color.Transparent;
field1.LayoutMode = PdfButtonLayoutMode.IconOnly;
field1.IconLayout.IsFitBounds = true;

Step 4: Set the content and format for the tooltip field.

field1.ToolTip = "E-iceblue Co. Ltd., a vendor of .NET, Java and WPF development components";
field1.BorderWidth = 0;
field1.BackColor = Color.Transparent;
field1.ForeColor = Color.Transparent;
field1.LayoutMode = PdfButtonLayoutMode.IconOnly;
field1.IconLayout.IsFitBounds = true;

Step 5: Save the document to file.

doc.SaveToFile("Addtooltip.pdf", FileFormat.PDF);

Effective screenshot after adding the tooltip to PDF:

C# add tooltip to the searched text on PDF

using Spire.Pdf;
using Spire.Pdf.Fields;
using Spire.Pdf.Texts;
using System.Collections.Generic;
using System.Drawing;

namespace TooltipPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile("Sample.pdf");

            PdfPageBase page = doc.Pages[0];

            PdfTextFinder finder = new PdfTextFinder(page);
            finder.Options.Parameter =TextFindParameter.WholeWord;

            // Find the occurrences of the specified text
            List⁢PdfTextFragment> result = finder.Find("Add tooltip to PDF");
            RectangleF rec = result[0].Bounds[0];

            //Create invisible button on text position
            PdfButtonField field1 = new PdfButtonField(page, "field1");
            field1.Bounds = rec;

            field1.ToolTip = "E-iceblue Co. Ltd., a vendor of .NET, Java and WPF development components";
            field1.BorderWidth = 0;
            field1.BackColor = Color.Transparent;
            field1.ForeColor = Color.Transparent;
            field1.LayoutMode = PdfButtonLayoutMode.IconOnly;
            field1.IconLayout.IsFitBounds = true;

            doc.SaveToFile("Addtooltip.pdf", FileFormat.PDF);

        }
    }
}

Starting from version 9.9.5, Spire.XLS supports applying style to an entire excel worksheet. This article will show you how to apply a style to an entire excel worksheet using Spire.XLS.

Detail steps:

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

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

Step 2: Get the first worksheet.

Worksheet sheet = workbook.Worksheets[0];

Step 3: Create a cell style, specify the cell background color, font color and font size.

CellStyle style = workbook.Styles.Add("newStyle");
style.Color = Color.DarkGray;
style.Font.Color = Color.White;
style.Font.Size = 15;

Step 4: Apply the style to the first worksheet.

sheet.ApplyStyle(style);

Step 5: Save the resultant file.

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

Output:

Apply a Style to an Entire Excel Worksheet in C#

Full code:

using System.Drawing;
using Spire.Xls;

namespace StyleEntireWorksheet
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance and load the excel file
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Input.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Create a cell style
            CellStyle style = workbook.Styles.Add("newStyle");
            style.Color = Color.DarkGray;
            style.Font.Color = Color.White;
            style.Font.Size = 15;

            //Apply the style to the first worksheet
            sheet.ApplyStyle(style);

            //Save the resultant file
            workbook.SaveToFile("Output.xlsx", ExcelVersion.Version2013);
        }
    }
}

With the help of Spire.Presentation for .NET, we could set 3D effect to the shapes and text in the PowerPoint document to make it attractive. We have already demonstrated how to use Spire.Presentation to set 3D format for shapes. In this article, I will introduce how to create three dimensional effects text in PowerPoint in C#.

using Spire.Presentation;
using Spire.Presentation.Drawing;
using System.Drawing;

namespace 3DEffectForText
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a new presentation object
            Presentation presentation = new Presentation();

            //Get the first slide
            ISlide slide = presentation.Slides[0];

            //Append a new shape to slide and set the line color and fill type
            IAutoShape shape = slide.Shapes.AppendShape(ShapeType.Rectangle, new RectangleF(30, 40, 600, 200));
            shape.ShapeStyle.LineColor.Color = Color.White;
            shape.Fill.FillType = Spire.Presentation.Drawing.FillFormatType.None;

            //Add text to the shape
            shape.AppendTextFrame("This demo shows how to add 3D effect text to Presentation slide");

            //set the color of text in shape
            TextRange textRange = shape.TextFrame.TextRange;
            textRange.Fill.FillType = Spire.Presentation.Drawing.FillFormatType.Solid;
            textRange.Fill.SolidColor.Color = Color.Green;

            //set the Font of text in shape
            textRange.FontHeight = 30;
            textRange.LatinFont = new TextFont("Gulim");


            //Set 3D effect for text
            shape.TextFrame.TextThreeD.ShapeThreeD.PresetMaterial = PresetMaterialType.Matte;
            shape.TextFrame.TextThreeD.LightRig.PresetType = PresetLightRigType.Sunrise;
            shape.TextFrame.TextThreeD.ShapeThreeD.TopBevel.PresetType = BevelPresetType.Circle;
            shape.TextFrame.TextThreeD.ShapeThreeD.ContourColor.Color = Color.Green;
            shape.TextFrame.TextThreeD.ShapeThreeD.ContourWidth = 3;                    
          
            //Save the document to file.
            presentation.SaveToFile("3DEffectForText_result.pptx", FileFormat.Pptx2010);                                                        
        }
    }
}

Effective screenshot for 3-D effect text on Presentation slides:

Set 3D effect for the text in PowerPoint in C#

Add arrow line to Excel worksheet in C#

2019-08-27 07:22:09 Written by Koohji

With Spire.XLS for .NET, developers can easily use C# to add shapes to Excel worksheet. From version 9.8.11, Spire.XLS supports to add arrow lines to Excel worksheet. The following sample will show you how to insert arrow line, double Arrow, Elbow Arrow, Elbow Double-Arrow, Curved Arrow and Curved Double-Arrow to Excel worksheet in C#.

using Spire.Xls;
using System.Drawing;

namespace Add_Lines_to_Excel
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initiate a Workbook object and get the first worksheet
            Workbook workbook = new Workbook();
            Worksheet sheet = workbook.Worksheets[0];

            //Add a Double Arrow and fill the line with solid color
            var line = sheet.TypedLines.AddLine();
            line.Top = 10;
            line.Left = 20;
            line.Width = 100;
            line.Height = 0;
            line.Color = Color.Blue;
            line.BeginArrowHeadStyle = ShapeArrowStyleType.LineArrow;
            line.EndArrowHeadStyle = ShapeArrowStyleType.LineArrow;
            
            //Add an Arrow and fill the line with solid color
            var line_1 = sheet.TypedLines.AddLine();
            line_1.Top = 50;
            line_1.Left = 30;
            line_1.Width = 100;
            line_1.Height = 100;
            line_1.Color = Color.Red;
            line_1.BeginArrowHeadStyle = ShapeArrowStyleType.LineNoArrow;
            line_1.EndArrowHeadStyle = ShapeArrowStyleType.LineArrow;

            //Add an Elbow Arrow Connector
            Spire.Xls.Core.Spreadsheet.Shapes.XlsLineShape line3 = sheet.TypedLines.AddLine() as Spire.Xls.Core.Spreadsheet.Shapes.XlsLineShape;
            line3.LineShapeType = LineShapeType.ElbowLine;
            line3.Width = 30;
            line3.Height = 50;
            line3.EndArrowHeadStyle = ShapeArrowStyleType.LineArrow;
            line3.Top = 100;
            line3.Left = 50;
            
            //Add an Elbow Double-Arrow Connector
            Spire.Xls.Core.Spreadsheet.Shapes.XlsLineShape line2 = sheet.TypedLines.AddLine() as Spire.Xls.Core.Spreadsheet.Shapes.XlsLineShape;
            line2.LineShapeType = LineShapeType.ElbowLine;
            line2.Width = 50;
            line2.Height = 50;
            line2.EndArrowHeadStyle = ShapeArrowStyleType.LineArrow;
            line2.BeginArrowHeadStyle = ShapeArrowStyleType.LineArrow;
            line2.Left = 120;
            line2.Top = 100;

            //Add a Curved Arrow Connector 
            line3 = sheet.TypedLines.AddLine() as Spire.Xls.Core.Spreadsheet.Shapes.XlsLineShape;
            line3.LineShapeType = LineShapeType.CurveLine;
            line3.Width = 30;
            line3.Height = 50;
            line3.EndArrowHeadStyle = ShapeArrowStyleType.LineArrowOpen;
            line3.Top = 100;
            line3.Left = 200;

            //Add a Curved Double-Arrow Connector
            line2 = sheet.TypedLines.AddLine() as Spire.Xls.Core.Spreadsheet.Shapes.XlsLineShape;
            line2.LineShapeType = LineShapeType.CurveLine;
            line2.Width = 30;
            line2.Height = 50;
            line2.EndArrowHeadStyle = ShapeArrowStyleType.LineArrowOpen;
            line2.BeginArrowHeadStyle = ShapeArrowStyleType.LineArrowOpen;
            line2.Left = 250;
            line2.Top = 100;

            //Save the file
            workbook.SaveToFile("AddLines.xlsx", ExcelVersion.Version2013);

        }
    }
}

Add arrow line to Excel worksheet in C#

C#: Create Pivot Charts in Excel

2024-10-17 01:05:00 Written by Koohji

A Pivot Chart is a graphical representation of a Pivot Table. While a Pivot Table summarizes data and allows users to manipulate it for analysis, a Pivot Chart provides a visual representation of that summarized data. Pivot Charts can be easily updated as the data in the Pivot Table changes, making them an essential tool for reporting and analysis. In this article, we will demonstrate how to create pivot charts in Excel in C# using Spire.XLS for .NET.

Install Spire.XLS for .NET

To begin with, you need to add the DLL files included in the Spire.XLS 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.XLS

Create Pivot Charts in Excel in C#

With Spire.XLS for .NET, creating a pivot chart from an existing pivot table in Excel is straightforward using the Worksheet.Charts.Add(ExcelChartType pivotChartType, IPivotTable pivotTable) method. The detailed steps are as follows.

  • Create an object of the Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet in the Excel file using Workbook.Worksheets[index] property.
  • Get a specific pivot table in the worksheet using Worksheet.PivotTables[index] property.
  • Add a pivot chart based on the pivot table to the worksheet using Worksheet.Charts.Add(ExcelChartType pivotChartType, IPivotTable pivotTable) method.
  • Set the position and title of the pivot chart.
  • Save the resulting file using Workbook.SaveToFile() method.
  • C#
using Spire.Xls;
using Spire.Xls.Core;

namespace CreatePivotChart
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();

            // Load an Excel file
            workbook.LoadFromFile("PivotTable.xlsx");

            // Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            // Get the first pivot table in the worksheet
            IPivotTable pivotTable = sheet.PivotTables[0];

            // Create a clustered column chart based on the pivot table
            Chart pivotChart = sheet.Charts.Add(ExcelChartType.ColumnClustered, pivotTable);

            // Set chart position
            pivotChart.TopRow = 1;
            pivotChart.LeftColumn = 11;
            pivotChart.RightColumn = 20;
            pivotChart.BottomRow = 15;

            // Set chart title to null
            pivotChart.ChartTitle = "";

            // Save the resulting file
            workbook.SaveToFile("CreatePivotChart.xlsx", ExcelVersion.Version2013);
            workbook.Dispose();
        }
    }
}

C#: Create Pivot Charts in Excel

Show or Hide Field Buttons in Pivot Charts in Excel in C#

Using Spire.XLS for .NET, you can easily show or hide different types of field buttons to customize the appearance of your charts. The field buttons you can control include:

  • Entire Field Buttons
  • Report Filter Field Buttons
  • Legend Field Buttons
  • Axis Field Buttons
  • Value Field Buttons

The detailed steps are as follows:

  • Create an object of the Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet in the Excel file using Workbook.Worksheets[index] property.
  • Get a specific pivot table in the worksheet using Worksheet.PivotTables[index] property.
  • Add a pivot chart based on the pivot table to the worksheet using Worksheet.Charts.Add(ExcelChartType pivotChartType, IPivotTable pivotTable) method.
  • Set the position and title of the pivot chart.
  • Hide specific field buttons in the pivot chart, such as the axis field buttons and the value field buttons, using Chart.DisplayAxisFieldButtons and Chart.DisplayValueFieldButtons properties.
  • Save the resulting file using Workbook.SaveToFile() method.
  • C#
using Spire.Xls;
using Spire.Xls.Core;

namespace ShowOrHideFieldButtons
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();

            // Load an Excel file
            workbook.LoadFromFile("CreatePivotChart.xlsx");

            // Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            // Get the first pivot table in the worksheet
            IPivotTable pivotTable = sheet.PivotTables[0];

            // Create a clustered column chart based on the pivot table
            Chart pivotChart = sheet.Charts.Add(ExcelChartType.ColumnClustered, pivotTable);

            // Set chart position
            pivotChart.TopRow = 1;
            pivotChart.LeftColumn = 11;
            pivotChart.RightColumn = 20;
            pivotChart.BottomRow = 15;

            // Set chart title to null
            pivotChart.ChartTitle = "";

            // Hide specific field buttons
            pivotChart.DisplayAxisFieldButtons = false;
            pivotChart.DisplayValueFieldButtons = false;
            // pivotChart.DisplayLegendFieldButtons = false;
            // pivotChart.ShowReportFilterFieldButtons = false;
            // pivotChart.DisplayEntireFieldButtons = false;

            // Save the resulting file
            workbook.SaveToFile("HideFieldButtons.xlsx", ExcelVersion.Version2013);
            workbook.Dispose();
        }
    }
}

C#: Create Pivot Charts in Excel

Format Pivot Chart Series in Excel in C#

When creating a pivot chart in Excel from a pivot table using Spire.XLS for .NET, it's important to note that the chart series do not get generated automatically. Instead, you must manually add the series and format them according to your preferences. The detailed steps are as follows:

  • Create an object of the Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet in the Excel file using Workbook.Worksheets[index] property.
  • Get a specific pivot table in the worksheet using Worksheet.PivotTables[index] property.
  • Add a pivot chart based on the pivot table to the worksheet using Worksheet.Charts.Add(ExcelChartType pivotChartType, IPivotTable pivotTable) method.
  • Set the position and title of the pivot chart.
  • Add series to the chart using Chart.Series.Add() method and then apply the desired formatting to the series.
  • Save the resulting file using Workbook.SaveToFile() method.
  • C#
using Spire.Xls;
using Spire.Xls.Charts;
using Spire.Xls.Core;

namespace FormatChartSeries
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();

            // Load an Excel file
            workbook.LoadFromFile("CreatePivotChart.xlsx");

            // Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            // Get the first pivot table in the worksheet
            IPivotTable pivotTable = sheet.PivotTables[0];

            // Create a clustered column chart based on the pivot table
            Chart pivotChart = sheet.Charts.Add(ExcelChartType.ColumnClustered, pivotTable);

            // Set chart position
            pivotChart.TopRow = 1;
            pivotChart.LeftColumn = 11;
            pivotChart.RightColumn = 20;
            pivotChart.BottomRow = 15;

            // Set chart title to null
            pivotChart.ChartTitle = "";

            // Add chart series
            ChartSerie series = pivotChart.Series.Add(ExcelChartType.ColumnClustered);

            // Set bar width
            series.GetCommonSerieFormat().GapWidth = 10;

            // Set overlap (uncomment the line below to enable)
            // series.GetCommonSerieFormat().Overlap = 100;

            // Save the resulting file
            workbook.SaveToFile("FormatChartSeries.xlsx", ExcelVersion.Version2013);
            workbook.Dispose();
        }
    }
}

C#: Create Pivot Charts in Excel

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.

With the help of Spire.Presentation, we can add shapes to the presentation slides easily. This example shows you how to add a round corner rectangle to presentation slide and set the radius of the round corner rectangle in C#.

using Spire.Presentation;
using Spire.Presentation.Drawing;
using System.Drawing;

namespace RoundRectangle
{
    class Program
    {
        static void Main(string[] args)
        {          
            Presentation presentation = new Presentation();

            //Insert a round corner rectangle and set its radious
            presentation.Slides[0].Shapes.InsertRoundRectangle(0, 60, 90, 100, 200, 36);

            //Append a round corner rectangle and set its radious
            IAutoShape shape = presentation.Slides[0].Shapes.AppendRoundRectangle(260, 90, 100, 200, 80);
            //Set the color and fill style of shape
            shape.Fill.FillType = FillFormatType.Solid;
            shape.Fill.SolidColor.Color = Color.SeaGreen;
            shape.ShapeStyle.LineColor.Color = Color.White;
            //Rotate the shape to 90 degree
            shape.Rotation = 90;  
            
            //Save the document to file    
            presentation.SaveToFile("Result.pptx", FileFormat.Pptx2013);
                                                                              
        }
    }
}

Effective screenshot of the round corner rectangle on presentation slide:

Add a round corner rectangle to presentation slide in C#

When there are overlapping shapes/images in your presentation slide, you can control which shape is under or above which shape by bring a shape forward or to front, or sending a shape backward or to back. The following example shows you how to bring a shape forward using Spire.Presentation with C# and VB.NET.

Code Snippets

[C#]
//load the sample PowerPoint file
Presentation presentation = new Presentation();
presentation.LoadFromFile(@"C:\Users\Administrator\Desktop\input.pptx");

//get the specified shape
IShape shape = presentation.Slides[0].Shapes[0];

//bring the shape forward through SetShapeArrange method
shape.SetShapeArrange(ShapeArrange.BringForward);

//save to file
presentation.SaveToFile("output.pptx", FileFormat.Pptx2013);
[VB.NET]
'load the sample PowerPoint file
Dim presentation As Presentation =  New Presentation() 
presentation.LoadFromFile("C:\Users\Administrator\Desktop\input.pptx")
 
'get the specified shape
Dim shape As IShape =  presentation.Slides(0).Shapes(0) 
 
'bring the shape forward through SetShapeArrange method
shape.SetShapeArrange(ShapeArrange.BringForward)
 
'save to file
presentation.SaveToFile("output.pptx", FileFormat.Pptx2013)

Output

Arrange Shapes in PowerPoint in C#, VB.NET

Math equations in Word documents are essential tools for expressing mathematical concepts and relationships. Whether you are writing an academic paper, a scientific report, or any other document involving mathematical content, incorporating math equations can greatly enhance your ability to convey complex mathematical concepts and improve the visual appeal and professionalism of your document. In this article, we will explain how to insert math equations into Word documents in C# and VB.NET 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

Insert Math Equations into a Word Document in C# and VB.NET

Spire.Doc for .NET allows generating math equations from LaTeX code and MathML code using OfficeMath.FromLatexMathCode(string latexMathCode) and OfficeMath.FromMathMLCode(string mathMLCode) methods. The detailed steps are as follows:

  • Create two string arrays from LaTeX code and MathML code.
  • Create a Document instance and add a section to it using Document.AddSection() method.
  • Iterate through each LaTeX code in the string array.
  • Create a math equation from the LaTeX code using OfficeMath.FromLatexMathCode(string latexMathCode) method.
  • Add a paragraph to the section, then add the math equation to the paragraph using Paragraph.Items.Add() method.
  • Iterate through each MathML code in the string array.
  • Create a math equation from the MathML code using OfficeMath.FromMathMLCode(string mathMLCode) method.
  • Add a paragraph to the section, then add the math equation to the paragraph using Paragraph.Items.Add() method.
  • Save the result document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields.OMath;

namespace AddMathEquations
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Create a string array from LaTeX code
            string[] latexMathCode = {
                "x^{2}+\\sqrt{x^{2}+1}=2",
                "\\cos (2\\theta) = \\cos^2 \\theta - \\sin^2 \\theta",
                "k_{n+1} = n^2 + k_n^2 - k_{n-1}",
                "\\frac {\\frac {1}{x}+ \\frac {1}{y}}{y-z}",
                "\\int_0^ \\infty \\mathrm {e}^{-x} \\, \\mathrm {d}x",
                "\\forall x \\in X, \\quad \\exists y \\leq \\epsilon",
                "\\alpha, \\beta, \\gamma, \\Gamma, \\pi, \\Pi, \\phi, \\varphi, \\mu, \\Phi",
                "A_{m,n} = \\begin{pmatrix} a_{1,1} & a_{1,2} & \\cdots & a_{1,n} \\\\ a_{2,1} & a_{2,2} & \\cdots & a_{2,n} \\\\ \\vdots  & \\vdots  & \\ddots & \\vdots  \\\\ a_{m,1} & a_{m,2} & \\cdots & a_{m,n} \\end{pmatrix}",
            };

            //Create a string array from MathML code
            string[] mathMLCode = {
                "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mi>a</mi><mo>≠</mo><mn>0</mn></math>",
                "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mi>a</mi><msup><mi>x</mi><mn>2</mn></msup><mo>+</mo><mi>b</mi><mi>x</mi><mo>+</mo><mi>c</mi><mo>=</mo><mn>0</mn></math>",
                "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mi>x</mi><mo>=</mo><mrow><mfrac><mrow><mo>−</mo><mi>b</mi><mo>±</mo><msqrt><msup><mi>b</mi><mn>2</mn></msup><mo>−</mo><mn>4</mn><mi>a</mi><mi>c</mi></msqrt></mrow><mrow><mn>2</mn><mi>a</mi></mrow></mfrac></mrow></math>",
            };

            //Create a Document instance
            Document doc = new Document();

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

            //Add a paragraph to the section
            Paragraph textPara = section.AddParagraph();
            textPara.AppendText("Creating Equations from LaTeX Code");
            textPara.ApplyStyle(BuiltinStyle.Heading1);
            textPara.Format.HorizontalAlignment = HorizontalAlignment.Center;

            //Iterate through each LaTeX code in the string array
            for (int i = 0; i < latexMathCode.Length; i++)
            {
                //Create a math equation from the LaTeX code
                OfficeMath officeMath = new OfficeMath(doc);
                officeMath.FromLatexMathCode(latexMathCode[i]);
                //Add the math equation to the section
                Paragraph paragraph = section.AddParagraph();                                
                paragraph.Items.Add(officeMath);
                section.AddParagraph();
            }

            section.AddParagraph();

            //Add a paragraph to the section
            textPara = section.AddParagraph();
            textPara.AppendText("Creating Equations from MathML Code");
            textPara.ApplyStyle(BuiltinStyle.Heading1);
            textPara.Format.HorizontalAlignment = HorizontalAlignment.Center;

            //Iterate through each MathML code in the string array
            for (int j = 0; j < mathMLCode.Length; j++)
            {
                //Create a math equation from the MathML code
                OfficeMath officeMath = new OfficeMath(doc);
                officeMath.FromMathMLCode(mathMLCode[j]);
                //Add the math equation to the section
                Paragraph paragraph = section.AddParagraph();
                paragraph.Items.Add(officeMath);               
                section.AddParagraph();
            }

            //Save the result document    
            doc.SaveToFile("AddMathEquations.docx", FileFormat.Docx2013);
            doc.Dispose();
        }
    }
}

C#/VB.NET: Insert Math Equations into 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.

C#/VB.NET: Digitally Sign Word Documents

2022-07-05 07:35:00 Written by Koohji

A signature confirms that the digital document originated from the signer and has not been tampered with during transit. The use of digital signatures eliminates the need for sending paper documents, and reduces the number of the documents that need to be printed, mailed, and stored, saving you time and money. In this article, you will learn how to digitally sign a Word document in C# and VB.NET 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

Add a Digital Signature to Word in C#, VB.NET

The steps are as follows.

  • Create a Document object.
  • Load a Word document using Document.LoadFromFile() method.
  • Specify the path and the password of a .pfx certificate.
  • Digitally sign the document while saving the document using Document.SaveToFile(string fileName, FileFormat fileFormat, string certificatePath, string securePassword) method. Here are some other methods that you can use to digitally sign a Word document.
    • public void SaveToFile(string fileName, FileFormat fileFormat, byte[] certificateData, string securePassword);
    • public void SaveToStream(Stream stream, FileFormat fileFormat, byte[] certificateData, string securePassword);
    • public void SaveToStream(Stream stream, FileFormat fileFormat, string certificatePath, string securePassword);
    • public static byte[] Document.Sign(Stream sourceStream, byte[] certificateData, string securePassword);
    • public static byte[] Document.Sign(Stream sourceStream, string certificatePath, string securePassword);
  • C#
  • VB.NET
using Spire.Doc;

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

            //Load a Word file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");

            //Specify the certificate path
            string certificatePath = "C:\\Users\\Administrator\\Desktop\\gary.pfx";

            //Specify the password of the certificate
            string password = "e-iceblue";

            //Digitally sign the document while saving it to a .docx file
            doc.SaveToFile("AddDigitalSignature.docx", FileFormat.Docx2013, certificatePath, password);
        }
    }
}

C#/VB.NET: Digitally Sign 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.

page 12