PDF Quick Start for WPF

2012-05-31 08:48:18 Written by Koohji

The sample demonstrates how to get started with Spire.PDF for WPF.

 

This article is designed to give you a detailed description about how to write a "HelloWorld" demo of Spire.XLS for WPF by Visual Studio. You can follow the below procedure step by step to finish this task. But first of all, please make sure that Spire.XLS for WPF and Visual Studio 2010 are correctly installed on system.

Step 1. Create a new project.

1. Create a new project by choosing WPF Application in Visual Studio and name the project "HelloWorld". If you want to create a C# project, select Visual C#, WPF Application, if you want to build a Visual Basic project, please choose Visual Basic, WPF Application. The detail process is:

Click File → NewProjectWPF ApplicationNameOK

2. Set the Target framework property of the HelloWorld project in Solution Explorer to be .NET Framework 4.The process is:

Click Solution Explorer-> HelloWorld (The project that you already built) -> Properties (right click HelloWorld)->Target framework->.NET Framework 4

3. Add a button in MainWindow. The default button name is "button1". You can set button1 Content property to be "Run" in its properties by right clicking it. Thus, it shows "Run" in the MainWindow. You can perform as below:

Click ViewToolboxButtonProperties (right click button1)Contentset the Content to be "Run"

Step 2. Add reference and project namespaces.

1. Add Spire.XLS. Wpf.dll as reference in Project. The Default location of Spire.Doc for WPF is “C:\Program Files\e-iceblue\Spire.XLS for WPF”. Details are:

Click ProjectAdd ReferenceBrowseChoose the folder contains Spire.XLS for WPFBinWPF 4.0Spire.XLS.Wpf.dll

2. Double click the "Run" button, you can see the following method has been added automatically:

[C#]
namespace HelloWorld
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
        }
    }
}
[VB.NET]
Namespace HelloWorld
	''' 
	''' Interaction logic for MainWindow.xaml
	''' 
	Public Partial Class MainWindow
		Inherits Window
		Public Sub New()
			InitializeComponent()
		End Sub

		Private Sub button1_Click(sender As Object, e As RoutedEventArgs)
                           End Sub
	 End Class
End Namespace

3. Add the below namespaces at the top of the method.

[C#]
using Spire.Xls;
[VB.NET]
Imports Spire.Xls

Step 3. Write "Hello, World!" in the method.

Add the following code to the method button1_click

[C#]
           //create a new excel workbook
            Workbook workbook = new Workbook();

            //edit the first worksheet of the workbook
            Worksheet sheet = workbook.Worksheets[0];
            sheet.Range["A1"].Text = "Hello, World!";

            //save the workbook
            workbook.SaveToFile(@"..\..\sample.xls", ExcelVersion.Version97to2003);

            //launch the workbook
            System.Diagnostics.Process.Start(@"..\..\sample.xls");
[VB.NET]
	  'create a new excel workbook
	   Dim workbook As New Workbook()

	  'edit the first worksheet of the workbook
	   Dim sheet As Worksheet = workbook.Worksheets(0)
	   sheet.Range("A1").Text = "Hello, World!"

	   'save the workbook
	    workbook.SaveToFile("..\..\sample.xls", ExcelVersion.Version97to2003)

	   'launch the workbook
	    System.Diagnostics.Process.Start("..\..\sample.xls")

Step 4. Debug the project

Right click the project HelloWorld in Solution Explorer  Debug  Start new instance  Click Run in MainWindow, an Excel Document will be created, edited and opened. The string "Hello, World!" is drawn in the first cell A1 of sheet 1.

Preview

This document aims at clearly introducing a simple “HelloWorld” demo about Spire.Doc for WPF by using Visual Studio. The below procedure will help you realize this task step by step. Before getting started, please make sure that Spire.Doc for WPF and Visual Studio are correctly installed on system.

Step 1. Create a new project.

1. Create a new project by choosing WPF Application in Visual Studio and name the project "HelloWorld". If you want to create a C# project, select Visual C#, WPF Application, if you want to build a Visual Basic project, please choose Visual Basic, WPF Application. The detail process is:

Click File → NewProjectWPF ApplicationNameOK

2. Set the Target framework property of the HelloWorld project in Solution Explorer to be .NET Framework 4.The process is:

Click Solution ExplorerHelloWorld (The project that you already built)Properties(right click HelloWorld)Target framework.NET Framework 4

3. Add a button in MainWindow. The default button name is "button1". You can set button1 Content property to be "Run" in its properties by right clicking it. Thus, it shows "Run" in the MainWindow. You can perform as below:

Click ViewToolboxButtonProperties (right click button1)Contentset the Content to be "Run"

Step 2. Add reference and project namespaces.

1. Add Spire.Doc. Wpf.dll as reference in Project. The Default location of Spire.Doc for WPF is “C:\Program Files\e-iceblue\Spire.Doc for WPF”. Details are:

Click ProjectAdd ReferenceBrowseChoose the folder contains Spire.Doc for WPFBinWPF 4.0Spire.Doc.Wpf.dll

2. Double click the "Run" button, you can see the following method has been added automatically:

[C#]
namespace HelloWorld
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

private void button1_Click(object sender, RoutedEventArgs e)
        {
        }
    }
}
[VB.NET]
Namespace HelloWorld
	''' 
	''' Interaction logic for MainWindow.xaml
	''' 
	Public Partial Class MainWindow
		Inherits Window
		Public Sub New()
			InitializeComponent()
		End Sub

		Private Sub button1_Click(sender As Object, e As RoutedEventArgs)
                End Sub
	End Class
