page 268

Document properties (also known as metadata) are a set of information about a document. All Word documents come with a set of built-in document properties, including title, author name, subject, keywords, etc. In addition to the built-in document properties, Microsoft Word also allows users to add custom document properties to Word documents. In this article, we will explain how to add these document properties to Word documents in C# and VB.NET using Spire.Doc for .NET.

Install Spire.Doc for .NET

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

PM> Install-Package Spire.Doc

Add Built-in Document Properties to a Word Document in C# and VB.NET

A built-in document property consists of a name and a value. You cannot set or change the name of a built-in document property as it's predefined by Microsoft Word, but you can set or change its value. The following steps demonstrate how to set values for built-in document properties in a Word document:

  • Initialize an instance of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Get the built-in document properties of the document through Document.BuiltinDocumentProperties property.
  • Set values for specific document properties such as title, subject and author through Title, Subject and Author properties of BuiltinDocumentProperties class.
  • Save the result document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;

namespace BuiltinDocumentProperties
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document document = new Document();
            //Load a Word document
            document.LoadFromFile("Sample.docx");

            //Add built-in document properties to the document
            BuiltinDocumentProperties standardProperties = document.BuiltinDocumentProperties;
            standardProperties.Title = "Add Document Properties";
            standardProperties.Subject = "C# Example";
            standardProperties.Author = "James";
            standardProperties.Company = "Eiceblue";
            standardProperties.Manager = "Michael";
            standardProperties.Category = "Document Manipulation";
            standardProperties.Keywords = "C#, Word, Document Properties";
            standardProperties.Comments = "This article shows how to add document properties";

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

C#/VB.NET: Add Document Properties to Word Documents

Add Custom Document Properties to a Word Document in C# and VB.NET

A custom document property can be defined by a document author or user. Each custom document property should contain a name, a value and a data type. The data type can be one of these four types: Text, Date, Number and Yes or No. The following steps demonstrate how to add custom document properties with different data types to a Word document:

  • Initialize an instance of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Get the custom document properties of the document through Document.CustomDocumentProperties property.
  • Add custom document properties with different data types to the document using CustomDocumentProperties.Add(string, object) method.
  • Save the result document using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using System;

namespace CustomDocumentProperties
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document document = new Document();
            //Load a Word document
            document.LoadFromFile("Sample.docx");

            //Add custom document properties to the document
            CustomDocumentProperties customProperties = document.CustomDocumentProperties;
            customProperties.Add("Document ID", 1);
            customProperties.Add("Authorized", true);
            customProperties.Add("Authorized By", "John Smith");
            customProperties.Add("Authorized Date", DateTime.Today);

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

C#/VB.NET: Add Document Properties to Word Documents

Apply for a Temporary License

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

A document can have one or more pages. It is probably easy to add a header for all pages of the document. If you want to add the header only for the first page of the document, Spire.Doc for .NET component can provide you an easy and flexible solution to handle it. The following steps will guide how to add a header into the first page of a document using Spire.Doc for .NET component in C#. In the example, the header is got from an existing document.

Step 1: Load a word document, documen1.docx.

Document document1 = new Document();
document1.LoadFromFile("D:\\document1.docx");

Step 2: Get the header of document1.docx.

HeaderFooter header = document1.Sections[0].HeadersFooters.Header;

Step 3: Load another word document which will be added the header, document2.docx.

Document document2 = new Document();
document2.LoadFromFile("D:\\document2.docx");

Step 4: Get the first page header of document2.docx.

HeaderFooter firstPageHeader = document2.Sections[0].HeadersFooters.FirstPageHeader;

Step 5: Specify that the current section has a different header/footer for the first page.

foreach (Section section in document2.Sections)
{
section.PageSetup.DifferentFirstPageHeaderFooter = true;
}

Step 6: Removes all child objects in firstPageHeader.

firstPageHeader.Paragraphs.Clear();

Step 7: Add all child objects of the header to firstPageHeader.

foreach (DocumentObject obj in header.ChildObjects)
{
firstPageHeader.ChildObjects.Add(obj.Clone());
}

Step 8: Save document2.docx to a new document, header.docx.

