Monday, 20 December 2021 07:38

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

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.

Monday, 18 March 2024 06:11

C#: Add Page Numbers to a PDF Document

Adding page numbers to a PDF document is not only practical but also aesthetically pleasing, as it provides a polished look akin to professionally published materials. Whether you're dealing with a digital copy of a novel, a report, or any other type of lengthy document, having page numbers can significantly improve its readability and utility. In this article, you will learn how to add page numbers to a PDF document in C# 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 DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

PDF Coordinate System

When utilizing Spire.PDF for .NET to manipulate an existing PDF document, it's important to note that the coordinate system's origin is located at the top left corner of the page. The x-axis extends to the right, while the y-axis extends downward.

Typically, page numbers are positioned within the header or footer section of a document. Therefore, it is crucial to take into account the page size and margins when determining the appropriate placement for the page numbers.

C#: Add Page Numbers to a PDF Document

Add Left-Aligned Page Numbers in the Footer in C#

In the Spire.PDF for .NET library, there are two classes available: PdfPageNumberField and PdfPageCountField. These classes allow you to retrieve and display the current page number and the total page count when they are added to a page of a PDF document. If you wish to insert text such as "Page X" or "Page X of Y", you can utilize the PdfCompositeField class, which enables you to combine the desired text with one or more fields into a single field.

The following are the steps to add left-aligned page numbers in the PDF footer using C#.

  • Create a Document object.
  • Load a PDF file from a specified page.
  • Create a PdfPageNumberField object and a PdfPageCountField object.
  • Create a PdfCompositeField object to create a "Page X of Y" format.
  • Specify the location of the PdfCompositeField object using PdfCompositeField.Location property.
  • Iterate though the pages in the document, and add "Page X of Y" to the left corner of the footer section using PdfCompositeField.Draw() method.
  • Save the document to a different PDF file.
  • C#
using Spire.Pdf.AutomaticFields;
using Spire.Pdf.Graphics;
using Spire.Pdf;
using System.Drawing;
using Spire.Pdf.License;

namespace AddPageNumbersToLeftCorner
{
    class Program
    {
        static void Main(string[] args)
        {
            // Apply your license key
            LicenseProvider.SetLicenseKey("License Key");

            // Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

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

            // Create font, brush and pen, which determine the appearance of the page numbers to be added
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", 12, FontStyle.Regular), true);
            PdfBrush brush = PdfBrushes.Black;
            PdfPen pen = new PdfPen(brush, 1.0f);

            // Create a PdfPageNumberField object and a PdfPageCountField object
            PdfPageNumberField pageNumberField = new PdfPageNumberField();
            PdfPageCountField pageCountField = new PdfPageCountField();

            // Create a PdfCompositeField object to combine page count field and page number field in a single field
            PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField);

            // Get the page size
            SizeF pageSize = doc.Pages[0].Size;

            // Set the location of the composite field
            compositeField.Location = new PointF(72, pageSize.Height - 45);

            // Iterate through the pages in the document
            for (int i = 0; i < doc.Pages.Count; i++)
            {

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

                // Draw a line at the specified position
                page.Canvas.DrawLine(pen, 72, pageSize.Height - 50, pageSize.Width - 72, pageSize.Height - 50);

                // Draw the composite field on the page
                compositeField.Draw(page.Canvas);
            }

            // Save to a different PDF file
            doc.SaveToFile("AddPageNumbersToLeftCorner.pdf");

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

C#: Add Page Numbers to a PDF Document

Add Center-Aligned Page Numbers in the Footer in C#

In order to align the page number in the footer section to the center, it is crucial to dynamically calculate the width of the text "Page X of Y." This calculation is essential as it determines the X coordinate of the page number (PdfCompositeField). To achieve center alignment, the X coordinate is calculated by subtracting the width of the page number from the page width and dividing the result by 2, as follows: (PageWidth - PageNumberWidth)/2.

The following are the steps to add center-aligned page numbers in the PDF footer using C#.