End Namespace

3. Add the below namespaces at the top of the method.

[C#]
using Spire.Doc;
using Spire.Doc.Documents;
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents

Step 3. Write "Hello, World!” in the method.

Add the following code to the method button1_click

[C#]
            //create a new document using spire.Doc
            Document document = new Document();

            //add one paragraph 
            Paragraph paragraph = document.AddSection().AddParagraph();
            paragraph.AppendText("Hello, World!");

            //save the document
            document.SaveToFile(@"..\..\sample.doc", FileFormat.Doc);

            //launch the document
            System.Diagnostics.Process.Start(@"..\..\sample.doc");
[VB.NET]
	  'create a new document using spire.Doc
	   Dim document As New Document()

	  'add one paragraph 
	   Dim paragraph As Paragraph = document.AddSection().AddParagraph()
	   paragraph.AppendText("Hello, World!")

	  'save the document
	   document.SaveToFile("..\..\sample.doc", FileFormat.Doc)

	   'launch the document
	   System.Diagnostics.Process.Start("..\..\sample.doc")

Step 4. Debug the project

Right click the project HelloWorld in Solution ExplorerDebug-> Start new instanceClick Run in MainWindow, a Word Document will be created, edited and opened. The string “Hello, World!” is drawn in the first line of page1.

Preview

How to Add Watermarks to PDF in C# .NET

2021-12-14 09:14:00 Written by Koohji

Add watermarks to PDF in C#

Adding watermarks to PDF documents is a common requirement for protecting sensitive information, indicating document status, or branding files. Watermarks can enhance the security of your documents by discouraging unauthorized copying or distribution. In this article, we'll explore how to add text watermarks to PDFs in C# using Spire.PDF for .NET, a powerful library designed for PDF manipulation.

Getting Started with Spire.PDF for .NET

Spire.PDF for .NET is a robust API that allows developers to create, edit, and manipulate PDF documents programmatically. It supports a wide range of features, including:

  • PDF generation and conversion
  • Text and image extraction
  • Digital signatures
  • Watermarking

Before proceeding, ensure you have installed the Spire.PDF NuGet package. You can install it via the NuGet Package Manager in Visual Studio:

Install-Package Spire.PDF

Alternatively, download it from our official website and reference the DLL file mannually.

Understanding the Coordinate System

Before writing code, it's crucial to understand how PDFs handle coordinates. In Spire.PDF:

  • The origin (0, 0) is at the top-left corner of the page.
  • The X-axis increases from left to right.
  • The Y-axis increases from top to bottom.
  • Measurements are in points (72 points = 1inch).

This coordinate system is essential when positioning watermarks, text, or images on a PDF page.

 Coordinate System in Spire.PDF

Step-by-Step Guide: Adding a Text Watermark to PDF in C#

Let’s break down the process of adding a watermark to a PDF document using Spire.PDF.

Step 1: Import Namespaces

First, include the necessary namespaces. These namespaces provide the essential classes needed for PDF manipulation and graphics rendering, enabling you to work with PDF files in your C# application.

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

Step 2: Load the PDF Document

This step involves initializing a new PdfDocument object and loading the PDF file you want to modify, making it ready for further operations.

PdfDocument doc = new PdfDocument();
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf");

Step 3: Customize a Function to Add Watermaks

Define a helper function to apply a watermark to a single page. This function is designed to position and draw the watermark text on the page, ensuring it is centered and visually appealing, while also applying transparency for a subtle effect.

private static void AddWatermark(PdfPageBase page, string watermarkText, PdfTrueTypeFont font, PdfBrush brush, float opacity)
{
    page.Canvas.SetTransparency(opacity);
    SizeF textSize = font.MeasureString(watermarkText);
    float pageWidth = page.ActualSize.Width;
    float pageHeight = page.ActualSize.Height;
    float x = (pageWidth - textSize.Width) / 2;
    float y = (pageHeight - textSize.Height) / 2;
    page.Canvas.DrawString(watermarkText, font, brush, x, y);
}

Step 4: Apply the Watermark to All Pages

In this step, you set up the font, color, and opacity for the watermark. The loop iterates through each page in the document, applying the watermark consistently across all pages.

PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial Black", 50f), true);
PdfBrush brush = PdfBrushes.Blue;
string watermarkText = "DO NOT COPY";
float opacify = 0.6f;
foreach (PdfPageBase page in doc.Pages)
{
    AddWatermark(page, watermarkText, font, brush, opacify);
}

Step 5: Save the Modifyed PDF

Finally, save the document under a new filename, ensuring that your watermark is preserved in the final output.

doc.SaveToFile("Watermark.pdf");

Result:

 The output PDF displaying a semi-transparent

Conclusion

Adding watermarks to PDFs in C# is straightforward with Spire.PDF for .NET . By understanding the coordinate system and using the library’s drawing capabilities, you can customize watermarks with different fonts, colors, and transparency levels. This method is useful for document security, branding, or marking drafts.

FAQs:

Q1. How do I rotate the watermark?

To add a diagonal watermark to a PDF in C#, you can rotate the coordinate system before drawing the text. Here is the code for your reference:

page.Canvas.RotateTransform(-45);
page.Canvas.DrawString(watermarkText, font, brush, x, y);

Q2. How can I adjust the watermark position?

Change the x and y values in DrawString() to reposition the watermark.

Q3. Can I add an image watermark instead of text?

Yes, you can add an image watermark instead of text. Use PdfPage.Canvas.DrawImage() for rendering the image directly on the page. Alternatively, set a background image for each page using the PdfPageBase.BackgroundImage property.

Q4: How do I add handwritten text to a PDF?

You can create an image of your handwritten text, and then draw it on each page as an image watermark.

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.

C#/VB.NET: Create a Pivot Table in Excel

2022-07-06 08:28:00 Written by Koohji

Pivot table is a kind of interactive table that is capable of quickly calculating, summarizing and analyzing large amounts of data. As one of the most powerful tools in Excel, it enables users to view static data from different perspectives, and also makes the comparisons between data more intuitive. In this article, you will learn how to programmatically create a pivot table in Excel 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 Pivot Table in Excel

The detailed steps are as follows.

  • Create a Workbook object.
  • Load a sample Excel document using Workbook.LoadFromFile() method.
  • Get a specified worksheet using Workbook.Worksheets[] property.
  • Select the data source range using Worksheet.Range[] property, and then create a PivotCache to save the data information using Workbook.PivotCaches.Add (CellRange) method.
  • Add a pivot table to the specified worksheet and set the location and cache of it using Worksheet.PivotTables.Add(String, CellRange, PivotCache) method.
  • Define row labels of the pivot table and then add fields to the data area to calculate data using PivotTable.DataFields.Add(IPivotField, String, SubtotalTypes) method.
  • Set the pivot table style using PivotTable.BuiltInStyle property.
  • Save the result document using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

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

            //Load a sample Excel document
            workbook.LoadFromFile(@"E:\Files\sample.xlsx");

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

            //Select the data source range
            CellRange dataRange = sheet.Range["B1:F11"];
            PivotCache cache = workbook.PivotCaches.Add(dataRange);

            //Add a PivotTable to the worksheet and set the location and cache of it
            PivotTable pt = sheet.PivotTables.Add("Pivot Table", sheet.Range["H3"], cache);

            //Define row labels
            PivotField r1 = pt.PivotFields["Country"] as PivotField;
            r1.Axis = AxisTypes.Row;
            pt.Options.RowHeaderCaption = "Country";

            PivotField r2 = pt.PivotFields["Product"] as PivotField;
            r2.Axis = AxisTypes.Row;

            //Add data fields to calculate data
            pt.DataFields.Add(pt.PivotFields["Quantity"], "SUM of Quantity", SubtotalTypes.Sum);
            pt.DataFields.Add(pt.PivotFields["Total Amount"], "SUM of Total Amount", SubtotalTypes.Sum);

            //Set pivot table style
            pt.BuiltInStyle = PivotBuiltInStyles.PivotStyleMedium10;

            //Save the document
            workbook.SaveToFile("CreatePivotTable.xlsx", ExcelVersion.Version2010);
    
        }
    }
}

