C#/VB.NET: Create a Line Chart in Word

2023-07-07 01:00:51 Written by Koohji

Charts in Word documents are a valuable tool for presenting and analyzing data in a visually appealing and understandable format. They help summarize key trends, patterns, or relationships within the data, which is especially useful when you are creating company reports, business proposals or research papers. In this article, you will learn how to programmatically add a line chart to a Word document using Spire.Doc for .NET.

Install Spire.Doc for .NET

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

PM> Install-Package Spire.Doc

Create a Line Chart in Word in C# and VB.NET

A line chart is a common type of chart that connects a series of data points with a continuous line. To add a line chart in Word, Spire.Doc for .NET offers the Paragraph.AppendChart(ChartType.Line, float width, float height) method. The following are the detailed steps.

  • Create a Document object.
  • Add a section and then add a paragraph to the section.
  • Add a line chart with specified size to the paragraph using Paragraph.AppendChart(ChartType.Line, float width, float height) method.
  • Get the chart and then set the chart title using Chart.Tilte.Text property.
  • Add a custom series to the chart using Chart.Series.Add(string seriesName, string[] categories, double[] values) method.
  • Set the legend position using Chart.Legend.Position property.
  • Save the result document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields.Shapes.Charts;
using Spire.Doc.Fields;

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

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

            //Add a paragraph to the section
            Paragraph newPara = section.AddParagraph();

            //Add a line chart with specified size to the paragraph
            ShapeObject shape = newPara.AppendChart(ChartType.Line, 460, 300);

            //Get the chart
            Chart chart = shape.Chart;

            //Set chart title
            chart.Title.Text = "Sales Report";

            //Clear the default series data of the chart
            chart.Series.Clear();

            //Add three custom series with specified series names, category names, and series values to chart
            string[] categories = { "Jan", "Feb", "Mar", "Apr"};
            chart.Series.Add("Team A", categories, new double[] { 1000, 2000, 2500, 4200 });
            chart.Series.Add("Team B", categories, new double[] { 1500, 1800, 3500, 4000 });
            chart.Series.Add("Team C", categories, new double[] { 1200, 2500, 2900, 3600 });

            //Set the legend position
            chart.Legend.Position = LegendPosition.Bottom;

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

C#/VB.NET: Create a Line Chart in Word

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.

Extracting tables from PDFs and converting them into Excel format offers numerous advantages, such as enabling data manipulation, analysis, and visualization in a more versatile and familiar environment. This task is particularly valuable for researchers, analysts, and professionals dealing with large amounts of tabular data. In this article, you will learn how to extract tables from PDF to Excel in C# and VB.NET using Spire.Office for .NET.

Install Spire.Office for .NET

To begin with, you need to add the Spire.Pdf.dll and the Spire.Xls.dll included in the Spire.Office for.NET package as references in your .NET project. Spire.PDF is responsible for extracting data from PDF tables, and Spire.XLS is responsible for creating an Excel document based on the data obtained from PDF.

The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Office

Extract Tables from PDF to Excel in C#, VB.NET

Spire.PDF for .NET offers the PdfTableExtractor.ExtractTable(int pageIndex) method to extract tables from a specific page of a searchable PDF document. The text of a specific cell can be accessed using PdfTable.GetText(int rowIndex, int columnIndex) method. This value can be then written to a worksheet through Worksheet.Range[int row, int column].Value property offered by Spire.XLS for .NET.  The following are the detailed steps.

  • Create an instance of PdfDocument class.
  • Load the sample PDF document using PdfDocument.LoadFromFile() method.
  • Extract tables from a specific page using PdfTableExtractor.ExtractTable() method.
  • Get text of a certain table cell using PdfTable.GetText() method.
  • Create a Workbook object.
  • Write the cell data obtained from PDF into a worksheet through Worksheet.Range.Value property.
  • Save the workbook to an Excel file using Workbook.SaveTofile() method.

The following code example extracts all tables from a PDF document and writes each of them into an individual worksheet within a workbook.

  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Utilities;
using Spire.Xls;

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

            //Load the sample PDF file
            doc.LoadFromFile(@"C:\Users\Administrator\Desktop\table.pdf");

            //Create a Workbook object
            Workbook workbook = new Workbook();

            //Clear default worksheets
            workbook.Worksheets.Clear();

            //Initialize an instance of PdfTableExtractor class
            PdfTableExtractor extractor = new PdfTableExtractor(doc);

            //Declare a PdfTable array 
            PdfTable[] tableList = null;

            int sheetNumber = 1;

            //Loop through the pages 
            for (int pageIndex = 0; pageIndex < doc.Pages.Count; pageIndex++)
            {
                //Extract tables from a specific page
                tableList = extractor.ExtractTable(pageIndex);

                //Determine if the table list is null
                if (tableList != null && tableList.Length > 0)
                {
                    //Loop through the table in the list
                    foreach (PdfTable table in tableList)
                    {
                        //Add a worksheet
                        Worksheet sheet = workbook.Worksheets.Add(String.Format("sheet{0}", sheetNumber));

                        //Get row number and column number of a certain table
                        int row = table.GetRowCount();
                        int column = table.GetColumnCount();

                        //Loop though the row and colunm 
                        for (int i = 0; i < row; i++)
                        {
                            for (int j = 0; j < column; j++)
                            {
                                //Get text from the specific cell
                                string text = table.GetText(i, j);

                                //Write text to a specified cell
                                sheet.Range[i + 1, j + 1].Value = text;
                            }
              
                        }
                        sheetNumber++;
                    }
                }
            }

            //Save to file
            workbook.SaveToFile("ToExcel.xlsx", ExcelVersion.Version2013);
        }
    }
}

C#/VB.NET: Extract Tables from PDF to Excel

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

C#/VB.NET: Create Column Charts in Word

2023-07-05 01:15:47 Written by Koohji

A clustered column chart and a stacked column chart are two variations of the column chart. The clustered column chart enables simple comparison of values across different categories, whereas the stacked column chart displays both the total value of different categories and the proportion of each individual component. In this article, you will learn how to create clustered or stacked column charts in Word in C# and VB.NET using Spire.Doc for .NET.

Install Spire.Doc for .NET

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

PM> Install-Package Spire.Doc

Create a Clustered Column Chart in Word in C#, VB.NET

To add a chart to a Word document, use Paragraph.AppenChart(ChartType chartType, float width, float height) method. The ChartType enumeration includes various chart types predefined in MS Word. The following are the steps to add a clustered column chart in Word using Spire.Doc for .NET.

  • Create a Document object.
  • Add a section and a paragraph.
  • Add a column chart to the paragraph using Paragraph.AppendChart() method.
  • Add series to the chart using Chart.Series.Add() method.
  • Set the chart title through Chart.Tilte.Text property.
  • 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.Shapes.Charts;