  • Create a Document object.
  • Load a PDF file from a specified page.
  • Create a PdfPageNumberField object and a PdfPageCountField object.
  • Create a PdfCompositeField object to create a "Page X of Y" format.
  • Specify the location of the PdfCompositeField object using PdfCompositeField.Location property.
  • Iterate though the pages in the document, and add "Page X of Y" to the center of the footer section using PdfCompositeField.Draw() method.
  • Save the document to a different PDF file.
  • C#
using Spire.Pdf.AutomaticFields;
using Spire.Pdf.Graphics;
using Spire.Pdf;
using System.Drawing;
using Spire.Pdf.License;

namespace AddPageNumbersToCenter
{
    class Program
    {
        static void Main(string[] args)
        {
            // Apply your license key
            LicenseProvider.SetLicenseKey("License Key");

            // Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

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

            // Create font, brush and pen, which determine the appearance of the page numbers to be added
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", 12, FontStyle.Regular), true);
            PdfBrush brush = PdfBrushes.Black;
            PdfPen pen = new PdfPen(brush, 1.0f);

            // Create a PdfPageNumberField object and a PdfPageCountField object
            PdfPageNumberField pageNumberField = new PdfPageNumberField();
            PdfPageCountField pageCountField = new PdfPageCountField();

            // Create a PdfCompositeField object to combine page count field and page number field in a single field
            PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField);


            // Iterate through the pages in the document
            for (int i = 0; i < doc.Pages.Count; i++)
            {

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

                // Get the page size
                SizeF pageSize = doc.Pages[i].Size;

                // Draw a line at the specified position
                page.Canvas.DrawLine(pen, 72, pageSize.Height - 50, pageSize.Width - 72, pageSize.Height - 50);

                // Measure the size the "Page X of Y"
                SizeF pageNumberSize = font.MeasureString(string.Format("Page {0} of {1}", i + 1, doc.Pages.Count));

                // Set the location of the composite field
                compositeField.Location = new PointF((pageSize.Width - pageNumberSize.Width) / 2, pageSize.Height - 45);

                // Draw the composite field on the page
                compositeField.Draw(page.Canvas);

            }

            // Save to a different PDF file
            doc.SaveToFile("AddPageNumbersToCenter.pdf");

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

C#: Add Page Numbers to a PDF Document

Add Right-Aligned Page Numbers in the Footer in C#

To position the page number in the footer section's right corner, it is essential to dynamically calculate the width of the text "Page X of Y" as well. Because the X coordinate of the page number (PdfCompositeField) is determined by subtracting the combined width of the page number and the right page margin from the page width, as follows: PageWidth - (PageNumberWidth + RightPageMargin).

Below are the steps to add right-aligned page numbers in the PDF footer in C#.

  • Create a Document object.
  • Load a PDF file from a specified page.
  • Create a PdfPageNumberField object and a PdfPageCountField object.
  • Create a PdfCompositeField object to create a "Page X of Y" format.
  • Specify the location of the PdfCompositeField object using PdfCompositeField.Location property.
  • Iterate though the pages in the document, and add "Page X of Y" to the right corner of the footer section using PdfCompositeField.Draw() method.
  • Save the document to a different PDF file.
  • C#
using Spire.Pdf.AutomaticFields;
using Spire.Pdf.Graphics;
using Spire.Pdf;
using System.Drawing;
using Spire.Pdf.License;

namespace AddPageNumbersToRigthCorner
{
    class Program
    {
        static void Main(string[] args)
        {
            // Apply your license key
            LicenseProvider.SetLicenseKey("License Key");

            // Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

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

            // Create font, brush and pen, which determine the appearance of the page numbers to be added
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", 12, FontStyle.Regular), true);
            PdfBrush brush = PdfBrushes.Black;
            PdfPen pen = new PdfPen(brush, 1.0f);

            // Create a PdfPageNumberField object and a PdfPageCountField object
            PdfPageNumberField pageNumberField = new PdfPageNumberField();
            PdfPageCountField pageCountField = new PdfPageCountField();

            // Create a PdfCompositeField object to combine page count field and page number field in a single field
            PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField);