C#/VB.NET: Create a Pivot Table 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.

Page borders in Microsoft Word can be a useful tool for improving the visual appeal and organization of your documents. Knowing how to effectively add, modify, and remove page borders can help you customize the appearance of your Word documents and elevate their overall presentation.

In this article, you will learn how to programmatically manage page borders in Word documents using C# and Spire.Doc for .NET.

Install Spire.Doc for .NET

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

PM> Install-Package Spire.Doc

Add Borders to All Pages in Word in C#

Spire.Doc for .NET provides the Borders class to manage the page borders in a Word document. This class offers a set of properties that allow you to control the appearance of the page border, including BorderType, Color, and LineWidth.

The steps to add borders to all pages in a Word document using C# are as follows:

  • Create a Document object.
  • Load a Word file from the given file path.
  • Iterate through the sections in the document.
    • Get a specific section.
    • Get the PageSetup object of the section.
    • Apply borders to all page by setting PageSetup.PageBordersApplyType to PageBordersApplyType.AllPages.
    • Get the Borders object through PageSetup.Borders property.
    • Set the border type, color, line width and other attributes through the properties under the Borders object.
  • Save the updated document to a different Word file.
  • C#
using Spire.Doc;
using System.Drawing;

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

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

            // Iterate through the sections in the document
            for (int i = 0; i < doc.Sections.Count; i++)
            {
                // Get a specific section
                Section section = doc.Sections[i];

                // Get page setup object
                PageSetup pageSetup = section.PageSetup;

                // Apply page border to all pages
                pageSetup.PageBordersApplyType = PageBordersApplyType.AllPages;

                // Set the border type
                pageSetup.Borders.BorderType = Spire.Doc.Documents.BorderStyle.DashLargeGap;

                // Set the border width
                pageSetup.Borders.LineWidth = 2;

                // Set the border color
                pageSetup.Borders.Color = Color.Red;

                // Set the spacing between borders and text within them
                pageSetup.Borders.Top.Space = 30;
                pageSetup.Borders.Bottom.Space = 30;
                pageSetup.Borders.Left.Space = 30;
                pageSetup.Borders.Right.Space = 30;
            }

            // Save the updated document to a different file
            doc.SaveToFile("AddPageBorder.docx", FileFormat.Docx);

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