using Spire.Doc.Fields;

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

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

            //Add a paragraph
            Paragraph paragraph = section.AddParagraph();

            //Add a column chart
            ShapeObject shape = paragraph.AppendChart(ChartType.Column, 450, 250);

            //Get the chart
            Chart chart = shape.Chart;

            //Clear the default data
            chart.Series.Clear();

            //Add a series including series name, category names, and series values to chart
            chart.Series.Add("June",
                new[] { "Cuba", "Mexico", "France", "Germany" },
                new double[] { 5000, 8000, 9000, 8500 });

            //Add another series
            chart.Series.Add("July",
            new[] { "Cuba", "Mexico", "France", "Germany" },
            new double[] { 3000, 5000, 7000, 6000 });

            //Set the chart title
            chart.Title.Text = "Sales by Country";

            //Set the number format of the Y-axis 
            chart.AxisY.NumberFormat.FormatCode = "#,##0";

            //Set the legend position
            chart.Legend.Position = LegendPosition.Bottom;

            //Save to file
            document.SaveToFile("ClusteredColumnChart.docx", FileFormat.Docx2019);
        }
    }
}

C#/VB.NET: Create Column Charts in Word

Create a Stacked Column Chart in Word in C#, VB.NET

A stacked column chart can be created pretty much in the same way as a clustered column chart. The only difference is you have to change the chart type from Column to ColumnStacked.

  • Create a Document object.
  • Add a section and a paragraph.
  • Add a stacked column chart to the paragraph using Paragraph.AppendChart() method.
  • Add series to the chart using Chart.Series.Add() method.
  • Set the chart title through Chart.Tilte.Text property.
  • 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.Shapes.Charts;
using Spire.Doc.Fields;

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

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

            //Add a paragraph
            Paragraph paragraph = section.AddParagraph();

            //Add a stacked column chart
            ShapeObject shape = paragraph.AppendChart(ChartType.ColumnStacked, 450, 250);

            //Get the chart
            Chart chart = shape.Chart;

            //Clear the default data
            chart.Series.Clear();

            //Add a series including series name, category names, and series values to chart
            chart.Series.Add("Store A",
                new[] { "Diet Coke", "Mountain Dew", "Diet Pesi", "Cherry Coke" },
                new double[] { 2500, 4600, 2800, 5100 });

            //Add another series
            chart.Series.Add("Store B",
            new[] { "Diet Coke", "Mountain Dew", "Diet Pesi", "Cherry Coke" },
            new double[] { 4100, 3200, 3800, 4000 });

            //Set the chart title
            chart.Title.Text = "Store Wise Soda Soft Drink Sales";

            //Set the number format of the Y-axis 
            chart.AxisY.NumberFormat.FormatCode = "#,##0";

            //Set the legend position
            chart.Legend.Position = LegendPosition.Bottom;

            //Save to file
            document.SaveToFile("StackedColumnChart.docx", FileFormat.Docx2019);
        }
    }
}

C#/VB.NET: Create Column Charts in Word

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.

print word documents in c#

Printing Word documents programmatically in C# can streamline business workflows, automate reporting, and enhance document management systems. This comprehensive guide explores how to print Word documents in C# using Spire.Doc for .NET, covering everything from basic printing to advanced customization techniques. We'll walk through practical code examples for each scenario, ensuring you can implement these solutions in real-world applications.

.NET Library for Printing Word Documents

Spire.Doc for .NET is a robust, standalone library that supports comprehensive Word document processing without requiring Microsoft Office to be installed. It provides intuitive APIs for loading, editing, and printing Word files (DOC/DOCX) while maintaining perfect formatting fidelity.

To get started, install the library via NuGet Package Manager:

Install-Package Spire.Doc

Alternatively, you can download Spire.Doc for .NET from our official website and reference the DLL file manually.

Print Word Documents in C#

The foundation of Word document printing in C# involves three key steps demonstrated in the following code. First, we create a Document object to represent our Word file, then load the actual document, and finally access the printing functionality through the PrintDocument class.

  • C#
using Spire.Doc;
using System.Drawing.Printing;

namespace PrintWordDocument
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Initialize a new Document instance
            Document doc = new Document();

            // Load the Word file from specified path
            doc.LoadFromFile("Input.docx");

            // Access the PrintDocument object for printing operations
            PrintDocument printDoc = doc.PrintDocument;

            // Send document to default printer
            printDoc.Print();
        }
    }
}

This basic implementation handles the entire printing process, from document loading to physical printing, with just a few lines of code. The PrintDocument object abstracts all the underlying printing operations, making the process straightforward for developers.

Customize Printing Options

Beyond basic printing, Spire.Doc offers extensive customization via the PrinterSettings class, providing developers with granular control over the printing process. These settings allow you to tailor the output to specific needs, such as selecting particular pages or configuring advanced printer features.

To obtain the PrinterSettings object associated with the current document, use the following line of code:

  • C#
PrinterSettings settings = printDoc.PrinterSettings;

Now, let’s explore the specific settings.

1. Specify the Printer Name

  • C#
settings.PrinterName = "Your Printer Name";

This code snippet demonstrates how to target a specific printer in environments with multiple installed printers. The PrinterName property accepts the exact name of the printer as it appears in the system's printer list.

2. Specify Pages to Print

  • C#
settings.FromPage = 1;
settings.ToPage = 5;

These settings are particularly useful when dealing with large documents, allowing you to print only the relevant sections and conserve resources.

3. Specify Number of Copies to Print

  • C#
settings.Copies = 2;

The Copies property controls how many duplicates of the document will be printed, with the printer handling the duplication process efficiently.

4. Enable Duplex Printing

  • C#
if (settings.CanDuplex)
{
    settings.Duplex = Duplex.Default;
}

This example first checks for duplex printing support before enabling two-sided printing, ensuring compatibility across different printer hardware.

5. Print on a Custom Paper Size

  • C#
settings.DefaultPageSettings.PaperSize = new PaperSize("custom", 800, 500);

Here we create a custom paper size (800x500 units) for specialized printing requirements, demonstrating Spire.Doc's flexibility in handling non-standard document formats.

6. Print Word to File

  • C#
settings.PrintToFile = true;
settings.PrinterName = "Microsoft Print to PDF";
settings.PrintFileName = @"C:\Output.pdf";

This configuration uses the system's PDF virtual printer to create a PDF file instead of physical printing, showcasing how Spire.Doc can be used for document conversion as well.

Silently Print Word Documents

In automated environments, you may need to print documents without any user interaction or visible dialogs. The following implementation achieves silent printing by using the StandardPrintController.

  • C#
using Spire.Doc;
using System.Drawing.Printing;

namespace SilentlyPrintWord
{
    class Program
    {
        static void Main(string[] args)
        {
            // Initialize a new Document instance
            Document doc = new Document();

            // Load the Word file from specified path
            doc.LoadFromFile("Input.docx");

            // Access the PrintDocument object for printing operations
            PrintDocument printDoc = doc.PrintDocument;

            // Disable the print dialog
            printDoc.PrintController = new StandardPrintController();

            // Exexute printing
            printDoc.Print();
        }
    }
}