            // Iterate through the pages in the document
            for (int i = 0; i < doc.Pages.Count; i++)
            {

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

                // Get the page size
                SizeF pageSize = doc.Pages[i].Size;

                // Draw a line at the specified position
                page.Canvas.DrawLine(pen, 72, pageSize.Height - 50, pageSize.Width - 72, pageSize.Height - 50);

                // Measure the size the "Page X of Y"
                SizeF pageNumberSize = font.MeasureString(string.Format("Page {0} of {1}", i + 1, doc.Pages.Count));

                // Set the location of the composite field
                compositeField.Location = new PointF(pageSize.Width - pageNumberSize.Width - 72, pageSize.Height - 45);

                // Draw the composite field on the page
                compositeField.Draw(page.Canvas);

            }

            // Save to a different PDF file
            doc.SaveToFile("AddPageNumbersToRigthCorner.pdf");

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

C#: Add Page Numbers to 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.

Spire.PDF supports to save the PDF files into different image file formats, such as BMP, JPG, PNG, GIF and TIFF. It also supports to save the PDF files as the Enhanced Metafile (EMF) image file format. This article will demonstrate how to save the PDF file as the EMF image file format in C#. With the help of Spire.PDF, we only need three lines of codes to finish the conversion function.

Note: Before Start, please download the latest version of Spire.PDF and add Spire.Pdf.dll in the bin folder as the reference of Visual Studio.

Here comes to the steps of how to export the PDF file to EMF in C#:

Step 1: Create a new PDF document and load from file.

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

Step 2: Call to use the SaveAsImage method to save all the PDF pages as System.Drawing.Imaging.ImageFormat.Emf file format.

for (int i = 0; i < doc.Pages.Count; i++)
{
    String fileName = String.Format("Sample-img-{0}.emf", i);
    using (Image image = doc.SaveAsImage(i, Spire.Pdf.Graphics.PdfImageType.Bitmap, 300, 300))
     {
       image.Save(fileName, System.Drawing.Imaging.ImageFormat.Emf);
     }

}

Effective screenshot:

Covert PDF to EMF image file format in C#

Full codes:

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

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

            for (int i = 0; i < doc.Pages.Count; i++)
            {
              using (Image image = doc.SaveAsImage(i, Spire.Pdf.Graphics.PdfImageType.Bitmap, 300, 300))
               {
                 image.Save(fileName, System.Drawing.Imaging.ImageFormat.Emf);
               }

            }
        }
    }
}

If you're creating a written report on a company's monthly expenditures, you might need to include a spreadsheet to show the financial figures and make them easier to read. This article demonstrates how to convert Excel data into a Word table maintaining the formatting in C# and VB.NET using Spire.Office for .NET.

Install Spire.Office for .NET

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

Export Excel Data to a Word Table with Formatting

Below are the steps to convert Excel data to a Word table and keep the formatting using Spire.Office for .NET.

  • Create a Workbook object and load a sample Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet through Workbook.Worksheets[index] property.
  • Create a Document object, and add a section to it.
  • Add a table using Section.AddTable() method.
  • Detect the merged cells in the worksheet and merge the corresponding cells of the Word tale using the custom method MergeCells().
  • Get value of a specific Excel cell through CellRange.Value property and add it to a cell of the Word table using TableCell.AddParagraph().AppendText() method.
  • Copy the font style and cell style from Excel to the Word table using the custom method CopyStyle().
  • Save the document to a Word file using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Xls;

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

            //Load an Excel file
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.xlsx");

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