C#: Add, Modify, or Remove Page Borders in Word

Modify Page Borders in Word in C#

The page borders in an existing Word document can be accessed through PageSetup.Borders class and their appearance can be modified using the properties under the Borders object.

The following are the steps to modify page border in a Word document using C#:

  • Create a Document object.
  • Load a Word file from the given file path.
  • Iterate through the sections in the document.
    • Get a specific section.
    • Get the PageSetup object of the section.
    • Get the Borders object through PageSetup.Borders property.
    • Set the border type, color, line width and other attributes through the properties under the Borders object.
  • Save the updated document to a different Word file.
  • C#
using Spire.Doc;
using System.Drawing;

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

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

            // Iterate through the sections in the document
            for (int i = 0; i < doc.Sections.Count; i++)
            {
                // Get a specific section
                Section section = doc.Sections[i];

                // Get page setup of the section
                PageSetup pageSetup = section.PageSetup;

                // Change the border type
                section.PageSetup.Borders.BorderType = Spire.Doc.Documents.BorderStyle.Double;

                // Change the border color
                section.PageSetup.Borders.Color = Color.Orange;

                // Change the border width
                section.PageSetup.Borders.LineWidth = 3;
            }

            // Save the updated document to a different file
            doc.SaveToFile("ModifyBorder.docx", FileFormat.Docx);

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