The key to silent printing lies in assigning the StandardPrintController to the PrintController property, which suppresses all printing-related dialogs and progress indicators. This approach is ideal for server-side applications or batch processing scenarios where user interaction is not possible or desired.

Print Multiple Pages on One Sheet

For economizing paper usage or creating compact document versions, Spire.Doc supports printing multiple document pages on a single physical sheet. The PrintMultipageToOneSheet method simplifies this process with predefined layout options.

  • C#
using Spire.Doc;
using Spire.Doc.Printing;
using System.Drawing.Printing;

namespace PrintMultiplePagesOnOneSheet
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Initialize a new Document instance
            Document doc = new Document();

            // Load the Word file from specified path
            doc.LoadFromFile("Input.docx");

            // Configure 2-page-per-sheet printing and execute printing
            doc.PrintMultipageToOneSheet(PagesPerSheet.TwoPages, false);
        }
    }
}

The PagesPreSheet enumeration offers several layout options (OnePage, TwoPages, FourPages, etc.), while the boolean parameter determines whether to include a page border on the printed sheet. This feature is particularly valuable for creating booklet layouts or draft versions of documents.

P.S. This scenario works only with .NET Framework versions earlier than 5.0.

Conclusion

This guide has demonstrated how Spire.Doc for .NET provides a comprehensive solution for Word document printing in C#. It simplifies the process with features such as:

  • Basic & silent printing.
  • Customizable print settings (printer selection, duplex, copies).
  • Multi-page per sheet printing to reduce paper usage.

By integrating these techniques, developers can efficiently automate document printing in enterprise applications, enhancing productivity and reducing manual effort. Overall, Spire.Doc empowers developers to create robust printing solutions that meet diverse business requirements.

FAQs

Q1. Can I print encrypted or password-protected Word files?

A: Yes, Spire.Doc supports printing password-protected documents after loading them with the correct password:

  • C#
doc.LoadFromFile("Protected.docx", FileFormat.Docx, "password");

After successful loading, you can print it like any other document, with all the same customization options available.

Q2. How can I print only selected text from a Word document?

A: You can extract specific content by accessing document sections and paragraphs:

  • C#
Section section = doc.Sections[0];
Paragraph paragraph = section.Paragraphs[0];
// Create new document with selected content
Document newDoc = new Document();
newDoc.Sections.Add(section.Clone());
newDoc.Print();

This approach gives you precise control over which document portions get printed.

Q3. Can I print documents in landscape mode or adjust margins programmatically?

A: Yes! Modify the DefaultPageSettings properties:

  • C#
printDoc.DefaultPageSettings.Landscape = true;
printDoc.DefaultPageSettings.Margins = new Margins(50, 50, 50, 50);

Q4. Can I print other file formats (e.g., PDF, Excel) using Spire.Doc?

A: Spire.Doc is designed for Word files (DOC/DOCX). For PDFs, use Spire.PDF; for Excel, use Spire.XLS.

Get a Free License

To fully experience the capabilities of Spire.Doc for Python without any evaluation limitations, you can request a free 30-day trial license.

If you have multiple images that you want to combine into one file for easier distribution or storage, converting them into a single PDF document is a great solution. This process not only saves space but also ensures that all your images are kept together in one file, making it convenient to share or transfer. In this article, you will learn how to combine several images into a single PDF document 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 DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Combine Multiple Images into a Single PDF in C# and VB.NET

In order to convert all the images in a folder to a PDF, we iterate through each image, add a new page to the PDF with the same size as the image, and then draw the image onto the new page. The following are the detailed steps.

  • Create a PdfDocument object.
  • Set the page margins to zero using PdfDocument.PageSettings.SetMargins() method.
  • Get the folder where the images are stored.
  • Iterate through each image file in the folder, and get the width and height of a specific image.
  • Add a new page that has the same width and height as the image to the PDF document using PdfDocument.Pages.Add() method.
  • Draw the image on the page using PdfPageBase.Canvas.DrawImage() method.
  • Save the document using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

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

            //Set the page margins to 0
            doc.PageSettings.SetMargins(0);

            //Get the folder where the images are stored
            DirectoryInfo folder = new DirectoryInfo(@"C:\Users\Administrator\Desktop\Images");

            //Iterate through the files in the folder
            foreach (FileInfo file in folder.GetFiles())
            {
                //Load a particular image 
                Image image = Image.FromFile(file.FullName);

                //Get the image width and height
                float width = image.PhysicalDimension.Width;
                float height = image.PhysicalDimension.Height;

                //Add a page that has the same size as the image
                PdfPageBase page = doc.Pages.Add(new SizeF(width, height));

                //Create a PdfImage object based on the image
                PdfImage pdfImage = PdfImage.FromImage(image);

                //Draw image at (0, 0) of the page
                page.Canvas.DrawImage(pdfImage, 0, 0, pdfImage.Width, pdfImage.Height);
            }
      
            //Save to file
            doc.SaveToFile("CombinaImagesToPdf.pdf");
            doc.Dispose();
        }
    }
}

C#/VB.NET: Convert Multiple Images into a Single 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.

Waterfall charts in Excel are graphs that visually show how a series of consecutive positive or negative values contribute to the final outcome. They are a useful tool for tracking company profits or cash flow, comparing product revenues, analyzing sales and inventory changes over time, etc. In this article, you will learn how to create a waterfall chart in Excel in C# and VB.NET using Spire.XLS for .NET.

Install Spire.XLS for .NET

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

PM> Install-Package Spire.XLS

Create a Waterfall Chart in Excel in C# and VB.NET