            //Create a Word document
            Document doc = new Document();
            Section section = doc.AddSection();
            section.PageSetup.Orientation = PageOrientation.Landscape;

            //Add a table
            Table table = section.AddTable(true);
            table.ResetCells(sheet.LastRow, sheet.LastColumn);

            //Merge cells
            MergeCells(sheet, table);

            for (int r = 1; r <= sheet.LastRow; r++)
            {
                //Set row Height
                table.Rows[r - 1].Height = (float)sheet.Rows[r - 1].RowHeight;

                for (int c = 1; c <= sheet.LastColumn; c++)
                {
                    CellRange xCell = sheet.Range[r, c];
                    TableCell wCell = table.Rows[r - 1].Cells[c - 1];

                    //Export data from Excel to Word table
                    TextRange textRange = wCell.AddParagraph().AppendText(xCell.NumberText);

                    //Copy font and cell style from Excel to Word
                    CopyStyle(textRange, xCell, wCell);
                }
            }

            //Save the document to a Word file
            doc.SaveToFile("ExportToWord.docx", Spire.Doc.FileFormat.Docx);
        }
        //Merge cells if any
        private static void MergeCells(Worksheet sheet, Table table)
        {
            if (sheet.HasMergedCells)
            {
                //Get merged cell ranges from Excel
                CellRange[] ranges = sheet.MergedCells;

                //Merge corresponding cells in Word table
                for (int i = 0; i < ranges.Length; i++)
                {
                    int startRow = ranges[i].Row;
                    int startColumn = ranges[i].Column;
                    int rowCount = ranges[i].RowCount;
                    int columnCount = ranges[i].ColumnCount;
                    if (rowCount > 1 && columnCount > 1)
                    {
                        for (int j = startRow; j <= startRow + rowCount; j++)
                        {
                            table.ApplyHorizontalMerge(j - 1, startColumn - 1, startColumn - 1 + columnCount - 1);
                        }
                        table.ApplyVerticalMerge(startColumn - 1, startRow - 1, startRow - 1 + rowCount - 1);
                    }
                    if (rowCount > 1 && columnCount == 1)
                    {
                        table.ApplyVerticalMerge(startColumn - 1, startRow - 1, startRow - 1 + rowCount - 1);
                    }
                    if (columnCount > 1 && rowCount == 1)
                    {
                        table.ApplyHorizontalMerge(startRow - 1, startColumn - 1, startColumn - 1 + columnCount - 1);
                    }
                }
            }
        }

        //Copy cell style of Excel to Word table
        private static void CopyStyle(TextRange wTextRange, CellRange xCell, TableCell wCell)
        {
            //Copy font style
            wTextRange.CharacterFormat.TextColor = xCell.Style.Font.Color;
            wTextRange.CharacterFormat.FontSize = (float)xCell.Style.Font.Size;
            wTextRange.CharacterFormat.FontName = xCell.Style.Font.FontName;
            wTextRange.CharacterFormat.Bold = xCell.Style.Font.IsBold;
            wTextRange.CharacterFormat.Italic = xCell.Style.Font.IsItalic;
            //Copy backcolor
            wCell.CellFormat.Shading.BackgroundPatternColor = xCell.Style.Color;
            //Copy horizontal alignment
            switch (xCell.HorizontalAlignment)
            {
                case HorizontalAlignType.Left:
                    wTextRange.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Left;
                    break;
                case HorizontalAlignType.Center:
                    wTextRange.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center;
                    break;
                case HorizontalAlignType.Right:
                    wTextRange.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right;
                    break;
            }
            //Copy vertical alignment
            switch (xCell.VerticalAlignment)
            {
                case VerticalAlignType.Bottom:
                    wCell.CellFormat.VerticalAlignment = VerticalAlignment.Bottom;
                    break;
                case VerticalAlignType.Center:
                    wCell.CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                    break;
                case VerticalAlignType.Top:
                    wCell.CellFormat.VerticalAlignment = VerticalAlignment.Top;
                    break;
            }
        }
    }
}