C#: Add, Modify, or Remove Page Borders in Word

Remove Page Borders in Word in C#

To remove the page borders of a Word document, you can simply set the Borders.BorderType property to BorderStyle.None. The following are the detailed steps.

  • Create a Document object.
  • Load a Word file from the given file path.
  • Iterate through the sections in the document.
    • Get a specific section.
    • Get the PageSetup object of the section.
    • Get the Borders object through PageSetup.Borders property.
    • Set the Borders.BorderType property as BorderStyle.None.
  • Save the updated document to a different Word file.
  • C#
using Spire.Doc;

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

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

            // Iterate through the sections in the document
            for (int i = 0; i < doc.Sections.Count; i++)
            {
                // Get a specific section
                Section section = doc.Sections[i];

                // Get page setup object
                PageSetup pageSetup = section.PageSetup;

                // Set the border type to none
                pageSetup.Borders.BorderType = Spire.Doc.Documents.BorderStyle.None;
            }

            // Save the updated document to a different file
            doc.SaveToFile("RemovePageBorder.docx", FileFormat.Docx);

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

C#: Add, Modify, or Remove Page Borders 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.

Remove Word Section in C#, VB.NET

2012-04-26 06:44:49 Written by Koohji

In Word document, users can add new sections or remove existing sections. This guide demonstrates how to remove Word section in C# and VB.NET.

Section, important part to form a Word document, can be easily added and removed. In MS Word, users can operation section by section break, adding new section by inserting a break and deleting existing section by removing section break. In this guide, a solution will be presented to remove Word section in C# and VB.NET via Spire.Doc for .NET.

Spire.Doc for .NET enables developers to access SectionCollection property of Document class to get specified section in Word document and then remove the unnecessary one or more. There are two methods to remove Word section.

Remove one Specified Section

Invoke Remove(Spire.Doc.Interface.IDocumentObject entity) method to remove specified object of document. In this solution, entity is the first section of document which has gotten at first.