Waterfall/bridge charts are ideal for analyzing financial statements. To add a waterfall chart to an Excel worksheet, Spire.XLS for .NET provides the Worksheet.Charts.Add(ExcelChartType.WaterFall) method. The following are the detailed steps.

  • Create a Workbook instance.
  • Load a sample Excel document using Workbook.LoadFromFile() method.
  • Get a specified worksheet by its index using Workbook.Worksheets[sheetIndex] property.
  • Add a waterfall chart to the worksheet using Worksheet.Charts.Add(ExcelChartType.WaterFall) method.
  • Set data range for the chart using Chart.DataRange property.
  • Set position and title of the chart.
  • Get a specified data series of the chart and then set specific data points in the chart as totals or subtotals using ChartSerie.DataPoints[int index].SetAsTotal property.
  • Show the connector lines between data points by setting the ChartSerie.Format.ShowConnectorLines property to true.
  • Show data labels for data points, and set the legend position of the chart.
  • Save the result document using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

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

            //Load a sample Excel document
            workbook.LoadFromFile("Data.xlsx");

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

            //Add a waterfall chart to the the worksheet
            Chart chart = sheet.Charts.Add(ExcelChartType.WaterFall);

            //Set data range for the chart
            chart.DataRange = sheet["A2:B11"];

            //Set position of the chart
            chart.LeftColumn = 4;
            chart.TopRow = 2;
            chart.RightColumn = 15;
            chart.BottomRow = 23;

            //Set the chart title
            chart.ChartTitle = "Income Statement";

            //Set specific data points in the chart as totals or subtotals
            chart.Series[0].DataPoints[2].SetAsTotal = true;
            chart.Series[0].DataPoints[7].SetAsTotal = true;
            chart.Series[0].DataPoints[9].SetAsTotal = true;

            //Show the connector lines between data points
            chart.Series[0].Format.ShowConnectorLines = true;

            //Show data labels for data points
            chart.Series[0].DataPoints.DefaultDataPoint.DataLabels.HasValue = true;
            chart.Series[0].DataPoints.DefaultDataPoint.DataLabels.Size = 8;

            //Set the legend position of the chart
            chart.Legend.Position = LegendPositionType.Top;

            //Save the result document
            workbook.SaveToFile("WaterfallChart.xlsx");
        }
    }
} 

C#/VB.NET: Create a Waterfall Chart in Excel

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Create PDF Programmatically Using C#

Creating PDFs in C# is a must-have skill for developers, especially when building apps that generate reports, invoices, or other dynamic documents. Libraries like Spire.PDF for .NET simplify the process by offering tools for adding text, tables, and even converting HTML to PDF—helping you create professional documents with minimal effort.

This guide walks you through C# PDF generation step by step, from basic text formatting to advanced features like HTML rendering and tenplate. By the end, you’ll be able to customize and creaete PDFs for any project.

.NET Library for Creating PDF Documents

Spire.PDF is a powerful and versatile .NET library designed for creating, editing, and manipulating PDF documents programmatically. It provides developers with a comprehensive set of features to generate high-quality PDFs from scratch, modify existing files, and convert various formats into PDF.

Key Features of Spire.PDF

  • PDF Creation & Editing – Build PDFs with text, images, tables, lists, and more.
  • Rich Formatting Options – Customize fonts, colors, alignment, and layouts.
  • HTML to PDF Conversion – Render web pages or HTML content into PDFs with precise formatting.
  • Template-Based PDF Generation – Use placeholders in existing PDFs to dynamically insert text and data.
  • Interactive Elements – Support for forms, annotations, and bookmarks.
  • Document Security – Apply passwords, permissions, and digital signatures.

Installing Spire.PDF

To begin using Spire.PDF to create PDF documents, install it directly through NuGet.

Install-Package Spire.PDF

Alternatively, you can download Spire.PDF from our official website and manually import the DLL in your project.

Creating a PDF File from Scratch in C#

Understanding the Coordinate System

Before delving into the code, it's important to understand the coordinate system used by Spire.PDF. It resembles those in many graphics libraries but has specific PDF considerations. The origin (0,0) is located at the top-left corner of the content area (excluding margins), with positive Y values extending downward.

Understanding this system is essential for accurate element placement when building document layouts.

Coordinate system in Spire.PDF

Note: This coordinate system applies only to newly created pages. In existing PDF pages, the origin is at the top-left corner of the entire page.

Creating a Simple PDF File with Text

Now, let's create our first PDF document. Text content is fundamental to most PDFs, so mastering text handling is crucial.

The following code demonstrates how to create a simple PDF with text in C#:

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

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

            // Add a page
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins(50f));

            // Create brush and font objects
            PdfSolidBrush titleBrush = new PdfSolidBrush(new PdfRGBColor(Color.Blue));
            PdfSolidBrush paraBrush = new PdfSolidBrush(new PdfRGBColor(Color.Black));
            PdfTrueTypeFont titleFont = new PdfTrueTypeFont(new Font("Times New Roman", 18f, FontStyle.Bold), true);
            PdfTrueTypeFont paraFont = new PdfTrueTypeFont(new Font("Times New Roman", 13f, FontStyle.Regular), true);

            // Specify title text
            String titleText = "What's Spire.PDF";

            // Set the text alignment via PdfStringFormat class
            PdfStringFormat format = new PdfStringFormat();
            format.Alignment = PdfTextAlignment.Center;

            // Draw title on the center of the page
            page.Canvas.DrawString(titleText, titleFont, titleBrush, page.Canvas.ClientSize.Width / 2, 20, format);

            // Get paragraph content from a .txt file
            string paraText = "Spire.PDF is a .NET library designed for creating, reading, and manipulating PDF documents." +
                " It offers a wide range of features, including the ability to generate PDF documents from scratch and " +
                "convert various formats into PDF. Users can modify existing PDF files by adding text, images, or annotations, " +
                "and it also supports filling and managing interactive PDF forms. Additionally, Spire.PDF allows for the " +
                "extraction of text and images from PDF documents, as well as converting PDF files into other formats like " +
                "Word, Excel, and images.";

            // Create a PdfTextWidget object to hold the paragrah content
            PdfTextWidget widget = new PdfTextWidget(paraText, paraFont, paraBrush);

            // Create a rectangle where the paragraph content will be placed
            RectangleF rect = new RectangleF(0, 50, page.Canvas.ClientSize.Width, page.Canvas.ClientSize.Height);

            // Set the PdfLayoutType to Paginate to make the content paginated automatically
            PdfTextLayout layout = new PdfTextLayout();
            layout.Layout = PdfLayoutType.Paginate;

            // Draw the widget on the page
            widget.Draw(page, rect, layout);

            // Save the document to file
            doc.SaveToFile("SimpleDocument.pdf");
            doc.Dispose();
        }
    }
}

In this code:

 

  • PdfDocument: Serves as the foundation for creating a PDF, managing its structure and content.
  • PdfPageBase: Adds a page to the document, specifying the A4 size and margins, setting up the drawing canvas.
  • PdfSolidBrush: Defines colors for the title and paragraph text, filling shapes and text.
  • PdfTrueTypeFont: Specifies font type, size, and style for text, creating distinct fonts for the title and paragraph.
  • PdfStringFormat: Used to set text alignment (centered for the title), enhancing presentation.
  • Canvas.DrawString(): Draws the title on the canvas at a specified location using the defined font, brush, and format.
  • PdfTextWidget: Encapsulates the paragraph text, simplifying management and rendering of larger text blocks.
  • PdfTextLayout: Configured for automatic pagination, ensuring text flows correctly to the next page if it exceeds the current one.
  • PdfTextWidget.Draw(): Renders the paragraph within a specified rectangle on the page.
  • SaveToFile(): Saves the document to the specified file path, completing the PDF creation process.

 

Output:

Output PDF document containing text only.

Enhancing Your PDF with Rich Elements

While text forms the foundation of most documents, professional PDFs often require richer content types to effectively communicate information. This section explores how to elevate your documents by incorporating images, tables, and lists.