C#/VB.NET: Convert Excel Data to Word Tables with Formatting

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.

Wednesday, 18 May 2016 07:41

How to Align a Table in C#

Usually there are three kinds of alignment style for a word table: left aligned, centered and right aligned. On Microsoft word, we can go to table properties to set the alignment for the whole table. Spire.Doc also offers a property table.TableFormat.HorizontalAlignment to enable developers to set the table alignment style easily in C#. This article will demonstrate how to align a table in C#.

Firstly, view the how to align a table for Microsoft word:

How to align a table in C#

Here come to the code snippet of how Spire.Doc align a table.

Step 1: Create a word document and load from file.

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

Step 2: Get the first section and two tables from the word document.

Section section = doc.Sections[0];
Table table = section.Tables[0] as Table;
Table table1 = section.Tables[1] as Table;

Step 3: Set the different alignment properties for each table.

table.Format.HorizontalAlignment = RowAlignment.Right;
table.Format.LeftIndent = 34;

table1.Format.HorizontalAlignment = RowAlignment.Left;
table1.Format.LeftIndent = 34;

Step 4: Save the document to file:

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

Effective screenshots after align the table format:

How to align a table in C#

Full codes:

using Spire.Doc;
using Spire.Doc.Documents;
namespace AlignTable
{
    class Program
    {

        static void Main(string[] args)
        {

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

            Section section = doc.Sections[0];
            Table table = section.Tables[0] as Table;
            Table table1 = section.Tables[1] as Table;

            table.Format.HorizontalAlignment = RowAlignment.Right;
            table.Format.LeftIndent = 34;
            
            table1.Format.HorizontalAlignment = RowAlignment.Left;
            table1.Format.LeftIndent = 34;

            doc.SaveToFile("result.docx", FileFormat.Docx);
        }
    }
}

To view the large amount of Excel data's easily, Spire.XLS for .NET supports create Pivot table and add excel table with filters. Spire.XLS also offers a method of pivotTable.ReportFilters.Add(); to enable developers to add the report filter to the pivot table.

This article will show you how to add a report filter to the Excel Pivot table in C#.

Note: Before Start, please download the latest version of Spire.XLS and add Spire.xls.dll in the bin folder as the reference of Visual Studio.

Firstly, please check the original screenshot of excel pivot table.

How to add report filter to Excel Pivot table in C#

Step 1: Create a new workbook and load from file.

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

Step 2: Get the PivotTable from the Excel worksheet.

Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotTable pivotTable = workbook.Worksheets["Pivot Table"].PivotTables[0] as Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotTable;

Step 3: Add a filter to the pivot table.

PivotReportFilter filter = new PivotReportFilter("JAN", true);
pivotTable.ReportFilters.Add(filter);

Step 4: Save the document to file and launch to preview it.

workbook.SaveToFile("Result.xlsx", ExcelVersion.Version2010);
System.Diagnostics.Process.Start("result.xlsx");

Effective screenshot after add a filter to the pivot table:

How to add report filter to Excel Pivot table in C#

Full codes:

using Spire.Xls;
using Spire.Xls.Core.Spreadsheet.PivotTables;

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

            Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotTable pivotTable = workbook.Worksheets["Pivot Table"].PivotTables[0] as Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotTable;

            PivotReportFilter filter = new PivotReportFilter("JAN", true);
            pivotTable.ReportFilters.Add(filter);

            workbook.SaveToFile("Result.xlsx", ExcelVersion.Version2010);
            System.Diagnostics.Process.Start("result.xlsx");
        }
    }
}

By using Spire.XLS, developers can easily set the IconSetType of conditional formatting. This article will demonstrate how to set the traffic lights icons in C# with the help of Spire.XLS.

