Thursday, 24 October 2013 06:20

How to Export Data into XML in C#?

The aim of the article is to introduce the procedure of exporting data into Office OpenXML in only two steps with a .net component. Spire.DataExport is a completely pure .NET component suit for exporting data into MS Excel, MS Word, HTML, Office OpenXML, PDF, MS Access, DBF, RTF, SQL Script, SYLK, DIF, CSV, MS Clipboard format. It has high performance for exporting data from Command, ListView, DataTable components, which help you to save much time and money.

Please download Spire.DataExport for .NET, add Spire.DataExport.dll as reference and set its target framework as .NET 4. Besides, many developers also check and download another C# excel component together - Spire.XLS for .NET.

Step1: Function to fill data in datatable

In this step, Spire.DataExport will help to load Data information from the datatable. After setting up the data source and SQL command, we can even preview and modify data through DataGridVew before exporting.

[C#]
private void Form1_Load(object sender, EventArgs e)
        {
            oleDbConnection1.ConnectionString = txtConnectString.Text;
            oleDbCommand1.CommandText = txtCommandText.Text;
            using (OleDbDataAdapter da = new OleDbDataAdapter())
            {
                da.SelectCommand = oleDbCommand1;
                da.SelectCommand.Connection = oleDbConnection1;
                DataTable dt = new DataTable();
                da.Fill(dt);
                dataGridView1.DataSource = dt;
            }
        }

Check the Screenshot below:

Datatable_to_XML_01

Step2: Export Data to Office OpenXML

The code below shows how to export data from the datatable to Office OpenXML. Spire.DataExport will create a new Office OpenXML and export data into Office OpenXML through DataGridView. It also allows you to rename the generated Office OpenXML in this step.

[C#]
private void btnExportToXml_Click(object sender, EventArgs e)
        {
            Spire.DataExport.XML.XMLExport xmlExport = new Spire.DataExport.XML.XMLExport();
            xmlExport.DataSource = Spire.DataExport.Common.ExportSource.DataTable;
            xmlExport.DataTable = this.dataGridView1.DataSource as DataTable;
            xmlExport.ActionAfterExport = Spire.DataExport.Common.ActionType.OpenView;
            xmlExport.FileName = @"..\..\ToXml.xml";
            xmlExport.SaveToFile();
        }

Check the Screenshot below:

Datatable_to_XML_02

Wednesday, 16 October 2013 09:13

How to Export Data into MS Access in C#?

This article will show you a clear introduction of how to Export Data to MS Access in C# via a .NET Data Export component. Spire.DataExport for.NET is designed to help developers to perform data exporting processing tasks. With Spire.DataExport, the whole exporting process is quickly and it only needs two simple steps.

Please download Spire.DataExport for .NET and install it on your system, add Spire.DataExport.dll as reference in the downloaded Bin folder thought the below path: “…\Spire.DataExport\Bin\NET4.0\ Spire.DataExport.dll”.

Step 1: Load Data Information

In this step, Spire.DataExport helps us load data from database. Through DataGridVew, we can even preview and modify data.

[C#]
private void Form1_Load(object sender, EventArgs e)
        {
            oleDbConnection1.ConnectionString = txtConnectString.Text;
            oleDbCommand1.CommandText = txtCommandText.Text;
            using (OleDbDataAdapter da = new OleDbDataAdapter())
            {
                da.SelectCommand = oleDbCommand1;
                da.SelectCommand.Connection = oleDbConnection1;
                DataTable dt = new DataTable();
                da.Fill(dt);
                dataGridView1.DataSource = dt;
            }
        }

Please check the screenshot:

datatable to access

Step 2: Set Export into MS Access

Here we need to set it as Access format. Spire.DataExport will create a new Access and through DataGridView export data into Access file. You can rename the file as you like.

[C#]
private void btnExportToAccess_Click(object sender, EventArgs e)
        {
            Spire.DataExport.Access.AccessExport accessExport = new              
            Spire.DataExport.Access.AccessExport();
            accessExport.DataSource = Spire.DataExport.Common.ExportSource.DataTable;
            accessExport.DataTable = this.dataGridView1.DataSource as DataTable;
            accessExport.DatabaseName = @"..\..\ToMdb.mdb";
            accessExport.TableName = "ExportFromDatatable";
            accessExport.SaveToFile();
        }

Here comes to the results:

Export to Access

There are some requirements to export datatable or dataset to word file on many occasions at work. The aim of this article is to help you complete this requirement. Spire.DataExport can help easily load data from the datatable and create a new Word file for storing the data. In addition to this, Spire.DataExport (or Spire.Office) can export data into MS Excel, HTML, XML, PDF, MS Access, DBF, SQL Script, SYLK, DIF, CSV and MS Clipboard format as well, which can be downloaded here. The following code is the example of showing how Spire.DataExport works.

Step 1: Function to fill data in datatable

In this step, Spire.DataExport will help load Data information from the datatable. After setting up the data source and SQL command, it allows you to preview and edit data in DataGridView component before exporting.

[C#]
private void Form1_Load(object sender, EventArgs e)
        {
            oleDbConnection1.ConnectionString = txtConnectString.Text;
            oleDbCommand1.CommandText = txtCommandText.Text;
            using (OleDbDataAdapter da = new OleDbDataAdapter())
            {
                da.SelectCommand = oleDbCommand1;
                da.SelectCommand.Connection = oleDbConnection1;
                DataTable dt = new DataTable();
                da.Fill(dt);
                dataGridView1.DataSource = dt;
            }
        }

Effect Picture

datatable to word

Step 2: Export Data to word document

The code below shows how to export data from the datatable to Word file. Spire.DataExport will create a new MS Word for storing exported Data. It also allows you to rename the generated Word file in this step.

[C#]
private void btnExportToWord_Click(object sender, EventArgs e)
        {
            Spire.DataExport.RTF.RTFExport rtfExport = new Spire.DataExport.RTF.RTFExport();
            rtfExport.DataSource = Spire.DataExport.Common.ExportSource.DataTable;
            rtfExport.DataTable = this.dataGridView1.DataSource as DataTable;
            rtfExport.ActionAfterExport = Spire.DataExport.Common.ActionType.OpenView;
            RTFStyle rtfStyle = new RTFStyle();
            rtfStyle.FontColor = Color.Blue;
            rtfStyle.BackgroundColor = Color.LightGreen;
            rtfExport.RTFOptions.DataStyle = rtfStyle;
            rtfExport.FileName=@"..\..\ToWord.doc";
            rtfExport.SaveToFile();
        }

Effect Picture

datatable to word

Tuesday, 12 November 2024 08:22

C#: Extract Images from PDF Documents

Extracting images from PDFs is a common task for many users, whether it's for repurposing visuals in a presentation, archiving important graphics, or facilitating easier analysis. By mastering image extraction using C#, developers can enhance resource management and streamline their workflow.

In this article, you will learn how to extract images from individual PDF pages as well as from entire documents using C# and 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

Extract Images from a Specific PDF Page

The PdfImageHelper class in Spire.PDF for .NET is designed to help users manage images within PDF documents. It allows for various operations, such as deleting, replacing, and retrieving images.

To obtain information about the images on a specific PDF page, developers can utilize the PdfImageHelper.GetImagesInfo(PdfPageBase page) method. Once they have the image information, they can save the images to files using the PdfImageInfo.Image.Save() method.

The steps to extract images from a specific PDF page are as follows:

  • Create a PdfDocument object.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Get a specific page using PdfDocument.Pages[index] property.
  • Create a PdfImageHelper object.
  • Get the image information collection from the page using PdfImageHelper.GetImagesInfo() method.
  • Iterate through the image information collection and save each instance as a PNG file using PdfImageInfo.Image.Save() method.
  • C#
using Spire.Pdf;
using Spire.Pdf.Utilities;
using System.Drawing;

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

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

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

            // Create a PdfImageHelper object
            PdfImageHelper imageHelper = new PdfImageHelper();

            // Get all image information from the page 
            PdfImageInfo[] imageInfos = imageHelper.GetImagesInfo(page);

            // Iterate through the image information
            for (int i = 0; i < imageInfos.Length; i++)
            {
                // Get a specific image information
                PdfImageInfo imageInfo = imageInfos[i];

                // Get the image
                Image image = imageInfo.Image;

                // Save the image to a png file
                image.Save("C:\\Users\\Administrator\\Desktop\\Extracted\\Image-" + i + ".png");
            }

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

Extract images from a specific PDF page

Extract All Images from an Entire PDF Document

Now that you know how to extract images from a specific page, you can iterate through the pages in a PDF document and extract images from each page. This allows you to collect all the images contained in the document.

The steps to extract all images throughout an entire PDF document are as follows:

  • Create a PdfDocument object.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Create a PdfImageHelper object.
  • Iterate through the pages in the document.
    • Get a specific page using PdfDocument.Pages[index] property.
    • Get the image information collection from the page using PdfImageHelper.GetImagesInfo() method.
    • Iterate through the image information collection and save each instance as a PNG file using PdfImageInfo.Image.Save() method.
  • C#
using Spire.Pdf;
using Spire.Pdf.Utilities;
using System.Drawing;

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

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

            // Create a PdfImageHelper object
            PdfImageHelper imageHelper = new PdfImageHelper();

            // Declare an int variable
            int m = 0;

            // Iterate through the pages
            for (int i = 0; i < doc.Pages.Count; i++)
            {
                // Get a specific page
                PdfPageBase page = doc.Pages[i];

                // Get all image information from the page 
                PdfImageInfo[] imageInfos = imageHelper.GetImagesInfo(page);

                // Iterate through the image information
                for (int j = 0; j < imageInfos.Length; j++)
                {
                    // Get a specific image information
                    PdfImageInfo imageInfo = imageInfos[j];

                    // Get the image
                    Image image = imageInfo.Image;

                    // Save the image to a png file
                    image.Save("C:\\Users\\Administrator\\Desktop\\Extracted\\Image-" + m + ".png");
                    m++;
                }

            }

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

Extract all images from an entire 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.

Friday, 20 September 2013 03:34

How to convert PDF pages to Tiff image in WPF?

Background

PDF is now widely used to represent document in independent specification. It encapsulates a complete description of a fixed-layout flat document, including the text, fonts and graphics and so on. Due to its powerful functions, it is difficult for developers to parse its format. Or more specifically, to parse content out from PDF document and convert it to different image format is a tough task for some developers. This article will help you solve this problem by using PDF document viewer component Spire.PDFViewer for WPF by 5 easy steps. Firstly, you can download Spire.PDFViewer for WPF.

Target

To convert a specified or random page including frames of images from PDF file to TIFF programmatically.

Step 1: To create WPF application in Visual Studio and reference Spire.PdfViewer.WPF dlls.

Set .NET 4 as target framework

Step 2: Instance an object of Spire.PdfViewer.Wpf.PdfDocumentViewer

[C#]
PdfDocumentViewer pdfViewer = new PdfDocumentViewer();

Step 3: Call the “LoadFromFile”of PdfDocumentViewer object and load a PDF file.

[C#]
pdfViewer.LoadFromFile ("sample.pdf");

Step 4: Create an array and save all pages of this PDF file.

[C#]
int[] pageNumbers=new int[pageCount];
            for (int i=0;i

Step 5: Save it to Tiff image format

[C#]
pdfViewer.SaveAsImage("sample.tiff",pageNumbers);

The following code snippet shows all the code when converting pdf page to tiff image:

[C#]
private void Button_Click(object sender, RoutedEventArgs e)
        {
            // Instance an object of Spire.PdfViewer.Wpf.PdfDocumentViewer
            PdfDocumentViewer pdfViewer = new PdfDocumentViewer();
            //Load a pdf file 
            pdfViewer.LoadFromFile("sample.pdf");
            int pageCount = pdfViewer.PageCount;
            // create an array and save all pages of this PDF file.
            int[] pageNumbers=new int[pageCount];
            for (int i=0;i

Screenshot

wpf screenshot

Spire.PDFViewer for WPF is a powerful WPF PDF Viewer control which enables developers to display PDF documents with their WPF applications without Adobe Reader. It’s available to load and view PDF documents like PDF/A-1B, PDF/X1A, and even encrypted from stream, file and byte array with support for printing, zooming, etc.

XPS is a format similar to PDF but uses XML in layout, appearance and printing information of a file. XPS format was developed by Microsoft and it is natively supported by the Windows operating systems. If you want to work with your PDF files on a Windows computer without installing other software, you can convert it to XPS format. Likewise, if you need to share a XPS file with a Mac user or use it on various devices, it is more recommended to convert it to PDF. This article will demonstrate how to programmatically convert PDF to XPS or XPS to PDF 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 

Convert PDF to XPS in C# and VB.NET

Spire.PDF for .NET supports converting PDF to various file formats, and to achieve the PDF to XPS conversion, you just need three lines of core code. The following are the detailed steps.

  • Create a PdfDocument instance.
  • Load a sample PDF document using PdfDocument.LoadFromFile() method.
  • Convert the PDF document to an XPS file using PdfDocument.SaveToFile (string filename, FileFormat.XPS) method.
  • C#
  • VB.NET
using Spire.Pdf;

namespace ConvertPdfToXps
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument instance
            PdfDocument pdf = new PdfDocument();

            //Load sample PDF document 
            pdf.LoadFromFile("sample.pdf");

            //Save it to XPS format 
            pdf.SaveToFile("ToXPS.xps", FileFormat.XPS);
            pdf.Close();
        }
    }
}

C#/VB.NET: Convert PDF to XPS or XPS to PDF

Convert XPS to PDF in C# and VB.NET

Conversion from XPS to PDF can also be achieved with Spire.PDF for .NET. While converting, you can set to keep high quality image on the generated PDF file by using the PdfDocument.ConvertOptions.SetXpsToPdfOptions() method. The following are the detailed steps.

  • Create a PdfDocument instance.
  • Load an XPS file using PdfDocument.LoadFromFile(string filename, FileFormat.XPS) method or PdfDocument.LoadFromXPS() method.
  • While conversion, set the XPS to PDF convert options to keep high quality images using PdfDocument.ConvertOptions.SetXpsToPdfOptions() method.
  • Save the XPS file to a PDF file using PdfDocument.SaveToFile(string filename, FileFormat.PDF) method.
  • C#
  • VB.NET
using Spire.Pdf;

namespace ConvertXPStoPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument instance
            PdfDocument pdf = new PdfDocument();

            //Load a sample XPS file
            pdf.LoadFromFile("Sample.xps", FileFormat.XPS);
            //pdf.LoadFromXPS("Sample.xps");

            //Keep high quality images when converting XPS to PDF
            pdf.ConvertOptions.SetXpsToPdfOptions(true);

            //Save the XPS file to PDF
            pdf.SaveToFile("XPStoPDF.pdf", FileFormat.PDF);
        }
    }
}

C#/VB.NET: Convert PDF to XPS or XPS 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.

Tuesday, 03 September 2013 02:08

How to Calculate Formulas in XLS Document in C#

Background

Excel is widely used to organize data manipulations like arithmetic operations. Excel provides many built-in functions which automate a number of types of calculation. Functions are pre-programmed formulate for example, the square-root function, trigonometric functions, logarithms etc. Excel has more than 300 functions covering a range of statistical, mathematical, financial and logical operations. There is no doubt that using a function offers a shortcut method.

Calculate Formulas in XLS Document

Microsoft Excel is a powerful tool which has many uses, the most basic feature of which is performing functions. The aim of this article is to help you perform simple arithmetic operations on values in programming by using excel functions. Spire.Xls for .NET can help you easily create a new excel document or load an existing excel document into program, and calculate data of designated cell by function. Applied in Console platform, WinForm and Asp.net, It provide different types of mathematical functions, statistical functions , logic functions ,and string functions to calculate data with C# codes.

The following is the method example of using Console application to show how Spire.XLS for .NET realizes the calculation formula:

Step 1: Build a console application, and add spire.XLS.dll, Spire.Common.dll assembly.

Step 2: Instantiate an object of Spire.Xls.WorkBook, and add a “WorkSheet” in WorkBook object.

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

Step 3: Set the value and format in Cell A1 and Cell A3.veiwing the C# Code.

[C#]
//set Column A, B, C width
sheet.SetColumnWidth(1, 32);
sheet.SetColumnWidth(2, 16);
sheet.SetColumnWidth(3, 16);

// Set value of Cell A1
sheet.Range[currentRow++, 1].Value = "Examples of formulas :";
// Set value of Cell A2.
sheet.Range[++currentRow, 1].Value = "Test data:";

// Set text format Of Cell A1
CellRange range = sheet.Range["A1"];
range.Style.Font.IsBold = true;
range.Style.FillPattern = ExcelPatternType.Solid;
range.Style.KnownColor = ExcelColors.LightGreen1;
range.Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Medium;

Step 4: Set some cells value and then to sum up some cells data and the results will be displayed in one of the cells.

[C#]
sheet.Range[currentRow, 2].NumberValue = 7.3;
sheet.Range[currentRow, 3].NumberValue = 5;
sheet.Range[currentRow, 4].NumberValue = 8.2;
sheet.Range[currentRow, 5].NumberValue = 4;
sheet.Range[currentRow, 6].NumberValue = 3;
sheet.Range[currentRow, 7].NumberValue = 11.3;
//Create arithmetic expression string about cells

currentFormula = "=Sheet1!$B$3 + Sheet1!$C$3+Sheet1!$D$3+Sheet1!$E$3+Sheet1!$F$3+Sheet1!$G$3";
//Caculate arithmetic expression about cells
formulaResult = workbook.CaculateFormulaValue(currentFormula);
value = formulaResult.ToString();
sheet.Range[currentRow, 2].Value = value;

Step 5: Respectively set value and text format of Cell A4, B4.

[C#]
sheet.Range[++currentRow, 1].Value = "Formulas"; ;
sheet.Range[currentRow, 2].Value = "Results";
range = sheet.Range[currentRow, 1, currentRow, 2];
range.Style.Font.IsBold = true;
range.Style.KnownColor = ExcelColors.LightGreen1;
range.Style.FillPattern = ExcelPatternType.Solid;
range.Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Medium;

Step 6: Realize calculation simple expression.

[C#]
// Create arithmetic tables enclosed type string
currentFormula = "=33*3/4-2+10";
sheet.Range[++currentRow, 1].Text = currentFormula;
// Caculate arithmetic expression
formulaResult = workbook.CaculateFormulaValue(currentFormula);
value = formulaResult.ToString();
sheet.Range[currentRow, 2].Value = value;

Step 7: Realize some mathematic functions.

[C#]
//absolute value function .
currentFormula = "=ABS(-1.21)";
sheet.Range[currentRow, 1].Text = currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;

Step 8: Realize some logic function.

[C#]
//NOT function
//Create NOT function string
currentFormula = "=NOT(true)";
sheet.Range[currentRow, 1].Text = currentFormula;
//Caculate NOT function
formulaResult = workbook.CaculateFormulaValue(currentFormula);
value = formulaResult.ToString();
sheet.Range[currentRow, 2].Value = value;
sheet.Range[currentRow, 2].HorizontalAlignment = HorizontalAlignType.Right;

Step 9: Realize some string handling functions.

[C#]
//Get the substring
// Build substring function
currentFormula = "=MID(\"world\",4,2)";
sheet.Range[++currentRow, 1].Text = currentFormula;
//Caculate substring function
formulaResult = workbook.CaculateFormulaValue(currentFormula);
value = formulaResult.ToString();
sheet.Range[currentRow, 2].Value = value;
sheet.Range[currentRow, 2].HorizontalAlignment = HorizontalAlignType.Right;

Step 10: Realize a random function.

[C#]
// Random function
// Create random function string.
currentFormula = "=RAND()";
sheet.Range[++currentRow, 1].Text = currentFormula;
//Caculate random function
formulaResult = workbook.CaculateFormulaValue(currentFormula);
value = formulaResult.ToString();
sheet.Range[currentRow, 2].Value = value;

Step 11: Save workbook object as file.

[C#]
workbook.SaveToFile("formulaTest.xls",ExcelVersion.Version97to2003);

Viewing the full c# code

[C#]
using Spire.Xls;

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

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

            int currentRow = 1;
            string currentFormula = string.Empty;
            object formulaResult = null;
            string value = string.Empty;

            // Set column widths for columns A, B, and C (1-based index)
            sheet.SetColumnWidth(1, 32);
            sheet.SetColumnWidth(2, 16);
            sheet.SetColumnWidth(3, 16);

            // Set the value of Cell A1
            sheet.Range[currentRow++, 1].Value = "Examples of formulas :";
            // Set the value of Cell A2
            sheet.Range[++currentRow, 1].Value = "Test data:";
            // Set the style of Cell A1
            CellRange range = sheet.Range["A1"];
            range.Style.Font.IsBold = true;
            range.Style.FillPattern = ExcelPatternType.Solid;
            range.Style.KnownColor = ExcelColors.LightGreen1;
            range.Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Medium;

            // Populate test data in row 3 (columns B to G)
            sheet.Range[currentRow, 2].NumberValue = 7.3;
            sheet.Range[currentRow, 3].NumberValue = 5; ;
            sheet.Range[currentRow, 4].NumberValue = 8.2;
            sheet.Range[currentRow, 5].NumberValue = 4;
            sheet.Range[currentRow, 6].NumberValue = 3;
            sheet.Range[currentRow, 7].NumberValue = 11.3;
            // Define a formula that sums the values in cells B3 through G3
            currentFormula = "=Sheet1!$B$3 + Sheet1!$C$3+Sheet1!$D$3+Sheet1!$E$3+Sheet1!$F$3+Sheet1!$G$3";
            // Calculate the result of the formula
            formulaResult = workbook.CalculateFormulaValue(currentFormula);
            value = formulaResult.ToString();
            sheet.Range[currentRow, 2].Value = value;


            // Set the value and format of two head cell
            sheet.Range[++currentRow, 1].Value = "Formulas"; ;
            sheet.Range[currentRow, 2].Value = "Results";
            sheet.Range[currentRow, 2].HorizontalAlignment = HorizontalAlignType.Right;
            range = sheet.Range[currentRow, 1, currentRow, 2];
            range.Style.Font.IsBold = true;
            range.Style.KnownColor = ExcelColors.LightGreen1;
            range.Style.FillPattern = ExcelPatternType.Solid;
            range.Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Medium;

            // --- Arithmetic Expression Example ---

            // Define a basic arithmetic formula
            currentFormula = "=33*3/4-2+10";
            sheet.Range[++currentRow, 1].Text = currentFormula;
            // Calculate and display the result
            formulaResult = workbook.CalculateFormulaValue(currentFormula);
            value = formulaResult.ToString();
            sheet.Range[currentRow, 2].Value = value;

            // --- Mathematical Function: ABS (Absolute Value) ---

            // Define an ABS function formula
            currentFormula = "=ABS(-1.21)";
            sheet.Range[++currentRow, 1].Text = currentFormula;
            // Calculate and display the absolute value
            formulaResult = workbook.CalculateFormulaValue(currentFormula);
            value = formulaResult.ToString();
            sheet.Range[currentRow, 2].Value = value;


            // --- Statistical Function: SUM ---

            // Define a SUM function formula
            currentFormula = "=SUM(18,29)";
            sheet.Range[++currentRow, 1].Text = currentFormula;
            // Calculate and display the sum
            formulaResult = workbook.CalculateFormulaValue(currentFormula);
            value = formulaResult.ToString();
            sheet.Range[currentRow, 2].Value = value;

            // --- Logical Function: NOT ---
            // Define a NOT function formula
            currentFormula = "=NOT(true)";
            sheet.Range[currentRow, 1].Text = currentFormula;
            // Calculate and display the logical result
            formulaResult = workbook.CalculateFormulaValue(currentFormula);
            value = formulaResult.ToString();
            sheet.Range[currentRow, 2].Value = value;
            sheet.Range[currentRow, 2].HorizontalAlignment = HorizontalAlignType.Right;

            // --- Text Function: MID (Substring Extraction) ---
            // Define a MID function to extract characters from a string
            currentFormula = "=MID(\"world\",4,2)";
            sheet.Range[++currentRow, 1].Text = currentFormula;
            // Calculate and display the substring result
            formulaResult = workbook.CalculateFormulaValue(currentFormula);
            value = formulaResult.ToString();
            sheet.Range[currentRow, 2].Value = value;
            sheet.Range[currentRow, 2].HorizontalAlignment = HorizontalAlignType.Right;

            // --- Random Number Function: RAND() ---
            // Define a RAND function to generate a random number between 0 and 1
            currentFormula = "=RAND()";
            sheet.Range[++currentRow, 1].Text = currentFormula;
            // Calculate and display the random value
            formulaResult = workbook.CalculateFormulaValue(currentFormula);
            value = formulaResult.ToString();
            sheet.Range[currentRow, 2].Value = value;

            // Save the workbook to a file
            workbook.SaveToFile("formulaTest2.xls", ExcelVersion.Version97to2003);
            System.Diagnostics.Process.Start("formulaTest2.xls");
        }
    }
}

Screenshot:

formula_01

Modifying passwords of PDF file is really a rational choice especially when the passwords are known by someone and your PDF file is no longer safe. Spire.PDF for .NET enables you to modify passwords of your encrypted PDF file in C#, VB.NET. You can modify your owner password as well as user password and set user restrictions when access the PDF file. Now please see the process of modifying encrypted PDF passwords as below picture:

Modify PDF Passwords

From above picture, you can easily find that the first step is to decrypt PDF file by owner password. So the original owner password is necessary. You can decrypt it by this method: Spire.Pdf.PdfDocument(string filename, string password)

Then, modify passwords by resetting owner password and user password. PDFSecurity class which is in the namespace Spire.PDFDocument.Security can help you not only to set owner password and user password, but also can set user permissions to restrict user access.

Below shows the whole code of modifying passwords of encrypted PDF file, please download Spire.PDF for .NET and install it on system before following the code:

[C#]
using Spire.Pdf;
using Spire.Pdf.Security;

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

            //load a encrypted file and decrypt it
            String encryptedPdf = @""..\Encrypt.pdf"";
            PdfDocument doc = new PdfDocument(encryptedPdf, ""e-iceblue"");

            // Define user and owner passwords
            string userPassword = ""user"";
            string ownerPassword = ""owner"";

            // Create a security policy with the specified passwords
            PdfSecurityPolicy securityPolicy = new PdfPasswordSecurityPolicy(userPassword, ownerPassword);

            // Set the encryption algorithm to AES 128-bit
            securityPolicy.EncryptionAlgorithm = PdfEncryptionAlgorithm.AES_128;

            // Allow printing of the document
            securityPolicy.DocumentPrivilege.AllowPrint = true;

            // Allow filling form fields in the document
            securityPolicy.DocumentPrivilege.AllowFillFormFields = true;

            // Allow copying content from the document
            securityPolicy.DocumentPrivilege.AllowContentCopying = true;

            // Encrypt the PDF document using the specified security policy
            doc.Encrypt(securityPolicy);

            // Save the encrypted PDF document to a file named ""SecurityPermission.pdf""
           doc.SaveToFile(""Encryption-result.pdf"");  
            
        }    
    }
}
[VB.NET]
Imports Spire.Pdf
Imports Spire.Pdf.Security

Namespace modify_PDF_passwords
	Class Program
		Private Shared Sub Main(args As String())

		  load a encrypted file and decrypt it
		  Dim encryptedPdf As String = ""..\Encrypt.pdf""
		  Dim doc As New PdfDocument(encryptedPdf, ""e-iceblue"")

		  ' Define user and owner passwords
		  Dim userPassword As String = ""user""
		  Dim ownerPassword As String = ""owner""

		  ' Create a security policy with the specified passwords
		  Dim securityPolicy As PdfSecurityPolicy = New PdfPasswordSecurityPolicy(userPassword, ownerPassword)

		  ' Set the encryption algorithm to AES 128-bit
		  securityPolicy.EncryptionAlgorithm = PdfEncryptionAlgorithm.AES_128

		  ' Allow printing of the document
		  securityPolicy.DocumentPrivilege.AllowPrint = True

		  ' Allow filling form fields in the document
		  securityPolicy.DocumentPrivilege.AllowFillFormFields = True

		  ' Allow copying content from the document
		  securityPolicy.DocumentPrivilege.AllowContentCopying = True

		  ' Encrypt the PDF document using the specified security policy
		  doc.Encrypt(securityPolicy)

		  ' Save the encrypted PDF document to a file named ""SecurityPermission.pdf""
		  doc.SaveToFile(""Encryption-result.pdf"")

		End Sub
	End Class
End Namespace

Spire.PDF for .NET is a .NET PDF component that enables you to generate, read, edit and manipulate PDF files in C#, VB.NET.

Tuesday, 11 December 2012 02:06

License Agreement

BY INSTALLING, DOWNLOADING, COPYING OR OTHERWISE USING THE PRODUCT, YOU AGREE TO BE BOUND BY THE TERMS OF THIS EULA. IF YOU DO NOT AGREE TO THE TERMS OF THIS EULA, DO NOT INSTALL, DOWNLOAD, COPY OR USE THE PRODUCT.

1. IMPORTANT NOTICE.

YOU SHOULD READ THE FOLLOWING TERMS AND CONDITIONS CAREFULLY BEFORE YOU DOWNLOAD, INSTALL OR USE E-ICEBLUE'S LIBRARY AND RELATED DOCUMENTATION (THE "LICENSED SOFTWARE") DISTRIBUTED UNDER THE TRADEMARK OF LIBRARY AND/OR E-ICEBLUE. BY INSTALLING OR USING THE LICENSED SOFTWARE, YOU AGREE TO BE BOUND BY THIS LICENSE AGREEMENT, AND ITS TERMS SHALL BE BINDING WITH RESPECT TO YOUR USE OF THE LICENSED SOFTWARE. IF YOU DO NOT AGREE TO THE FOLLOWING TERMS AND CONDITIONS, DO NOT INSTALL OR USE THE SOFTWARE.

2. DEFINITIONS.

A. "e-iceblue" means e-iceblue Corporation
B. "You" and "Your" mean the party purchasing a license to use the Licensed Software under the terms of this agreement.
C. "Application Programming Interface or API" means a publicly accessible interface defining the ways by which an application program may request services from libraries and/or software.
D. "Licensed Software" means compiled Objects, Modules, License Key and any and all updates thereto, together with all associated documentation provided by e-iceblue or its authorized resellers.
E. "License Key" means a unique code provided by e-iceblue or its authorized resellers which identifies You, as well as the license type, and which unlocks or enables certain features of the Licensed Software.
F. "Application" or "Your Application" means a software application that You develop which incorporates all or parts of the Licensed Software.
G. "Evaluation Trial Period" means a specified period of time during which You may temporarily use the Licensed Software for evaluation purposes only.

3. LICENSE GRANT.

The Cumulative License granted to You by e-iceblue is a combination of the Base License Grant, described in section (3A) below, which is common to every Licensed Software title covered by this agreement, and one or more supplemental License Grant which covers the specific product obtained by You from e-iceblue or its authorized resellers.
Four basic types of supplemental License Grants are described in sections (3B): Evaluation License, Developer License, Developer OEM License, Site Enterprise License, Site OEM License.
These five basic types are hereby further defined and/or restricted as to the number of developers, servers, geography locations and distribution method(s), depending on the specific product(s) being licensed by You.
The precise combination of the Base License Grant and one or more supplemental License Grant(s) obtained by You is identified by e-iceblue at the time of purchase or most recent upgrade.

3A. BASE LICENSE GRANT.

In consideration of Your payment of applicable license fees and/or Your acceptance of the terms of this Agreement, e-iceblue hereby grants to You certain nonexclusive and nontransferable rights limited by the terms of this Agreement.
The Licensed Software is licensed (not sold) to You, for use strictly under the terms of this Agreement, and e-iceblue reserves all rights not expressly granted to You herein. If You upgrade the Licensed Software to a higher-numbered version thereof or to a comparable E-iceblue product, this license is terminated and Your rights shall be limited to the license associated with the upgraded product or version.
In addition, You acknowledge that the Licensed Software may contain certain third party software components which are distributed under the terms of their own licenses.

3B. EVALUATION LICENSE.

In order to facilitate an efficient evaluation process of the Licensed Software by developers, e-iceblue may, at its discretion, provide specially designed, temporary License Key(s) that are encoded with an embedded expiration date.
The License granted in conjunction with such License Key(s) is considered temporary, and multiple developers may use it for the sole purpose of evaluating the Licensed Software during a specific Evaluation Trial Period. Licensed Evaluation Trial Software contains mechanisms that inhibit its ability to function at a later date.
It is Your responsibility to ensure that the Applications You create do not contain Licensed Evaluation Trial Software and that their ability to function at a later date is not inhibited or diminished.

3C. DEVELOPER LICENSE.

The following terms and conditions contained in this section (3C) apply to You ONLY if at the time of original purchase or most recent upgrade, the License granted to You by E-iceblue was defined as "Developer License".
The specific license level selected by you at the time of purchase or most recent upgrade determines whether the license applies to (1) a single named developer, or (2) a team of named developers, for example a Developer Team, or (3) a single site (facility or campus) whereby an unlimited number of developers located within said site (facility or campus) may be allowed access to the Licensed Software.

You are hereby granted a nonexclusive, royalty-free license to integrate the Licensed Software into Your Applications and to distribute such Licensed Software in connection with said Applications, provided that
(a) said Applications do not in any way compete with the Licensed Software, or provide substantially the same functionality as the Licensed Software, or expose the functionality of the Licensed Software through a programmable interface;
(b) each of Your Applications developed using Licensed Software is substantially larger, more complex, and contains a significantly wider range of functions as compared to the Licensed Software;
(c) each of Your Applications developed using Licensed Software is designed for end users, rather than for developers who would be able to build other software that would compete with the Licensed Software, and
(d) You do not permit further distribution of the Licensed Software by Your end users.

You may embed the License Keys in the Applications You distribute, provided that the following conditions are met:
(a) each such Application must be marked with a prominent copyright notice bearing Your name as declared by You during purchase of the License;
(b) the License Key may not be embedded in any such Application or distributed in any other manner that makes the License Key visible to the end user, and
(c) each such Application must include the following comment in its source code within close proximity to each copy of an embedded License Key: "This application utilizes a licensed copy of e-iceblue software, copyright (c) 2004-2026, which is the property of e-iceblue Corporation, www.e-iceblue.com. All rights are reserved by e-iceblue.
Use of any objects outside of the context of this application is a violation of United States and international copyright laws and other applicable laws."

For each License Key provided to You by e-iceblue, depending on the specific license level selected by you at the time of purchase or most recent upgrade, You are granted a nonexclusive License to make the Licensed Software and/or the License Key(s) available either to the specified number of Your named developers or to an unlimited number of Your developers located at a single site (facility or campus) as indicated by e-iceblue and further explained below.
Should either the number of named developers or the number of sites with access to the Licensed Software and/or the License Key(s) ever exceed the number indicated at the time of original purchase or most recent upgrade, You agree to inform E-iceblue of such change and to upgrade Your License accordingly by paying an upgrade fee to e-iceblue in a timely manner.

  • One Developer Small Business authorizes One developer to utilize our product to create an unlimited number of applications which can be deployed at One geographic location in your organization (internal use only). It does not allow distribution of your custom applications to public-facing websites, docker or SaaS/PaaS/IaaS projects.
  • One Developer OEM authorizes One developer to create an unlimited of custom applications using our product, and the applications are allowed to be distributed in any form to any number of geographic locations.
  • One Site Small Business authorizes up to 10 developers to create an unlimited number of applications which can be deployed at up to 10 geographic locations. It does not allow distribution of your custom applications to public-facing websites, docker or SaaS/PaaS/IaaS projects.
  • One Site OEM authorizes up to 10 developers to create an unlimited number of custom applications using our product, and the applications are allowed to be distributed in any form to any number of geographic locations.

Notes:

  • A developer is defined as a software developer, a tester or other person who uses the product for programming, compiling and debugging. Each developer must have their own license.
  • A geographic location is defined as a unique Mac Address/Machine ID.

4. RESTRICTIONS ON USE AND TRANSFER.

You may not sublicense, rent, lease, assign or otherwise transfer the Licensed Software or any of Your rights thereto, either in whole or in part, to anyone else, except that You may, after obtaining written permission from e-iceblue, permanently transfer the Licensed Software in its entirety, provided You retain no copies of the Licensed Software and the transferee agrees to the terms and conditions of this Agreement.
Use of the Licensed Software with a License Key obtained from a source other than e-iceblue or its authorized resellers is expressly and strictly forbidden. e-iceblue reserves the right to take any and all actions that e-iceblue, in its sole discretion, deems necessary to protect against, monitor and control the use of the Licensed Software with illegal License Keys.
You agree to ensure that anyone who uses any portion of the Licensed Software provided to You complies with the terms and conditions of this Agreement.

5. INTELLECTUAL PROPERTY RIGHTS.

You acknowledge that the Licensed Software contains copyrighted material, trade secrets, trademarks and other proprietary material of e-iceblue ("Confidential Information"), and is protected under United States and international copyright law and other applicable laws.
You may not engage in any unauthorized use or disclosure of any Confidential Information. You agree that the source code of the Licensed Software is confidential and proprietary to e-iceblue. Accordingly, You may not copy the Licensed Software, or decompile, disassemble, reverse engineer or create a derivative work based upon the Licensed Software, or authorize anyone else to do so.
You must reproduce and maintain all copyright notices that are contained in the Licensed Software on any copy thereof that You make or use.

6. TERM AND TERMINATION.

Except as otherwise provided in this Agreement, depending on the specific license level selected by you at the time of purchase or most recent upgrade, the term of the license granted herein is either perpetual, or alternatively the license is periodic, valid for a specific period of time, such as a month or a year.
The license becomes effective when You install or use the Licensed Software. You may terminate this license at any time by destroying any and all copies of the Licensed Software or by returning all such copies to e-iceblue.
This Agreement and the associated license for the Licensed Software will terminate automatically and without provision of notice by e-iceblue if You fail to comply with any of the terms or conditions of this Agreement or if You cease permanent use of the Licensed Software, for whatever reason.
Upon termination of this Agreement for any reason, You agree that You will destroy all copies of the Licensed Software or return all such copies to e-iceblue. In addition to this sentence and the previous sentence, Sections 4, 5 and 7-13 shall survive any termination of this Agreement.

7. LIMITED WARRANTY.

e-iceblue warrants that the Licensed Software will perform substantially in accordance with its accompanying documentation, when operated in the execution environment specified in such documentation, for the warranty period ending thirty (30) days following the date on which You first install or first use the Licensed Software.
This limited warranty is void if failure of the Licensed Software to conform to such warranty is caused in whole or in part by
(a) any defect in any hardware or other equipment used with the Licensed Software;
(b) any failure of any hardware or any other equipment used with the Licensed Software to function in accordance with applicable manufacturer's specifications for such items;
(c) any alteration, modification or enhancement of the Licensed Software by You or anyone other than e-iceblue;
(d) any failure by You or anyone else to follow e-iceblue's instructions with respect to proper use of the Licensed Software; or
(e) improper use, abuse, accident, neglect or negligence on the part of You or anyone other than e-iceblue.
e-iceblue will not be obligated to honor the limited warranty or provide any remedy thereunder unless the Licensed Software is returned to e-iceblue along with the original dated receipt.
Any replacement Licensed Software will be warranted for thirty (30) days following the date on which e-iceblue provides it to You.

EXCEPT AS OTHERWISE SET FORTH IN THIS AGREEMENT, THE LICENSED SOFTWARE IS PROVIDED TO YOU "AS IS", AND E-ICEBLUE MAKES NO EXPRESS OR IMPLIED WARRANTIES WHATSOEVER WITH RESPECT TO ITS FUNCTIONALITY, CONDITION, PERFORMANCE, OPERABILITY OR USE.
WITHOUT LIMITING THE FOREGOING, E-ICEBLUE DISCLAIMS ALL IMPLIED WARRANTIES INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR FREEDOM FROM INFRINGEMENT.
SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO THE ABOVE EXCLUSIONS MAY NOT APPLY TO YOU.
THIS LIMITED WARRANTY GIVES YOU SPECIFIC LEGAL RIGHTS, AND YOU MAY ALSO HAVE OTHER RIGHTS THAT VARY FROM ONE JURISDICTION TO ANOTHER.

8. LIMITATIONS OF LIABILITY.

YOUR SOLE AND EXCLUSIVE REMEDY FOR ANY BREACH OF THE FOREGOING LIMITED WARRANTY SHALL BE, AT E-ICEBLUE'S OPTION, EITHER (A) REPAIR OR REPLACEMENT OF THE LICENSED SOFTWARE SO THAT IT CONFORMS TO THE FOREGOING LIMITED WARRANTY, OR (B) REFUND OF THE FEE THAT YOU PAID TO LICENSE THE LICENSED SOFTWARE.
IN NO EVENT SHALL E-ICEBLUE BE LIABLE FOR ANY DAMAGES OF ANY TYPE, WHETHER DIRECT OR INDIRECT, CONSEQUENTIAL, INCIDENTAL OR SPECIAL DAMAGES, INCLUDING WITHOUT LIMITATION, LOST REVENUES, LOST PROFITS, LOSSES RESULTING FROM BUSINESS INTERRUPTION OR LOSS OF DATA, REGARDLESS OF THE FORM OF ACTION OR LEGAL THEORY UNDER WHICH SUCH LIABILITY MAY BE ASSERTED, EVEN IF E-ICEBLUE HAS BEEN ADVISED OF THE POSSIBILITY OR LIKELIHOOD OF SUCH DAMAGES.
E-ICEBLUE SHALL HAVE NO LIABILITY WITH RESPECT TO ANY DATA THAT IS READ, ACCESSED, STORED OR PROCESSED WITH THE LICENSED SOFTWARE, OR FOR THE COSTS OF RECOVERING ANY SUCH DATA.
IN NO EVENT SHALL E-ICEBLUE'S MAXIMUM AGGREGATE LIABILITY UNDER THIS AGREEMENT EXCEED THE TOTAL FEES PAID OR PAYABLE BY YOU TO LICENSE THE LICENSED SOFTWARE.
SOME JURISDICTIONS DO NOT ALLOW THE LIMITATION OR EXCLUSION OF LIABILITY FOR INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THE ABOVE LIMITATION OR EXCLUSION MAY NOT APPLY TO YOU.

9. INDEMNIFICATION.

You agree to defend, indemnify, and hold E-iceblue and all of its employees, agents, representatives, directors, officers, partners, shareholders, attorneys, predecessors, successors, and assigns harmless from and against any and all claims, proceedings, damages, injuries, liabilities, losses, costs, and expenses (including reasonable attorneys' fees and litigation expenses), relating to or arising from Your use of the Licensed Software, or any breach of this Agreement, except to the extent such claim relates to or arises from a violation by e-iceblue of any third party copyright, trademark, trade secret or other intellectual property right.

10. EXPORT.

You agree that You will not export or transmit the Licensed Software or any Applications, directly or indirectly, to any restricted countries or in any manner that would violate United States laws and regulations as shall from time to time govern the license and delivery of technology abroad by persons subject to the jurisdiction of the United States government, including the Export Administration Act of 1979, as amended, and any applicable laws or regulations issued thereafter.

11. U.S. GOVERNMENT RESTRICTED RIGHTS.

If You are licensing the Licensed Software on behalf of the U.S. Government or any of its agencies ("Government"), the use, duplication, reproduction, release, modification, disclosure or transfer of the Licensed Software by the Government is subject to restricted rights in accordance with Federal Acquisition Regulation ("FAR") 12.212 for civilian agencies and Defense Federal Acquisition Regulation Supplement ("DFARS") 227.7202 for military agencies.
The Licensed Software is commercial. Use of the Licensed Software by the Government is further restricted in accordance with the terms and conditions of this Agreement.

12. MISCELLANEOUS.

If any provision of this Agreement is held to be invalid or unenforceable under any circumstances, its application in any other circumstances and the remaining provisions of this Agreement shall not be affected.
No waiver of any right under this Agreement shall be effective unless given in writing by an authorized representative of e-iceblue.
No waiver by e-iceblue of any right shall be deemed to be a waiver of any other right of e-iceblue arising under this Agreement.
This Agreement is solely between You and e-iceblue and shall not be construed to create any third party beneficiary rights in any other individual, partnership, corporation or other entity.
This Agreement shall be governed by and interpreted in accordance with the laws of the State of New York, without regard to its provisions governing conflicts of law.
Any and all disputes between You and e-iceblue pertaining to this Agreement shall be submitted to one arbitrator in binding arbitration within ten miles of New York City, New York in accordance with the Commercial Rules of the American Arbitration Association ("AAA").
The arbitrator shall be experienced in computer consulting, the development of custom software, the sale of packaged software, or related services.
If You and e-iceblue do not agree on an arbitrator within sixty (60) days of the institution of the arbitration, the arbitrator shall be chose by AAA.
Evidence and argument may be presented in person or by telephone, fax, postal mail, electronic mail, and other methods of communication approved by the arbitrator.
The prevailing party in such proceeding shall be entitled to recover its actually incurred costs, including reasonable attorney's fees, arbitration and court costs.
All hearings shall be held and a written arbitration award issued within one-hundred eighty (180) days of the date on which the arbitrator is appointed.
Judgment on the award shall be final and binding and may be entered in any court of competent jurisdiction.

13. ENTIRE AGREEMENT.

YOU AGREE THAT THIS AGREEMENT IS THE COMPLETE AND EXCLUSIVE STATEMENT OF THE AGREEMENT BETWEEN YOU AND E-ICEBLUE, AND THAT IT SUPERSEDES ANY PROPOSALS OR PRIOR AGREEMENTS, ORAL OR WRITTEN, AND ANY OTHER COMMUNICATIONS RELATING TO THE LICENSED SOFTWARE AND THE SUBJECT MATTER HEREOF.
E-ICEBLUE SHALL NOT BE BOUND BY ANY PROVISION OF ANY PURCHASE ORDER, RECEIPT, ACCEPTANCE, CONFIRMATION, CORRESPONDENCE OR OTHERWISE, OR BY ANY AGREEMENT BETWEEN YOU AND ANY OTHER PARTY, UNLESS E-ICEBLUE SPECIFICALLY AGREES TO SUCH PROVISION IN WRITING IN A FORM OF A LEGAL CONTRACT, DATED AND SIGNED BY YOU AND BY E-ICEBLUE'S OFFICER OR AUTHORIZED EMPLOYEE.
NO VENDOR, DISTRIBUTOR, PROVIDER, RESELLER, OEM, SALES REPRESENTATIVE, OR OTHER PERSON IS AUTHORIZED TO MODIFY THIS AGREEMENT OR TO MAKE ANY WARRANTY, REPRESENTATION OR PROMISE REGARDING THE LICENSED SOFTWARE WHICH IS DIFFERENT FROM THOSE SET FORTH IN THIS AGREEMENT.

Thursday, 11 August 2022 07:25

C#/VB.NET: Create Lists in PDF Documents

A list is a collection of related values written one after another. Lists are the best tool to make important information stand out on the page, show the steps in a process, or present an overview to the readers. In this article, you will learn how to create ordered or unordered lists in a PDF document in C# and VB.NET using Spire.PDF for .NET.

Spire.PDF provides the PdfSortedList class and the PdfList class to represent the ordered lists and unordered lists, respectively. To set the list's content, indent, font, marker style and other attributes, use the methods, properties, or events under these two classes. The following table lists some of the core items involved in this tutorial.

Member Description
PdfSortedList class Represents an ordered list in a PDF document.
PdfList class Represents an unordered list in a PDF document.
Brush property Gets or sets a list's brush.
Font property Gets or sets a list's font.
Indent property Gets or sets a list's indent.
TextIndent property Gets or sets the indent from the marker to the list item text.
Items property Gets items of a list.
Marker property Gets or sets the marker of a list.
Draw() method Draw list on the canvas of a page at the specified location.
PdfOrderedMarker class Represents the marker style of an ordered list, such as numbers, letters, and roman numerals.
PdfMarker class Represents bullet style for an unordered list.

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

Create an Ordered List in PDF

An ordered list is a container which holds a sequence of objects. Each item in the list is marked with a number, a letter, or a roman numeral. The following are the step to create an ordered list in PDF using Spire.PDF for .NET.

  • Create a PdfDocument object.
  • Add a page to it using PdfDocument.Pages.Add() method.
  • Create PdfBrush and PdfFont objects for the list.
  • Create a PdfOrderedMarker object, specifying the marker style.
  • Specify the list content with a string, and create an object of PdfSortedList class based on the string.
  • Set the font, indent, brush and marker of the list though the properties under the PdfSortedList object.
  • Draw the list on the page at the specified location using PdfSortedList.Draw() method.
  • Save the document to another file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using System;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Lists;

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

            //Set the margins
            PdfMargins margins = new PdfMargins(30);

            //Add a page
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margins);

            //Create a brush
            PdfBrush brush = PdfBrushes.Black;

            //Create fonts
            PdfFont titleFont = new PdfFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Bold);
            PdfFont listFont = new PdfFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Regular);

            //Create a maker for ordered list
            PdfOrderedMarker marker = new PdfOrderedMarker(PdfNumberStyle.LowerLatin, listFont);

            //Specify the initial coordinate
            float x = 10;
            float y = 20;

            //Draw title
            String title = "Required Web Development Skills:";
            page.Canvas.DrawString(title, titleFont, brush, x, y);
            y = y + (float)titleFont.MeasureString(title).Height;
            y = y + 5;


            //Create a numbered list
            String listContent = "Command-line Unix\n"
                + "Vim\n"
                + "HTML\n"
                + "CSS\n"
                + "Python\n"
                + "JavaScript\n"
                + "SQL";
            PdfSortedList list = new PdfSortedList(listContent);

            //Set the font, indent, text indent, brush of the list
            list.Font = listFont;
            list.Indent = 2;
            list.TextIndent = 4;
            list.Brush = brush;
            list.Marker = marker;

            //Draw list on the page at the specified location
            list.Draw(page, x, y);

            //Save to file
            doc.SaveToFile("OrderedList.pdf");
        }
    }
}

C#/VB.NET: Create Lists in PDF Documents

Create an Unordered List with Symbol Bullets in PDF

An unordered list, also named bulleted list, is a collection of related items that have no special order or sequence. Each item in the list is marked with a bullet. The following are the step to create an unordered list in PDF using Spire.PDF for .NET.

  • Create a PdfDocument object.
  • Add a page to it using PdfDocument.Pages.Add() method.
  • Create PdfBrush and PdfFont objects for the list.
  • Create a PdfMarker object, specifying the marker style.
  • Specify the list content with a string, and create an object of PdfList class based on the string.
  • Set the font, indent, brush and marker of the list though the properties under the PdfList object.
  • Draw the list on the page at the specified location using PdfList.Draw() method.
  • Save the document to another file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Lists;
using System;

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

            //Set the margin
            PdfMargins margin = new PdfMargins(30);

            //Add a page
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin);

            //Create fonts
            PdfFont titleFont = new PdfFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Bold);
            PdfFont listFont = new PdfFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Regular);
            PdfFont markerFont = new PdfFont(PdfFontFamily.TimesRoman, 6f, PdfFontStyle.Regular);

            //Create a brush
            PdfBrush brush = PdfBrushes.Black;

            //Specify the initial coordinate
            float x = 10;
            float y = 20;

            //Draw title
            String title = "Computer Science Subjects:";
            page.Canvas.DrawString(title, titleFont, brush, x, y);
            y = y + (float)titleFont.MeasureString(title).Height;
            y = y + 5;

            //Specify the marker style
            PdfMarker marker = new PdfMarker(PdfUnorderedMarkerStyle.Asterisk);
            marker.Font = markerFont;

            //Create an unordered list
            String listContent = "Data Structure\n"
                    + "Algorithm\n"
                    + "Computer Networks\n"
                    + "Operating System\n"
                    + "Theory of Computations\n"
                    + "C Programming\n"
                    +"Computer Organization and Architecture";

            PdfList list = new PdfList(listContent);

            //Set the font, indent, text indent, brush, maker of the list
            list.Font = listFont;
            list.Indent = 2;
            list.TextIndent = 4;
            list.Brush = brush;
            list.Marker = marker;

            //Draw list on a page at the specified location
            list.Draw(page, x, y);

            //Save to file
            doc.SaveToFile("UnorderedList.pdf");
        }
    }
}

C#/VB.NET: Create Lists in PDF Documents

Create an Unordered List with Image Bullets in PDF

In addition to symbols, the bullet points of an unordered list can be also a picture. The steps to create an unordered list with images bullets are as follows.

  • Create a PdfDocument object.
  • Add a page to it using PdfDocument.Pages.Add() method.
  • Create PdfBrush and PdfFont objects for the list.
  • Create a PdfMarker object, setting the marker style as CustomImage.
  • Set an image as the mark through PdfMarker.Image property.
  • Specify the list content with a string, and create an object of PdfList class based on the string.
  • Set the font, indent, brush and marker of the list though the properties under the PdfList object.
  • Draw the list on the page at the specified location using PdfList.Draw() method.
  • Save the document to another file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using System;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Lists;

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

            //Set the margin
            PdfMargins margin = new PdfMargins(30);

            //Add a page
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin);

            //Create fonts
            PdfFont titleFont = new PdfFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Bold);
            PdfFont listFont = new PdfFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Regular);

            //Create a brush
            PdfBrush brush = PdfBrushes.Black;

            //Specify the initial coordinate
            float x = 10;
            float y = 20;

            //Draw title
            String title = "Project Task To-Do List:";
            page.Canvas.DrawString(title, titleFont, brush, x, y);
            y = y + (float)titleFont.MeasureString(title).Height;
            y = y + 5;

            //Specify the marker style to image
            PdfMarker marker = new PdfMarker(PdfUnorderedMarkerStyle.CustomImage);

            //Set the image for the marker
            marker.Image = PdfImage.FromFile(@"C:\Users\Administrator\Desktop\checkmark.jpg");

            //Create an unordered list
            String listContent = "Define projects and tasks you're working on\n"
                    + "Assign people to tasks\n"
                    + "Define the priority levels of your tasks\n"
                    + "Keep track of the progress status of your tasks\n"
                    + "Mark tasks as done when completed";
            PdfList list = new PdfList(listContent);

            //Set the font, indent, text indent, brush, maker of the list
            list.Font = listFont;
            list.Indent = 2;
            list.TextIndent = 4;
            list.Brush = brush;
            list.Marker = marker;

            //Draw list on a page at the specified location
            list.Draw(page, x, y);

            //Save to file
            doc.SaveToFile("ImageBullets.pdf");
        }
    }
}