1. Inserting an Image to PDF

Spire.PDF provides the PdfImage class to load and manage various image formats. You can position the image using the coordinate system discussed earlier with the DrawImage method.

// Load an image
PdfImage image = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\ai.png"); 

// Specify the X and Y coordinates to start drawing the image
float x = 0f;
float y = 0f;

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

2. Creating a Table in PDF

Spire.PDF provides the PdfTable class for creating and managing tables in a PDF document. You can populate the table with a DataTable and customize its appearance using various interfaces within PdfTable. Finally, the table is rendered on the page using the Draw method.

// Create a PdfTable
PdfTable table = new PdfTable();

// Create a DataTable
DataTable dataTable = new DataTable();
dataTable.Columns.Add("Name");
dataTable.Columns.Add("Age");
dataTable.Columns.Add("Deparment");
dataTable.Rows.Add(new object[] { "David", "35", "Development" });
dataTable.Rows.Add(new object[] { "Sophie", "32", "Support" });
dataTable.Rows.Add(new object[] { "Wayne", "28", "Marketing" });

// Show header (invisible by default)
table.Style.ShowHeader = true;

//Set font color and backgroud color of header row
table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.Gray;
table.Style.HeaderStyle.TextBrush = PdfBrushes.White;

// Assign data source
table.DataSource = dataTable;

//Set text alignment in header row
table.Style.HeaderStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);

//Set text alignment in other cells
for (int i = 0; i < table.Columns.Count; i++)
{
    table.Columns[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
}

// Draw table on the page
table.Draw(page, new RectangleF(0, 150, 300, 150));

In addition to PdfTable, Spire.PDF offers the PdfGrid class, making it easier to create and manage complex tables in PDF documents. For detailed instruction, check this guide: Generate Tables in PDF Using C#.

3. Adding a List to PDF

The PdfSortedList class in Spire.PDF enables the creation of ordered lists with various numbering styles. You can specify the list content as a string and customize its appearance by adjusting properties such as font, indent, and text indent. The list is then rendered on the page using the Draw method at a specified location.

// Create a font
PdfFont listFont = new PdfFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Regular);

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

//Create a numbered list
String listContent = "Data Structure\n"
        + "Algorithm\n"
        + "Computer Networks\n"
        + "Operating System\n"
        + "Theory of Computations";
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.Marker = marker;

//Draw list on the page at the specified location
list.Draw(page, 310, 125);

Output:

Below is a screenshot of the PDF file created by the code snippets in this section:

Output PDF document containing an image, a table and a list.

In addition to the mentioned elements, Spire.PDF supports the addition of nearly all common elements to PDFs. For more documentation, refer to the Spire.PDF Programming Guide.

Creating PDF from HTML in C#

In modern applications, it's increasingly common to need conversion of HTML content to PDF format—whether for web page archiving, report generation, or creating printable versions of web content.

Spire.PDF addresses this need through its HTML conversion capabilities, which leverage Chrome's rendering engine for exceptional fidelity. This approach ensures that your PDF output closely matches how the content appears in web browsers, including support for modern CSS features.

The conversion process is highly configurable, allowing you to control aspects like page size , margins , and timeout settings to accommodate various content types and network conditions.

Here's an exmaple demonstrating how to create PDF from HTML in C#:

using Spire.Additions.Chrome;

namespace ConvertHtmlToPdf
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Specify the input URL and output PDF file path
            string inputUrl = @"C:\Users\Administrator\Desktop\Html.html";
            string outputFile = @"HtmlToPDF.pdf";

            // Specify the path to the Chrome plugin
            string chromeLocation = @"C:\Program Files\Google\Chrome\Application\chrome.exe";

            // Create an instance of the ChromeHtmlConverter class
            ChromeHtmlConverter converter = new ChromeHtmlConverter(chromeLocation);

            // Create an instance of the ConvertOptions class
            ConvertOptions options = new ConvertOptions();
            options.Timeout = 10 * 3000;

            // Set paper size and page margins of the converted PDF
            options.PageSettings = new PageSettings()
            {
                PaperWidth = 8.27,
                PaperHeight = 11.69,
                MarginTop = 0,
                MarginLeft = 0,
                MarginRight = 0,
                MarginBottom = 0
            };

            //Convert the URL to PDF
            converter.ConvertToPdf(inputUrl, outputFile, options);
        }
    }
}

Output:

A screenshot of the input HTML file and output PDF file.

Creating PDF Based on Template in C#

Template-based PDF generation enhances maintainability and consistency in enterprise applications. Spire.PDF supports this with text replacement functionality, allowing the creation of master templates with placeholders filled at runtime. This separation enables non-technical users to update templates easily.

The PdfTextReplacer class facilitates replacements, including automatic text resizing to fit designated spaces, making it ideal for documents like contracts, certificates, or forms with a constant layout.

The following code demonstrates how to create a PDF file based on a predefined template in C#:

using Spire.Pdf;
using Spire.Pdf.Texts;

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

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

            // Create a PdfTextReplaceOptions object and specify the options
            PdfTextReplaceOptions textReplaceOptions = new PdfTextReplaceOptions
            {
                ReplaceType = PdfTextReplaceOptions.ReplaceActionType.AutofitWidth | PdfTextReplaceOptions.ReplaceActionType.WholeWord
            };

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

            // Create a PdfTextReplacer object based on the page
            PdfTextReplacer textReplacer = new PdfTextReplacer(page)
            {
                Options = textReplaceOptions
            };

            // Dictionary for old and new strings
            Dictionary<string, string> replacements = new Dictionary<string, string>
            {
                { "#name#", "John Doe" },
                { "#gender#", "Male" },
                { "#birthdate#", "January 15, 1990" },
                { "#address#", "123 Main St, Springfield, IL, 62701" }
            };

            // Loop through the dictionary to replace text
            foreach (var pair in replacements)
            {
                textReplacer.ReplaceText(pair.Key, pair.Value);
            }

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

Output:

A screenshot of the input template file and output PDF document.

Conclusion

The ability to create and manipulate PDF documents in C# is an invaluable skill for developers, especially in today's data-driven environment. This guide has covered various methods for generating PDFs, including creating documents from scratch, converting HTML to PDF, and utilizing templates for dynamic content generation.

With the robust features of Spire.PDF, developers can produce professional-quality PDFs that meet diverse requirements, from simple reports to complex forms. Dive into the world of PDF generation with Spire.PDF and unlock endless possibilities for your projects.

FAQs

Q1. What is the best library for creating PDFs in C#?

Spire.PDF is highly recommended due to its extensive feature set, user-friendly interface, and support for advanced operations like HTML-to-PDF conversion. It allows developers to easily create, manipulate, and customize PDF documents to meet a variety of needs.

Q2. Can I create PDF files in C# without external libraries?

While .NET has limited built-in capabilities, libraries like Spire.PDF are essential for complex tasks like adding tables or images.