[C#]
            Section section = document.Sections[0];
            document.Sections.Remove(section);
[VB.NET]
            Dim section As Section = document.Sections(0)
            document.Sections.Remove(section)

Invoke RemoveAt(int index) method to remove document object at the specified index from the collection.

[C#]
            document.Sections.RemoveAt(0);
[VB.NET]
	    document.Sections.RemoveAt(0)

Remove All Sections

Invoke Clear() method to clear all objects of document.

[C#]
            document.Sections.Clear();
[VB.NET]
            document.Sections.Clear()

Note: Because a Word document must include at least one section, so the document cannot be saved if all the sections are removed.

Spire.Doc, the professional stand-alone component to manipulate MS Word document without automation, enables developers to generate, read, write, modify Word document on their .NET, WPF and Silverlight application.

C#/VB.NET: Create Tables in PDF

2022-10-26 06:12:00 Written by Koohji

A table provides fast and efficient access to data displayed in rows and columns in a visually appealing manner. When presented in a table, data has a greater impact than when just used as words and enables readers to easily compare and understand relationships between them. In this article, you will learn how to create a table in PDF in C# and VB.NET using Spire.PDF for .NET.

Spire.PDF for .NET offers the PdfTable and the PdfGrid class to work with the tables in a PDF document. The PdfTable class is used to quickly create simple, regular tables without too much formatting, while the PdfGrid class is used to create more complex tables.

The table below lists the differences between these two classes.

PdfTable PdfGrid
Formatting
Row Can be set through events. No API support. Can be set through API.
Column Can be set through API (StringFormat). Can be set through API (StringFormat).
Cell Can be set through events. No API support. Can be set through API.
Others
Column span Not support. Can be set through API.
Row span Can be set through events. No API support. Can be set through API.
Nested table Can be set through events. No API support. Can be set through API.
Events BeginCellLayout,  EndCellLayout, BeginRowLayout, EndRowLayout, BeginPageLayout, EndPageLayout. BeginPageLayout, EndPageLayout.

The following sections demonstrate how to create a table in PDF using the PdfTable class and the PdfGrid class, respectively.

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 a Table Using PdfTable Class

The following are the steps to create a table using the PdfTable class.

  • Create a PdfDocument object.
  • Add a page to it using PdfDocument.Pages.Add() method.
  • Create a Pdftable object.
  • Set the table style through PdfTable.Style property.
  • Insert data to table through PdfTable.DataSource property.
  • Set row height and row color through BeginRowLayout event.
  • Draw table on the PDF page using PdfTable.Draw() method.
  • Save the document to a PDF file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using System;
using System.Data;
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Tables;

namespace CreateTable
{
    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(40));

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

            //Set font for header and the rest cells
            table.Style.DefaultStyle.Font = new PdfTrueTypeFont(new Font("Times New Roman", 12f, FontStyle.Regular), true);
            table.Style.HeaderStyle.Font = new PdfTrueTypeFont(new Font("Times New Roman", 12f, FontStyle.Bold), true);

            //Crate a DataTable
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("ID");
            dataTable.Columns.Add("Name");
            dataTable.Columns.Add("Department");
            dataTable.Columns.Add("Position");
            dataTable.Columns.Add("Level");
            dataTable.Rows.Add(new string[] { "1", "David", "IT", "Manager", "1" });
            dataTable.Rows.Add(new string[] { "3", "Julia", "HR", "Manager", "1" });
            dataTable.Rows.Add(new string[] { "4", "Sophie", "Marketing", "Manager", "1" });
            dataTable.Rows.Add(new string[] { "7", "Wickey", "Marketing", "Sales Rep", "2" });
            dataTable.Rows.Add(new string[] { "9", "Wayne", "HR", "HR Supervisor", "2" });
            dataTable.Rows.Add(new string[] { "11", "Mia", "Dev", "Developer", "2" });

            //Set the datatable as the data source of table
            table.DataSource = dataTable;

            //Show header(the header is hidden 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;

            //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);
            }

            //Register with BeginRowLayout event
            table.BeginRowLayout += Table_BeginRowLayout;

            //Draw table on the page
            table.Draw(page, new PointF(0, 30));

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

        //Event handler
        private static void Table_BeginRowLayout(object sender, BeginRowLayoutEventArgs args)
        {
            //Set row height
            args.MinimalHeight = 20f;

            //Alternate row color
            if (args.RowIndex < 0)
            {
                return;
            }
            if (args.RowIndex % 2 == 1)
            {
                args.CellStyle.BackgroundBrush = PdfBrushes.LightGray;
            }
            else
            {
                args.CellStyle.BackgroundBrush = PdfBrushes.White;
            }
        }
    }
}

C#/VB.NET: Create Tables in PDF

Create a Table Using PdfGrid Class