Note: Before Start, please download the latest version of Spire.XLS and add Spire.xls.dll in the bin folder as the reference of Visual Studio.

Here comes to the code snippets:

Step 1: Create a new excel document instance and get the first worksheet.

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

Step 2: Add some data to the Excel sheet cell range and set the format for them.

sheet.Range["A1"].Text = "Traffic Lights";
sheet.Range["A2"].NumberValue = 0.95;
sheet.Range["A2"].NumberFormat = "0%";
sheet.Range["A3"].NumberValue = 0.5;
sheet.Range["A3"].NumberFormat = "0%";
sheet.Range["A4"].NumberValue = 0.1;
sheet.Range["A4"].NumberFormat = "0%";
sheet.Range["A5"].NumberValue = 0.9;
sheet.Range["A5"].NumberFormat = "0%";
sheet.Range["A6"].NumberValue = 0.7;
sheet.Range["A6"].NumberFormat = "0%";
sheet.Range["A7"].NumberValue = 0.6;
sheet.Range["A7"].NumberFormat = "0%";

Step 3: Set the height of row and width of column for Excel cell range.

sheet.AllocatedRange.RowHeight = 20;
sheet.AllocatedRange.ColumnWidth = 25;

Step 4: Add a conditional formatting of cell range and set its type to CellValue.

XlsConditionalFormats xcfs1 = sheet.ConditionalFormats.Add();
xcfs1.AddRange(sheet.AllocatedRange);
IConditionalFormat cf1 = xcfs1.AddCondition();
cf1.FormatType= ConditionalFormatType.CellValue;
cf1.FirstFormula = "300";
cf1.Operator = ComparisonOperatorType.Less;
cf1.FontColor = Color.Black;
cf1.BackColor = Color.LightSkyBlue;

Step 5: Add a conditional formatting of cell range and set its type to IconSet.

IConditionalFormat cf2 = xcfs1.AddCondition();
cf2.FormatType = ConditionalFormatType.IconSet;
cf2.IconSet.IconSetType = IconSetType.ThreeTrafficLights1;

Step 6: Save the document to file.

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

Effective screenshots of the traffic lights icons set by Spire.XLS.

How to set the traffic lights icons in C# by Spire.XLS

Thursday, 04 February 2016 06:54

Set XMP Metadata of a PDF Document in C#/VB.NET

XMP is a file labeling technology that lets you embed metadata into files themselves during the content creation process. With an XMP enabled application, your workgroup can capture meaningful information about a project (such as titles and descriptions, searchable keywords, and up-to-date author and copyright information) in a format that is easily understood by your team as well as by software applications, hardware devices, and even file formats.

In the Spire.PDF Version 3.6.135 and above, we add a new feature to read, set and load an existing XMP data from XML documents. This article presents how to set XMP Metadata while creating a PDF document.

Code Snippet:

Step 1: Initialize a new instance of PdfDocument class.

string input = "..\\..\\..\\..\\..\\..\\Data\\SetXMPMetadata.pdf";

// Open a PDF document.
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(input);

// Set XMP metadata for the document.
doc.DocumentInformation.Author = "E-iceblue";
doc.DocumentInformation.Creator = "Spire.PDF";
doc.DocumentInformation.Keywords = "XMP";
doc.DocumentInformation.Producer = "E-icenlue Co,.Ltd";
doc.DocumentInformation.Subject = "XMP Metadata";
doc.DocumentInformation.Title = "Set XMP Metadata in PDF";

// Specify the output file name for the modified PDF.
string output = "SetXMPMetadata.pdf";

// Save the PDF document with the updated XMP metadata.
doc.SaveToFile(output);

Output:

To view metadata in a PDF document, open it with Acrobat or Acrobat Reader and select ‘Document Properties’ in the File menu.

Set XMP Matedata of a PDF Document in C#, VB.NET

Full Code:

[C#]
using Spire.Pdf;
using Spire.Pdf.Xmp;
using System;

namespace SetXMPMetadata
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "..\\..\\..\\..\\..\\..\\Data\\SetXMPMetadata.pdf";

            // Open a PDF document.
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile(input);

            // Set XMP metadata for the document.
            doc.DocumentInformation.Author = "E-iceblue";
            doc.DocumentInformation.Creator = "Spire.PDF";
            doc.DocumentInformation.Keywords = "XMP";
            doc.DocumentInformation.Producer = "E-icenlue Co,.Ltd";
            doc.DocumentInformation.Subject = "XMP Metadata";
            doc.DocumentInformation.Title = "Set XMP Metadata in PDF";

            // Specify the output file name for the modified PDF.
            string output = "SetXMPMetadata.pdf";

            // Save the PDF document with the updated XMP metadata.
            doc.SaveToFile(output);
        }
    }
}
[VB.NET]
Imports Spire.Pdf
Imports Spire.Pdf.Xmp

Namespace SetXMPMetadata
	Class Program
		Private Shared Sub Main(args As String())
            Load the input PDF file
            Dim input As String = "..\..\..\..\..\..\Data\SetXMPMetadata.pdf"

            ' Create a new PdfDocument object
            Dim doc As New PdfDocument()

            ' Load the PDF document from the input file
            doc.LoadFromFile(input)

            ' Set the author information in the document properties
            doc.DocumentInformation.Author = "E-iceblue"

            ' Set the creator information in the document properties
            doc.DocumentInformation.Creator = "Spire.PDF"

            ' Set the keywords information in the document properties
            doc.DocumentInformation.Keywords = "XMP"

            ' Set the producer information in the document properties
            doc.DocumentInformation.Producer = "E-icenlue Co,.Ltd"

            ' Set the subject information in the document properties
            doc.DocumentInformation.Subject = "XMP Metadata"

            ' Set the title information in the document properties
            doc.DocumentInformation.Title = "Set XMP Metadata in PDF"

            ' Specify the output file name
            Dim output As String = "SetXMPMetadata.pdf"

            ' Save the modified document to the output file
            doc.SaveToFile(output)	
	   End Sub
	End Class
End Namespace
Wednesday, 03 February 2016 08:10

How to delete layer in PDF

With the help of Spire.PDF, we can add several kinds of layers such as line, image, string, ellipse, rectangle and pie to any page of a new or an existing pdf document. At the same time, it also supports us to delete specific layer from a pdf document.

In this section, we're going to demonstrate how to delete layer in PDF using Spire.PDF for .NET. To add layer to PDF, please check this article: How to add layers to PDF file in C#.

Below is the screenshot of the original PDF document which contains three layers: a red line layer and two image layers.

How to delete layer in PDF

Before start, download Spire.PDF and install it correctly, next add the corresponding dll file from the installation folder as reference of your project.

Detail steps:

Step 1: Initialize a new instance of PdfDocument class and load the sample document from file.

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

Step 2: Get its first page and delete the specific layer by name from page one.

doc.Layers.RemoveLayer("red line");

Step 3: Save and launch the file.

doc.SaveToFile("delete.pdf");
System.Diagnostics.Process.Start("delete.pdf");

Effective screenshot after deleting:

How to delete layer in PDF

Full codes:

using Spire.Pdf;

namespace Delete_page_layer_in_PDF
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load the document from disk
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile(@"..\..\..\..\..\..\Data\DeleteLayer.pdf");

            // Remove the "red line" layer from the document
            doc.Layers.RemoveLayer("red line");

            // Save the modified document to a new file
            doc.SaveToFile("Output.pdf");

            // View the Pdf file
            PDFDocumentViewer("Output.pdf");
        }
    }
}
Monday, 16 November 2015 09:05

How to add layers to PDF file in C#