Q3. How do I generate a PDF from HTML in C#?

Spire.PDF’s integration with Chrome allows for seamless conversion of HTML to PDF. You can customize page settings, such as margins and orientation, ensuring that the output PDF maintains the desired formatting and layout of the original HTML content.

Q4. How do I protect my PDF with passwords or permissions?

Spire.PDF offers robust encryption options through the PdfSecurityPolicy class. You can set owner and user passwords to restrict access, as well as define permissions for printing, copying, and editing the PDF. For more details, refer to: Encrypt or Decrypt PDF Files in C# .NET

Q5. Can I create PDF files from Word and Excel using Spire.PDF?

No, you cannot convert Word or Excel files directly with Spire.PDF. For Word to PDF conversion, use Spire.Doc, and for Excel to PDF, use Spire.XLS.

Get a Free License

To fully experience the capabilities of Spire.PDF for .NET without any evaluation limitations, you can request a free 30-day trial license.

Lists are used in Word documents to outline, arrange, and emphasize text, making it easy for users to scan and understand a series of items. There are three different types of lists in Word, namely numbered lists, bulleted lists and multi-level lists. Numbered lists are used for items that have a sequence or priority, such as a series of instructions. Bulleted lists are used for items that have no particular priority, such as a list of functions or facts. Multi-level lists are used where there is a sequence and you want each paragraph numbered separately.

In this article, you will learn how to insert these types of lists into a Word document in C# and VB.NET using Spire.Doc for .NET.

Install Spire.Doc for .NET

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

PM> Install-Package Spire.Doc

Insert a Numbered List in Word in C#, VB.NET

Spire.Doc for .NET offers the ListStyle class that you can use to create a numbered list style or a bulleted style. Then, the list style can be applied to a paragraph using Paragraph.ListFormat.ApplyStyle() method. The steps to create a numbered list are as follows.

  • Create a Document object.
  • Add a section using Document.AddSection() method.
  • Create an instance of ListStyle class, specifying the list type to Numbered.
  • Get a specific level of the list through ListStyle.Levels[index] property, and set the numbering type through ListLevel.PatternType property.
  • Add the list style to the document using Document.ListStyles.Add() method.
  • Add several paragraphs to the document using Section.AddParagraph() method.
  • Apply the list style to a specific paragraph using Paragraph.ListFormat.ApplyStyle() method.
  • Specify the list level through Paragraph.ListFormat.ListLevelNumber property.
  • Save the document to a Word file using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;

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

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

            //Create a numbered list style
            ListStyle listStyle = document.Styles.Add(ListType.Numbered, "numberedList");
            listStyle.Name = "numberedList";
            listStyle.ListRef.Levels[0].PatternType = ListPatternType.DecimalEnclosedParen;
            listStyle.ListRef.Levels[0].TextPosition = 20;

            //Add a paragraph
            Paragraph paragraph = section.AddParagraph();
            paragraph.AppendText("Required Web Development Skills:");
            paragraph.Format.AfterSpacing = 5f;

            //Add a paragraph and apply the numbered list style to it
            paragraph = section.AddParagraph();
            paragraph.AppendText("HTML");
            paragraph.ListFormat.ApplyStyle("numberedList");
            paragraph.ListFormat.ListLevelNumber = 0;

            //Add another four paragraphs and apply the numbered list style to them
            paragraph = section.AddParagraph();
            paragraph.AppendText("CSS");
            paragraph.ListFormat.ApplyStyle("numberedList");
            paragraph.ListFormat.ListLevelNumber = 0;

            paragraph = section.AddParagraph();
            paragraph.AppendText("JavaScript");
            paragraph.ListFormat.ApplyStyle("numberedList");
            paragraph.ListFormat.ListLevelNumber = 0;

            paragraph = section.AddParagraph();
            paragraph.AppendText("Python");
            paragraph.ListFormat.ApplyStyle("numberedList");
            paragraph.ListFormat.ListLevelNumber = 0;

            paragraph = section.AddParagraph();
            paragraph.AppendText("MySQL");
            paragraph.ListFormat.ApplyStyle("numberedList");
            paragraph.ListFormat.ListLevelNumber = 0;

            //Save the document to file
            document.SaveToFile("NumberedList.docx", FileFormat.Docx);
        }
    }
}

C#/VB.NET: Insert Lists in a Word Document

Insert a Bulleted List in Word in C#, VB.NET

The process of creating a bulleted list is similar to that of creating a numbered list. The difference is that when creating a list style, you must specify the list type as Bulleted and set a bullet symbol for it. The following are the detailed steps.

  • Create a Document object.
  • Add a section using Document.AddSection() method.
  • Create an instance of ListStyle class, specifying the list type to Bulleted.
  • Get a specific level of the list through ListStyle.Levels[index] property, and set the bullet symbol through ListLevel.BulletCharacter property.
  • Add the list style to the document using Document.ListStyles.Add() method.
  • Add several paragraphs to the document using Section.AddParagraph() method.
  • Apply the list style to a specific paragraph using Paragraph.ListFormat.ApplyStyle() method.
  • Specify the list level through Paragraph.ListFormat.ListLevelNumber property.
  • Save the document to a Word file using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;

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

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

            //Create a bulleted list style
            ListStyle listStyle = document.Styles.Add( ListType.Bulleted, "bulletedList");
            listStyle.Name = "bulletedList";
            listStyle.ListRef.Levels[0].BulletCharacter = "\x00B7";
            listStyle.ListRef.Levels[0].CharacterFormat.FontName = "Symbol";
            listStyle.ListRef.Levels[0].TextPosition = 20;

            //Add a paragraph
            Paragraph paragraph = section.AddParagraph();
            paragraph.AppendText("Computer Science Subjects:");
            paragraph.Format.AfterSpacing = 5f;

            //Add a paragraph and apply the bulleted list style to it
            paragraph = section.AddParagraph();
            paragraph.AppendText("Data Structure");
            paragraph.ListFormat.ApplyStyle("bulletedList");
            paragraph.ListFormat.ListLevelNumber = 0;

            //Add another five paragraphs and apply the bulleted list style to them
            paragraph = section.AddParagraph();
            paragraph.AppendText("Algorithm");
            paragraph.ListFormat.ApplyStyle("bulletedList");
            paragraph.ListFormat.ListLevelNumber = 0;

            paragraph = section.AddParagraph();
            paragraph.AppendText("Computer Networks");
            paragraph.ListFormat.ApplyStyle("bulletedList");
            paragraph.ListFormat.ListLevelNumber = 0;

            paragraph = section.AddParagraph();
            paragraph.AppendText("Operating System");
            paragraph.ListFormat.ApplyStyle("bulletedList");
            paragraph.ListFormat.ListLevelNumber = 0;

            paragraph = section.AddParagraph();
            paragraph.AppendText("C Programming");
            paragraph.ListFormat.ApplyStyle("bulletedList");
            paragraph.ListFormat.ListLevelNumber = 0;

            paragraph = section.AddParagraph();
            paragraph.AppendText("Theory of Computations");
            paragraph.ListFormat.ApplyStyle("bulletedList");
            paragraph.ListFormat.ListLevelNumber = 0;

            //Save the document to file
            document.SaveToFile("BulletedList.docx", FileFormat.Docx);
        }
    }
}