Below are the steps to create a table using the PdfGrid class.

  • Create a PdfDocument object.
  • Add a page to it using PdfDocument.Pages.Add() method.
  • Create a PdfGrid object.
  • Set the table style through PdfGrid.Style property.
  • Add rows to the table using PdfGrid.Rows.Add() method.
  • Insert data to specific cells through PdfGridRow.Cells[index].Value property.
  • Span cells across columns or rows through PdfGridRow.RowSpan or PdfGridRow.ColumnSpan property.
  • Set the formatting of a specific cell through PdfGridRow.Cells[index].StringFormat and PdfGridRow.Cells[index].Style properties.
  • Draw table on the PDF page using PdfGrid.Draw() method.
  • Save the document to a PDF file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Grid;
using System.Drawing;

namespace CreateGrid
{
    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(40));

            //Create a PdfGrid
            PdfGrid grid = new PdfGrid();

            //Set cell padding
            grid.Style.CellPadding = new PdfPaddings(1, 1, 1, 1);

            //Set font
            grid.Style.Font = new PdfTrueTypeFont(new Font("Times New Roman", 13f, FontStyle.Regular), true);

            //Add rows
            PdfGridRow row1 = grid.Rows.Add();
            PdfGridRow row2 = grid.Rows.Add();
            PdfGridRow row3 = grid.Rows.Add();
            PdfGridRow row4 = grid.Rows.Add();
            grid.Columns.Add(4);

            //Set column width
            foreach (PdfGridColumn col in grid.Columns)
            {
                col.Width = 110f;
            }

            //Write data into specific cells
            row1.Cells[0].Value = "Order and Payment Status";
            row2.Cells[0].Value = "Order number";
            row2.Cells[1].Value = "Date";
            row2.Cells[2].Value = "Customer";
            row2.Cells[3].Value = "Paid or not";
            row3.Cells[0].Value = "00223";
            row3.Cells[1].Value = "2022/06/02";
            row3.Cells[2].Value = "Brick Lane Realty";
            row3.Cells[3].Value = "Yes";
            row4.Cells[0].Value = "00224";
            row4.Cells[1].Value = "2022/06/03";
            row4.Cells[3].Value = "No";

            //Span cell across columns
            row1.Cells[0].ColumnSpan = 4;

            //Span cell across rows
            row3.Cells[2].RowSpan = 2;

            //Set text alignment of specific cells
            row1.Cells[0].StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
            row3.Cells[2].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);

            //Set background color of specific cells
            row1.Cells[0].Style.BackgroundBrush = PdfBrushes.Orange;
            row4.Cells[3].Style.BackgroundBrush = PdfBrushes.LightGray;

            //Format cell border
            PdfBorders borders = new PdfBorders();
            borders.All = new PdfPen(Color.Orange, 0.8f);
            foreach (PdfGridRow pgr in grid.Rows)
            {
                foreach (PdfGridCell pgc in pgr.Cells)
                {
                    pgc.Style.Borders = borders;
                }
            }

            //Draw table on the page
            grid.Draw(page, new PointF(0, 30));

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

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

When receiving or downloading a Word document from the Internet, you may sometimes need to extract content from the document for other purposes. In this article, you will learn how to programmatically extract text and images from 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

Extract Text from a Word Document

Below are detailed steps on how to extract text from a Word document and save in a TXT file.

  • Create a Document instance.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Create a StringBuilder instance.
  • Get each paragraph of each section in the document.
  • Get the text of a specified paragraph using Paragraph.Text property, and then append the extracted text to the StringBuilder instance using StringBuilder.AppendLine() method.
  • Create a new txt file and write the extracted text to the file using File.WriteAllText() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using System.Text;
using System.IO;

namespace ExtractTextfromWord
{
    class ExtractText
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document document = new Document();

            //Load a sample Word document 
            document.LoadFromFile("input.docx");

            //Create a StringBuilder instance
            StringBuilder sb = new StringBuilder();