Developers can use PDF layer to set some content to be visible and others to be invisible in the same PDF file. It makes the PDF Layer widely be used to deal with related contents within the same PDF. Now developers can easily add page layers by using class PdfPageLayer offered by Spire.PDF. This article will focus on showing how to add layers to a PDF file in C# with the help of Spire.PDF.

Note: Before Start, please download the latest version of Spire.PDF and add Spire.PDF.dll in the bin folder as the reference of Visual Studio.

Here comes to the details:

Step 1: Create a new PDF document

PdfDocument pdfdoc = new PdfDocument();

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

PdfPageBase page = pdfdoc.Pages.Add();

Step 3: Add a layer named "red line" to the PDF page.

 PdfLayer layer = doc.Layers.AddLayer("red line", PdfVisibility.On);

Step 4: Draw a red line to the added layer.

// Create a graphics context for drawing on the specified page's canvas using the created layer
 PdfCanvas pcA = layer.CreateGraphics(page.Canvas);

 // Draw a red line on the graphics context using a pen with thickness 2, starting from (100, 350) to (300, 350)
 pcA.DrawLine(new PdfPen(PdfBrushes.Red, 2), new PointF(100, 350), new PointF(300, 350));

Step 5: Use the same method above to add the other two layers to the PDF page.

layer = doc.Layers.AddLayer("blue line");
PdfCanvas pcB = layer.CreateGraphics(doc.Pages[0].Canvas);
pcB.DrawLine(new PdfPen(PdfBrushes.Blue, 2), new PointF(100, 400), new PointF(300, 400));
layer = doc.Layers.AddLayer("green line");
PdfCanvas pcC = layer.CreateGraphics(doc.Pages[0].Canvas);
pcC.DrawLine(new PdfPen(PdfBrushes.Green, 2), new PointF(100, 450), new PointF(300, 450));

Step 6: Save the document to file.

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

Effective screenshot:

How to add layers to PDF file in C#

Full codes:

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

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

  // Load an existing PDF document from the specified file path
  doc.LoadFromFile(@"..\..\..\..\..\..\Data\AddLayers.pdf");

  // Get the first page of the loaded document
  PdfPageBase page = doc.Pages[0];

  // Create a new layer named "red line" with visibility set to "On"
  PdfLayer layer = doc.Layers.AddLayer("red line", PdfVisibility.On);

  // Create a graphics context for drawing on the specified page's canvas using the created layer
  PdfCanvas pcA = layer.CreateGraphics(page.Canvas);

  // Draw a red line on the graphics context using a pen with thickness 2, starting from (100, 350) to (300, 350)
  pcA.DrawLine(new PdfPen(PdfBrushes.Red, 2), new PointF(100, 350), new PointF(300, 350));

  // Create a new layer named "blue line" without specifying visibility (default is "Off")
  layer = doc.Layers.AddLayer("blue line");

  // Create a graphics context for drawing on the first page's canvas using the newly created layer
  PdfCanvas pcB = layer.CreateGraphics(doc.Pages[0].Canvas);

  // Draw a blue line on the graphics context using a pen with thickness 2, starting from (100, 400) to (300, 400)
  pcB.DrawLine(new PdfPen(PdfBrushes.Blue, 2), new PointF(100, 400), new PointF(300, 400));

  // Create a new layer named "green line" without specifying visibility (default is "Off")
  layer = doc.Layers.AddLayer("green line");

  // Create a graphics context for drawing on the first page's canvas using the newly created layer
  PdfCanvas pcC = layer.CreateGraphics(doc.Pages[0].Canvas);

  // Draw a green line on the graphics context using a pen with thickness 2, starting from (100, 450) to (300, 450)
  pcC.DrawLine(new PdfPen(PdfBrushes.Green, 2), new PointF(100, 450), new PointF(300, 450));

  // Specify the output file name for the modified PDF
  string output = "AddLayers.pdf";

  // Save the modified PDF document to the specified output file
  doc.SaveToFile(output);
        }
    }
}