C#/VB.NET: Insert Lists in a Word Document

Insert a Multi-Level Numbered List in Word in C#, VB.NET

A multi-level list consists of at least two different levels. Each level of a nested list is represented by the ListStyle.Levels[index] property, through which you can set the numbering type and prefix for a certain level. The following are the steps to create a multi-level numbered list in Word.

  • Create a Document object.
  • Add a section using Document.AddSection() method.
  • Create an instance of ListStyle class, specifying the list type to Numbered.
  • Get a specific level of the list through ListStyle.Levels[index] property, and set the numbering type and prefix.
  • Add the list style to the document using Document.ListStyles.Add() method.
  • Add several paragraphs to the document using Section.AddParagraph() method.
  • Apply the list style to a specific paragraph using Paragraph.ListFormat.ApplyStyle() method.
  • Specify the list level through Paragraph.ListFormat.ListLevelNumber property.
  • Save the document to a Word file using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;

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

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

            //Create a numbered list style, specifying number prefix and pattern type of each level
            ListStyle listStyle = document.Styles.Add(ListType.Numbered, "levelstyle");
            listStyle.Name = "levelstyle";
            listStyle.ListRef.Levels[0].PatternType = ListPatternType.Arabic;
            listStyle.ListRef.Levels[0].TextPosition = 20;
            listStyle.ListRef.Levels[1].NumberPrefix = "\x0000.";
            listStyle.ListRef.Levels[1].PatternType = ListPatternType.Arabic;
            listStyle.ListRef.Levels[2].NumberPrefix = "\x0000.\x0001.";
            listStyle.ListRef.Levels[2].PatternType = ListPatternType.Arabic;

            //Add a paragraph
            Paragraph paragraph = section.AddParagraph();
            paragraph.AppendText("Here's a Multi-Level Numbered List:");
            paragraph.Format.AfterSpacing = 5f;

            //Add a paragraph and apply the numbered list style to it
            paragraph = section.AddParagraph();
            paragraph.AppendText("The first item");
            paragraph.ListFormat.ApplyStyle("levelstyle");
            paragraph.ListFormat.ListLevelNumber = 0;

            //Add another five paragraphs and apply the numbered list stype to them
            paragraph = section.AddParagraph();
            paragraph.AppendText("The second item");
            paragraph.ListFormat.ApplyStyle("levelstyle");
            paragraph.ListFormat.ListLevelNumber = 0;

            paragraph = section.AddParagraph();
            paragraph.AppendText("The first sub-item");
            paragraph.ListFormat.ApplyStyle("levelstyle");
            paragraph.ListFormat.ListLevelNumber = 1;

            paragraph = section.AddParagraph();
            paragraph.AppendText("The second sub-item");
            paragraph.ListFormat.ContinueListNumbering();
            paragraph.ListFormat.ApplyStyle("levelstyle");

            paragraph = section.AddParagraph();
            paragraph.AppendText("A sub-sub-item");
            paragraph.ListFormat.ApplyStyle("levelstyle");
            paragraph.ListFormat.ListLevelNumber = 2;

            paragraph = section.AddParagraph();
            paragraph.AppendText("The third item");
            paragraph.ListFormat.ApplyStyle("levelstyle");
            paragraph.ListFormat.ListLevelNumber = 0;

            //Save the document to file
            document.SaveToFile("MultilevelNumberedList.docx", FileFormat.Docx);
        }
    }
}

C#/VB.NET: Insert Lists in a Word Document

Insert a Multi-Level Mixed-Type List in Word in C#, VB.NET

In some cases, you may want to mix number and symbol bullet points in a multi-level list. To create a mixed-type list, you just need to create a numbered list style and a bulleted list style and apply them to different paragraphs. The detailed steps are as follows.

  • Create a Document object.
  • Add a section using Document.AddSection() method.
  • Create a numbered list style and a bulleted list style.
  • Add several paragraphs to the document using Section.AddParagraph() method.
  • Apply different list style to different paragraphs using Paragraph.ListFormat.ApplyStyle() method.
  • Save the document to a Word file using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;

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

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

            //Create a numbered list style
            ListStyle numberedListStyle = document.Styles.Add(ListType.Numbered, "numberedStyle");
            numberedListStyle.ListRef.Levels[0].PatternType = ListPatternType.Arabic;
            numberedListStyle.ListRef.Levels[0].TextPosition = 20;
            numberedListStyle.ListRef.Levels[1].PatternType = ListPatternType.LowLetter;
            
            //Create a bulleted list style
            ListStyle bulletedListStyle = document.Styles.Add(ListType.Bulleted, "bulltedStyle"); 
            bulletedListStyle.Name = "bulltedStyle";
            bulletedListStyle.ListRef.Levels[2].BulletCharacter = "\x002A";
            bulletedListStyle.ListRef.Levels[2].CharacterFormat.FontName = "Symbol";

            //Add a paragraph
            Paragraph paragraph = section.AddParagraph();
            paragraph.AppendText("Here's a Multi-Level Mixed List:");
            paragraph.Format.AfterSpacing = 5f;

            //Add a paragraph and apply the numbered list style to it
            paragraph = section.AddParagraph();
            paragraph.AppendText("The first item");
            paragraph.ListFormat.ApplyStyle("numberedStyle");
            paragraph.ListFormat.ListLevelNumber = 0;

            //Add another five paragraphs and apply different list stype to them
            paragraph = section.AddParagraph();
            paragraph.AppendText("The first sub-item");
            paragraph.ListFormat.ApplyStyle("numberedStyle");
            paragraph.ListFormat.ListLevelNumber = 1;

            paragraph = section.AddParagraph();
            paragraph.AppendText("The second sub-item");
            paragraph.ListFormat.ListLevelNumber = 1;
            paragraph.ListFormat.ApplyStyle("numberedStyle");

            paragraph = section.AddParagraph();
            paragraph.AppendText("The first sub-sub-item");
            paragraph.ListFormat.ApplyStyle("bulltedStyle");
            paragraph.ListFormat.ListLevelNumber = 2;

            paragraph = section.AddParagraph();
            paragraph.AppendText("The second sub-sub-item");
            paragraph.ListFormat.ApplyStyle("bulltedStyle");
            paragraph.ListFormat.ListLevelNumber = 2;

            paragraph = section.AddParagraph();
            paragraph.AppendText("The second item");
            paragraph.ListFormat.ApplyStyle("numberedStyle");
            paragraph.ListFormat.ListLevelNumber = 0;

            //Save the document to file
            document.SaveToFile("MultilevelMixedList.docx", FileFormat.Docx);
        }
    }
}