            //Extract text from Word and save to StringBuilder instance
            foreach (Section section in document.Sections)
            {
                foreach (Paragraph paragraph in section.Paragraphs)
                {
                    sb.AppendLine(paragraph.Text);
                }
            }

            //Create a new txt file to save the extracted text
            File.WriteAllText("Extract.txt", sb.ToString());
        }
    }
}

C#/VB.NET: Extract Text and Images from Word

Extract Images from a Word Document

Below are detailed steps on how to extract all images from a Word document.

  • Create a Document instance and load a sample Word document.
  • Get each paragraph of each section in the document.
  • Get each document object of a specific paragraph.
  • Determine whether the document object type is picture. If yes, save the image out of the document using DocPicture.Image.Save(String, ImageFormat) method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System;

namespace ExtractImage
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load a Word document
            Document document = new Document("input.docx");
            int index = 0;

            //Get each section of document
            foreach (Section section in document.Sections)
            {
                //Get each paragraph of section
                foreach (Paragraph paragraph in section.Paragraphs)
                {
                    //Get each document object of a specific paragraph
                    foreach (DocumentObject docObject in paragraph.ChildObjects)
                    {
                        //If the DocumentObjectType is picture, save it out of the document
                        if (docObject.DocumentObjectType == DocumentObjectType.Picture)
                        {
                            DocPicture picture = docObject as DocPicture;
                            picture.Image.Save(string.Format("image_{0}.png", index), System.Drawing.Imaging.ImageFormat.Png);
                            index++;
                        }
                    }
                }
            }
        }
    }
}

C#/VB.NET: Extract Text and Images from 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.

C#/VB.NET: Insert Page Breaks in Excel

2022-11-18 08:37:00 Written by Koohji

In Excel, a page break is a separator that divides a worksheet into several different pages/segments for the purpose of better printing. By inserting page breaks where necessary, you can avoid misalignment of data and ensure a desired print result, which is especially useful when working with a large data set. This article will demonstrate how to programmatically insert horizontal or vertical page breaks in Excel 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

Insert Horizontal Page Breaks in an Excel Worksheet

A horizontal page break is inserted between a selected row and the row above it. After insertion, the selected row will become the top row of the new page. With Spire.XLS for .NET, developers are allowed to use the Worksheet.HPageBreaks.Add(CellRange) method to insert horizontal page breaks. The detailed steps are as follows.

  • Create a Workbook instance.
  • Load a sample Excel file using Workbook.LoadFromFile() method.
  • Get a specified worksheet using Workbook.Worksheets[sheetIndex] property.
  • Add horizontal page break to a specified cell range using Worksheet.HPageBreaks.Add(CellRange) method.
  • Set view mode to Preview mode using Worksheet.ViewMode property.
  • Save the result file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

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

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

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

            //Set Excel page break horizontally
            sheet.HPageBreaks.Add(sheet.Range["A7"]);
            sheet.HPageBreaks.Add(sheet.Range["A18"]);

            //Set view mode to Preview mode
            sheet.ViewMode = ViewMode.Preview;

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

C#/VB.NET: Insert Page Breaks in Excel

Insert Vertical Page Breaks in an Excel Worksheet

A vertical page break is inserted between a selected column and the column to its left. After insertion, the selected column will become the left most column of the new page. To insert vertical page breaks, developers can use the Worksheet.VPageBreaks.Add(CellRange) method offered by Spire.XLS for .NET offers. The detailed steps are as follows.

  • Create a Workbook instance.
  • Load a sample Excel file using Workbook.LoadFromFile() method.
  • Get a specified worksheet using Workbook.Worksheets[sheetIndex] property.
  • Add vertical page break to a specified cell range using Worksheet.VPageBreaks.Add(CellRange) method.
  • Set view mode to Preview mode using Worksheet.ViewMode property.
  • Save the result file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

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

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

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

            //Set Excel page break vertically
            sheet.VPageBreaks.Add(sheet.Range["B1"]);

            //Set view mode to Preview mode
            sheet.ViewMode = ViewMode.Preview;

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

C#/VB.NET: Insert Page Breaks 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.

page 74