C#/VB.NET: Create Lists in PDF Documents

Create a Nested Numbered List in PDF

A nested list is a list that contains at least one sub list. Nested lists are used to present data in hierarchical structures. The following are the steps to create a nested numbered list in PDF using Spire.PDF for .NET.

  • Create a PdfDocument object.
  • Add a page to it using PdfDocument.Pages.Add() method.
  • Create a PdfOrderedMarker object, specifying the marker style as Numeric.
  • Specify the list content with a string, and create a parent list based on the string. And then set the font, indent, brush and marker of the list though the properties under the PdfSortedList object.
  • Repeat the above step to create sub lists and sub-sub lists.
  • Get the specific item of the parent list through PdfSortedList.Items[] property, and add a list to it as its sub list through PdfListItem.Sublist property.
  • Draw the list on the page at the specified location using PdfSortedList.Draw() method.
  • Save the document to another file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using System;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Lists;

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

            //Set the margin
            PdfMargins margin = new PdfMargins(30);

            //Add a page
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin);

            //Specify the initial coordinate
            float x = 10;
            float y = 20;

            //Create two brushes
            PdfBrush blackBrush = PdfBrushes.Black;
            PdfBrush purpleBrush = PdfBrushes.Purple;

            //Create two fonts
            PdfFont titleFont = new PdfFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Bold);
            PdfFont listFont = new PdfFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Regular);

            //Create a maker for ordered list
            PdfOrderedMarker marker = new PdfOrderedMarker(PdfNumberStyle.Numeric, listFont);

            //Draw title
            String title = "Below is a Nested Numbered List:";
            page.Canvas.DrawString(title, titleFont, blackBrush, x, y);
            y = y + (float)titleFont.MeasureString(title).Height;
            y = y + 5;

            //Create a parent list
            String parentListContent = "Parent Item 1\n"
                    + "Parent Item 2";
            PdfSortedList parentList = new PdfSortedList(parentListContent);
            parentList.Font = listFont;
            parentList.Indent = 2;
            parentList.Brush = purpleBrush;
            parentList.Marker = marker;

            //Create a sub list - "subList_1"
            String subListContent_1 = "Sub Item 1\n"
                    + "Sub Item 2\n"
                    + "Sub Item 3\n"
                    + "Sub Item 4";
            PdfSortedList subList_1 = new PdfSortedList(subListContent_1);
            subList_1.Indent = 12;
            subList_1.Font = listFont;
            subList_1.Brush = blackBrush;
            subList_1.Marker = marker;
            subList_1.MarkerHierarchy = true;

            //Create another sub list -"subList_2"
            String subListContent_2 = "Sub Item 1\n"
                    + "Sub Item 2\n"
                    + "Sub Item 3";
            PdfSortedList subList_2 = new PdfSortedList(subListContent_2);
            subList_2.Indent = 12;
            subList_2.Font = listFont;
            subList_2.Brush = blackBrush;
            subList_2.Marker = marker;
            subList_2.MarkerHierarchy = true;

            //Create a sub-sub list - "subList_1"
            String subSubListContent_1 = "Sub Sub Item 1\n"
                    + "Sub Sub Item 2";
            PdfSortedList subSubList = new PdfSortedList(subSubListContent_1);
            subSubList.Indent = 20;
            subSubList.Font = listFont;
            subSubList.Brush = blackBrush;
            subSubList.Marker = marker;
            subSubList.MarkerHierarchy = true;

            //Set subList_1 as sub list of the first item of parent list
            PdfListItem item_1 = parentList.Items[0];
            item_1.SubList = subList_1;

            //Set subList_2 as sub list of the second item of parent list
            PdfListItem item_2 = parentList.Items[1];
            item_2.SubList = subList_2;

            //Set subSubList as sub list of the first item of subList_1
            PdfListItem item_1_1 = subList_1.Items[0];
            item_1_1.SubList = subSubList;

            //Draw parent list
            parentList.Draw(page, x, y);

            //Save to file
            doc.SaveToFile("MultiLevelList.pdf");
        }
    }
}

C#/VB.NET: Create Lists in PDF 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.