C#/VB.NET: Insert Lists in a Word 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.

PDF margins are blank areas between content and page edges. In most cases, we set moderate or narrow margins in order to create a compact appearance. However, if we wish to place a company logo or other relevant information in the margins, we need to make the margins a bit wider. In this article, you will learn how to increase or decrease the margins of an existing PDF document 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 DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Increase the Margins of a PDF Document in C#, VB.NET

The way to enlarge the margins of a PDF document is to create a new PDF that has a larger page size, and then draw the source page on the large page at the appropriate location. The following are the steps to increase the margins of a PDF document using Spire.PDF for .NET.

  • Load the original PDF document while initialing the PdfDocument object.
  • Create another PdfDocument object, which is used to create a new PDF document that has a larger page size.
  • Set the increasing values of the margins.
  • Calculate the page size of the new PDF document.
  • Loop through the pages in the original document, and create a template based on a specific page using PdfPageBase.CreateTemplate() method.
  • Add a page to the new PDF document using PdfDocument.Pages.Add() method.
  • Draw the template on the page at the coordinate (0, 0) using PdfTemplate.Draw() method.
  • Save the new PDF document to file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace IncreaseMargins
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load the original PDF document
            PdfDocument originalPdf = new PdfDocument("C:\\Users\\Administrator\\Desktop\\sample.pdf");

            //Get the first page
            PdfPageBase firstPage = originalPdf.Pages[0];

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

            //Set increasing value of the margins
            PdfMargins margins = newPdf.PageSettings.Margins;
            margins.Top = 40;
            margins.Bottom=40;
            margins.Left=40;
            margins.Right= 40;

            //Calculate the new page size
            SizeF sizeF = new SizeF(firstPage.Size.Width + margins.Left + margins.Right, firstPage.Size.Height + margins.Top + margins.Bottom);

            //Loop through the pages in the original document
            for (int i = 0; i < originalPdf.Pages.Count; i++)
            {
                //Create a template based on a spcific page
                PdfTemplate pdfTemplate = originalPdf.Pages[i].CreateTemplate();

                //Add a page to the new PDF
                PdfPageBase page = newPdf.Pages.Add(sizeF);

                //Draw template on the page
                pdfTemplate.Draw(page, 0, 0);
            }

            //Save the new document
            newPdf.SaveToFile("IncreaseMargins.pdf", FileFormat.PDF);
        }
    }
}

C#/VB.NET: Adjust the Margins of a PDF Document

Decrease the Margins of a PDF Document in C#, VB.NET

The way to decrease the margins of a PDF is to create a new PDF that has a smaller page size, and then draw the source page on the small page at a specified coordinate. The following are the steps to decrease the margins of a PDF document using Spire.PDF for .NET.

  • Load the original PDF document while initialing the PdfDocument object.
  • Create another PdfDocument object, which is used to create a new PDF document that has a smaller page size.
  • Set the decreasing values of the margins.
  • Calculate the page size of the new PDF document.
  • Loop through the pages in the original document, and create a template based on a specific page using PdfPageBase.CreateTemplate() method.
  • Add a page to the new PDF document using PdfDocument.Pages.Add() method.
  • Draw the template on the page at a specified coordinate using PdfTemplate.Draw() method.
  • Save the new PDF document to file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace DecreaseMargins
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load the original PDF document
            PdfDocument originalPdf = new PdfDocument("C:\\Users\\Administrator\\Desktop\\sample.pdf");

            //Get the first page
            PdfPageBase firstPage = originalPdf.Pages[0]; 

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

            //Set decreasing value
            float left = -20;
            float right = -20;
            float top = -20;
            float bottom = -20;

            //Calculate the new page size
            SizeF sizeF = new SizeF(firstPage.Size.Width + left + right, firstPage.Size.Height + top + bottom);

            //Loop through the pages in the original document
            for (int i = 0; i < originalPdf.Pages.Count; i++)
            {
                //Create a template based on a specific page
                PdfTemplate pdfTemplate = originalPdf.Pages[i].CreateTemplate();

                //Add a page to the new PDF
                PdfPageBase page = newPdf.Pages.Add(sizeF, new PdfMargins(0));

                //Draw template on the page
                pdfTemplate.Draw(page, left, top);
            }

            //Save the new document
            newPdf.SaveToFile("DecreaseMargins.pdf", FileFormat.PDF);
        }
    }
}

C#/VB.NET: Adjust the Margins of 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.OCR for .NET is a professional OCR library that supports recognizing text from Images (such as JPG, PNG, GIF, BMP, and TIFF) in both .NET Framework and .NET Core applications. In this article, we will explain how to use Spire.OCR for .NET to read text from images in .NET Framework applications.

Step 1: Create a console application (.NET Framework) in Visual Studio.

How to use Spire.OCR in .NET Framework Applications

How to use Spire.OCR in .NET Framework Applications

Step 2: Change the platform target of the application to X64.

In the application's solution explorer, right-click on the solution name and then click "Properties".

How to use Spire.OCR in .NET Framework Applications

Change the platform target of the application to X64. This step must be performed since Spire.OCR only supports 64-bit platforms.

How to use Spire.OCR in .NET Framework Applications

Step 3: Add a reference to Spire.OCR for .NET DLL in the application.

We recommend installing Spire.OCR for .NET through NuGet (Note: only Spire.OCR for .NET Version 1.8.0 or above supports working with .NET Framework). The detailed steps are as follows:

  • In the application's solution explorer, right-click on the solution name or "References" and select "Manage NuGet Packages".
  • Click the "Browse" tab and search for Spire.OCR.
  • Click "Install" to install Spire.OCR.

How to use Spire.OCR in .NET Framework Applications

Step 4: Copy DLLs from the "packages" directory to the "Debug" directory in the application.

When you install Spire.OCR through NuGet, NuGet downloads the packages and puts them in your application under a directory called "packages". You need to find the "Spire.OCR" directory under the "packages" directory, then copy the DLLs under the "Spire.OCR" directory (packages\Spire.OCR.1.8.0\runtimes\win-x64\native) to the "Debug" directory of your application.

How to use Spire.OCR in .NET Framework Applications

Now you have successfully included Spire.OCR in your .NET Framework application. You can refer to the following code example to read text from images using Spire.OCR.

  • C#
using Spire.OCR;
using System.IO;

namespace OcrImage
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Create an instance of the OcrScanner class
            OcrScanner scanner = new OcrScanner();

            //Call the OcrScanner.Scan() method to scan text from an image
            scanner.Scan("image.png");

            //Save the scanned text to a .txt file
            string text = scanner.Text.ToString();            
            File.WriteAllText("output.txt", text);
        }
    }
}

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Page 7 of 95
page 7