document2.SaveToFile("D:\\Header.docx"", FileFormat.Docx);

Full code:

Document document1 = new Document();
document1.LoadFromFile(@"..\..\document1.docx");
Document document2 = new Document();
document2.LoadFromFile(@"..\..\document2.docx");
HeaderFooter header = document1.Sections[0].HeadersFooters.Header;
HeaderFooter firstPageHeader = document2.Sections[0].HeadersFooters.FirstPageHeader;

foreach (Section section in document2.Sections)
{
section.PageSetup.DifferentFirstPageHeaderFooter = true;
}

firstPageHeader.Paragraphs.Clear();
foreach (DocumentObject obj in header.ChildObjects)
{
firstPageHeader.ChildObjects.Add(obj.Clone());
}

document2.SaveToFile("Header.docx", FileFormat.Docx);

Screenshots:

document1.docx:

Add a header only into the first page

document2.docx:

Add a header only into the first page

Header.docx:

Add a header only into the first page

C# .NET Convert Excel to PDF

Converting Excel files to PDF is a crucial task for anyone looking to share spreadsheet data in a secure, consistent, and universally accessible format. Whether you are generating financial reports, creating invoices, or sharing analytical data, PDFs ensure that your document's layout and formatting remain intact across all devices and platforms. Unlike Excel files, which require compatible software to open, PDFs are universally viewable without any dependency.

This guide provides a comprehensive overview of how to efficiently convert Excel files to PDF in C# using a .NET Excel library – Spire.XLS for .NET. You will learn both basic and advanced conversion techniques, including how to export specific sheets or cell ranges, customize page setup, secure converted PDFs with passwords, generate PDF/A-compliant files, and more.

Table of Contents

Why Convert Excel to PDF

Converting Excel files to PDF offers several key advantages:

  • Preserved Layout and Formatting: PDF maintains the original structure and formatting of your Excel file, ensuring consistent appearance across devices.
  • Cross-Platform Accessibility: PDF is universally compatible, viewable on any device or operating system without requiring Excel or other spreadsheet software.
  • Enhanced Security: PDF files can be encrypted, digitally signed, and restricted to prevent unauthorized access, copying, or editing.

C# .NET Excel to PDF Conversion Library

Spire.XLS for .NET is a comprehensive Excel library that enables seamless conversion of Excel files to PDF within .NET applications without the need for Microsoft Office. It provides developers with full control over how the content is rendered and ensures that the layout and formatting are preserved during the conversion process.

Install Spire.XLS for .NET

Before starting the conversion process, install Spire.XLS for .NET using one of the following methods:

  • Option 1: Install via NuGet (Recommended)
Install-Package Spire.XLS
  • Option 2: Manually Add DLLs to Your Project
    • Download the Spire.XLS package and extract the files.
    • In Visual Studio, right-click References > Add Reference > Browse, then select the appropriate Spire.Xls.dll based on your target framework.

Basic Excel to PDF Conversion

Converting an Excel file to PDF with Spire.XLS is simple and requires only a few lines of code. The following example demonstrates how to load an Excel file and save it as a PDF:

  • C#
using Spire.Xls;

namespace ExcelToPdf
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();
            // Load an Excel file
            workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Example.xlsx");

            // Save the Excel file to PDF
            workbook.SaveToFile("Output.pdf", FileFormat.PDF);
            // Dispose resources
            workbook.Dispose();
        }
    }
}

C# .NET Convert XLS or XLSX to PDF

Advanced Excel to PDF Conversion Features

In addition to basic conversion, Spire.XLS for .NET provides advanced options for customized Excel-to-PDF conversions, including:

  • Export specific sheet or cell range as PDF.
  • Fit sheet to one page.
  • Adjust page setup options (e.g., margins, orientation, paper size) for customized PDF output.
  • Secure the converted PDF with password.
  • Generate PDF/A-compliant files for long-term preservation.

Export Specific Sheet or Cell Range as PDF

Sometimes, you may want to export only a specific sheet or range of cells from an Excel file to PDF. Here's how to do that:

  • C#
using Spire.Xls;

namespace WorksheetOrCellRangeToPdf
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();
            // Load the Excel file
            workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Example.xlsx");

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

            // Set the print area to a specific cell range
            // Comment this line out if you need to export the entire worksheet as a PDF
            sheet.PageSetup.PrintArea = "B1:E6";

            // Save the cell range as a PDF
            sheet.SaveToPdf("CellRange.pdf");
            // Dispose resources
            workbook.Dispose();
        }
    }
}

Fit Sheet to One Page

Spire.XLS allows you to fit the content of a sheet to one page, which is particularly useful for printing or distributing concise reports.

  • C#
using Spire.Xls;

namespace FitWorksheetToOnePage
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();
            // Load the Excel file
            workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Example.xlsx");

            // Fit every worksheet in the workbook to one page
            workbook.ConverterSetting.SheetFitToPage = true;

            // Save the Excel file to PDF
            workbook.SaveToFile("FitToOnePage.pdf", FileFormat.PDF);
            // Dispose resources
            workbook.Dispose();
        }
    }
}

Adjust Page Setup for Customized PDF Output

Before converting an Excel worksheet to PDF, you can adjust page setup options such as margins, paper size, orientation, and gridline visibility. This ensures the final PDF is accurately formatted to meet your presentation requirements.

  • C#
using Spire.Xls;

namespace AdjustPageSetup
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();
            // Load the Excel file
            workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Example.xlsx");

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

            // Adjust page setup settings
            // Set page orientation
            sheet.PageSetup.Orientation = PageOrientationType.Landscape;
            // Set paper size
            sheet.PageSetup.PaperSize = PaperSizeType.PaperA4;
            // Set margins
            sheet.PageSetup.LeftMargin = 0.5;
            sheet.PageSetup.RightMargin = 0.5;
            sheet.PageSetup.TopMargin = 0.5;
            sheet.PageSetup.BottomMargin = 0.5;
            // Display Gridlines
            sheet.PageSetup.IsPrintGridlines = true;

            // Save the worksheet as a PDF
            sheet.SaveToPdf("CustomPageSetup.pdf");
            // Dispose resources
            workbook.Dispose();
        }
    }
}

Secure the Converted PDF with Password

You can secure the converted PDF by applying password protection. This ensures that unauthorized users cannot access or modify the document.

  • C#
using Spire.Xls;
using Spire.Xls.Pdf.Security;

namespace SecurePdfWithPassword
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();
            // Load the Excel file
            workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Example.xlsx");

            // Set the open and permission passwords for the converted PDF
            workbook.ConverterSetting.PdfSecurity.Encrypt("openPassword", "persmissionPassword", PdfPermissionsFlags.Print, PdfEncryptionKeySize.Key128Bit);

            // Save the Excel file to PDF
            workbook.SaveToFile("SecurePdf.pdf", FileFormat.PDF);
            // Dispose resources
            workbook.Dispose();
        }
    }
}

Generate PDF/A-compliant Files

If you need to archive your documents for long-term storage or ensure they meet certain accessibility standards, you can generate PDF/A-compliant files from Excel.

  • C#
using Spire.Xls;
using Spire.Xls.Pdf;

namespace ExcelToPdfA
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a Workbook object
            Workbook workbook = new Workbook();
            // Load the Excel file
            workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Example.xlsx");

            // Set the compliance for the converted PDF
            workbook.ConverterSetting.PdfConformanceLevel = PdfConformanceLevel.Pdf_A1A;

            // Save the Excel file to PDF
            workbook.SaveToFile("PdfA_Compliant.pdf", FileFormat.PDF);
            // Dispose resources
            workbook.Dispose();
        }
    }
}

FAQs

Q1: Can I convert a password-protected Excel file to PDF?

Yes, you can load password-protected Excel files by providing the password before loading:

  • C#
Workbook workbook = new Workbook();
workbook.OpenPassword = "ExcelPassword";
workbook.LoadFromFile("ProtectedExcel.xlsx");
workbook.SaveToFile("Output.pdf", FileFormat.PDF);

Q2: Is Spire.XLS compatible with .NET Core?

Yes, Spire.XLS supports .NET Framework, .NET Core, and .NET Standard.

Q3: Can I batch convert multiple Excel files to PDF?

Yes, you can batch convert multiple Excel files to PDF using a loop:

  • C#
string[] files = Directory.GetFiles("ExcelFolder", "*.xlsx");
foreach (string file in files)
{
    Workbook workbook = new Workbook();
    workbook.LoadFromFile(file);
    string outputPath = Path.ChangeExtension(file, ".pdf");
    workbook.SaveToFile(outputPath, FileFormat.PDF);
}

Q4: Can I convert multiple Excel files to a single PDF?

Yes, you can combine multiple Excel files into a single workbook and then save them as a single PDF:

  • C#
Workbook combinedWorkbook = new Workbook();
combinedWorkbook.Worksheets.Clear();
foreach (string file in Directory.GetFiles("ExcelFolder", "*.xlsx"))
{
    Workbook tempWorkbook = new Workbook();
    tempWorkbook.LoadFromFile(file);
    foreach (Worksheet sheet in tempWorkbook.Worksheets)
    {
        combinedWorkbook.Worksheets.AddCopy(sheet);
    }
}
combinedWorkbook.SaveToFile("Combined.pdf", FileFormat.PDF);

Q5: Why does my converted PDF look different from the Excel file?

This issue could be due to missing fonts on the system. Make sure that all fonts used in the Excel file are installed on the machine performing the conversion.

Conclusion

Spire.XLS for .NET provides a powerful and flexible solution for converting Excel files to PDF in C#. Whether you need simple conversions or advanced features—such as exporting specific sheets or cell ranges, customizing page setup, applying password protection to the converted PDF, or generating PDF/A-compliant files—Spire.XLS offers a comprehensive set of tools to meet all your requirements. By following the steps outlined in this guide, you can easily integrate Excel-to-PDF conversion capabilities into your .NET applications.

Get a Free License

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

page 268