C#/VB.NET: Print Excel Documents

2022-11-22 08:17:00 Written by Koohji

Excel documents are easy to print, but it would be a bit tricky if you have some special printing requirements. For example, printing only selected range of a sheet, repeating the header row on each page, or fitting a worksheet on one page. This article covers how to set Excel print options via page setup and how to send an Excel document to printer in C# and VB.NET by 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

Set Excel Print Options via Page Setup in C# and VB.NET

Excel Page Setup provides options to control how a worksheet will be printed, such as whether to print comments, whether to print gridlines and specify the cell range to print. Spire.XLS offers the PageSetup object to deal with these things. The following are the steps to set Excel print options through PageSetup using Spire.XLS for .NET.

  • Create a Workbook object.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet through Workbook.Worksheets[index] property.
  • Get PageSetup object through Worksheet.PageSetup property.
  • Set page margins, print area, pint title row, print quality, etc. through the properties under PageSetup object.
  • Save the workbook to another Excel file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

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

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

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

            //Get the PageSetup object of the first worksheet
            PageSetup pageSetup = worksheet.PageSetup;

            //Set page margins
            pageSetup.TopMargin = 0.3;
            pageSetup.BottomMargin = 0.3;
            pageSetup.LeftMargin = 0.3;
            pageSetup.RightMargin = 0.3;

            //Specify print area
            pageSetup.PrintArea = "A1:D10";

            //Specify title row
            pageSetup.PrintTitleRows = "$1:$2";

            //Allow to print with row/column headings
            pageSetup.IsPrintHeadings = true;

            //Allow to print with gridlines
            pageSetup.IsPrintGridlines = true;

            //Allow to print comments as displayed on worksheet
            pageSetup.PrintComments = PrintCommentType.InPlace;

            //Set printing quality (dpi)
            pageSetup.PrintQuality = 300;

            //Allow to print worksheet in black & white mode
            pageSetup.BlackAndWhite = true;

            //Set the printing order
            pageSetup.Order = OrderType.OverThenDown;

            //Fit worksheet on one page
            pageSetup.IsFitToPage = true;

            //Save the workbook
            workbook.SaveToFile("PagePrintOptions.xlsx", ExcelVersion.Version2016);
        }
    }
}

C#/VB.NET: Print Excel Documents

Print Excel Documents Using Print Dialog in C# and VB.NET

A Print Dialog box lets users to select options for a particular print job. For example, the user can specify the printer to use. The following are the steps to send an Excel document to a print dialog using Spire.XLS for .NET.

  • Create a Workbook object.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Create a PrintDialog object.
  • Specify printer settings through the properties under PrintDialog object.
  • Apply the print dialog to workbook.
  • Get PrintDocument object from the workbook through Workbook.PrintDocument property.
  • Invoke the print dialog and start printing using PrintDocument.Print() method.
  • C#
  • VB.NET
using System;
using Spire.Xls;
using System.Drawing.Printing;
using System.Windows.Forms;

namespace PrintExcelUsingPrintDialog
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Create a Workbook object
            Workbook workbook = new Workbook();

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

            //Fit worksheet on one page    
            PageSetup pageSetup = workbook.Worksheets[0].PageSetup;
            pageSetup.IsFitToPage = true;

            //Create a PrintDialog object
            PrintDialog dialog = new PrintDialog();

            //Specify printer settings 
            dialog.AllowCurrentPage = true;
            dialog.AllowSomePages = true;
            dialog.AllowSelection = true;
            dialog.UseEXDialog = true;
            dialog.PrinterSettings.Duplex = Duplex.Simplex;

            //Apply the dialog to workbook 
            workbook.PrintDialog = dialog;

            //Create a PrintDocument object based on the workbook
            PrintDocument printDocument = workbook.PrintDocument;

            //Invoke the print dialog
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                printDocument.Print();
            }
        }
    }
}

C#/VB.NET: Print Excel Documents

Silently Print Excel Documents in C# and VB.NET

If you do not want to see the print dialog or the print process, you can silently print Excel documents to a specified printer. The following are the steps.

  • Create a Workbook object.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Set the print controller to StandardPrintController, which will prevent print process from showing.
  • Get PrinterSettings object from the workbook through Workbook.PrintDocument.PrinterSettings property.
  • Specify printer name, duplex mode and print pages through the properties under PrinerSettings object.
  • Print the workbook using Workbook.PrintDocument.Print() method.
  • C#
  • VB.NET
using Spire.Xls;
using System.Drawing.Printing;

namespace SilentlyPrint
{
    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\sample.xlsx");

            //Fit worksheet on one page    
            PageSetup pageSetup = workbook.Worksheets[0].PageSetup;
            pageSetup.IsFitToPage = true;

            //Set the print controller to StandardPrintController, which will prevent print process from showing
            workbook.PrintDocument.PrintController = new StandardPrintController();

            //Get PrinterSettings from the workbook
            PrinterSettings settings = workbook.PrintDocument.PrinterSettings;

            //Specify printer name, duplex mode and print pages
            settings.PrinterName = "HP LaserJet P1007"; 
            settings.Duplex = Duplex.Simplex;
            settings.FromPage = 1;
            settings.ToPage = 3;         

            //Print the workbook
            workbook.PrintDocument.Print();
        }
    }
}

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.

Update excel data via GridViewTable

2014-07-04 07:01:18 Written by Koohji

Spire.XLS for .NET is a professional Excel component which enables developers/programmers to fast generate, read, write and modify Excel document for .NET. Spire.XLS for .NET doesn't need Microsoft Office Excel Automation. It allows user to operate Excel document directly such as save to stream, save as web response, copy, lock/unlock worksheet, set up workbook properties, etc. As a professional .NET Excel component, it also includes many useful features, for example, functionalities of importing data from Excel to dataTable and exporting dataTable to Excel from Database.

In this article introduces a method of updating excel data by dataTable via using sheet.ExportDataTable() method and sheet.InsertDataTable() method to import data from excel to dataTable and export dataTable to excel from Database.

The main steps of method are:

Step 1: Load the excel document and use sheet.ExportDataTable() method extract data to dataTable and show by dataGridView control.

private void Form1_Load(object sender, EventArgs e)
        {
            //load excel document to workbook
            workbook.LoadFromFile(@"DatatableSample.xls");
            Worksheet sheet = workbook.Worksheets[0];
            sheet.Name = "Original table";
            //extract data to dataTable from sheet 
            DataTable dataTable = sheet.ExportDataTable();
            //show the data to dataGridView
            this.dataGridView.DataSource = dataTable;
        }

The effect screenshot:

Update excel data via GridViewTable

Step 2: Create a new sheet to save the updata data and use sheet.InsertDataTable() method to insert dataTable to the sheet.

            //create a new sheet to save Updata data.
            Worksheet sheet = workbook.CreateEmptySheet("Updata Table");
            //extract data from dataGridView
            DataTable dataTable = this.dataGridView.DataSource as DataTable;
            // insert dataTable to sheet
            sheet.InsertDataTable(dataTable, true, 1, 1);

Step 3: Save the result excel document.

workbook.SaveToFile("result.xlsx", ExcelVersion.Version2007);

The effect screenshot:

Update excel data via GridViewTable

Download and install Spire.XLS for .NET and use below code to experience this method to update excel data by dataTable.

The full code:

[C#]
using System;
using System.Data;
using System.Windows.Forms;
using Spire.Xls;
namespace UpdataExcelDataByDataTable
{

    public partial class UpdataExcelData : Form
    {
        private Workbook workbook = new Workbook();
        private void Form1_Load(object sender, EventArgs e)
        {
            workbook.LoadFromFile(@"DatatableSample.xls");
            Worksheet sheet = workbook.Worksheets[0];
            sheet.Name = "Original table";
            DataTable dataTable = sheet.ExportDataTable();
            this.dataGridView.DataSource = dataTable;
        }
        private void Updata_Click(object sender, EventArgs e)
        {
            Worksheet sheet = workbook.CreateEmptySheet("Updata Table");
            DataTable dataTable = this.dataGridView.DataSource as DataTable;
            sheet.InsertDataTable(dataTable, true, 1, 1);
            workbook.SaveToFile("result.xlsx", ExcelVersion.Version2007);
            System.Diagnostics.Process.Start("result.xlsx");
        }
    }
}
[VB.NET]
Imports System.Data
Imports System.Windows.Forms
Imports Spire.Xls
Public Class Form1
    Private workbook As New Workbook()
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        'load excel document to workbook
        workbook.LoadFromFile("DatatableSample.xls")
        Dim sheet As Worksheet = workbook.Worksheets(0)
        sheet.Name = "Original table"
        'extract data to dataTable from sheet 
        Dim dataTable As DataTable = sheet.ExportDataTable()
        'show the data to dataGridView
        Me.DataGridView.DataSource = dataTable
    End Sub

If you couldn't successfully use the Spire.Xls, please refer Spire.XLS Quick Start which can guide you quickly use the Spire.Xls.

Insert an Image to PDF Grid Cell in C#

2014-07-03 07:22:29 Written by Koohji

This sample demo has demonstrated how to draw nested grid in PDF document and set grid row&cell format. In the following section, we are going to create a simple PDF grid and show you how to insert an image to a specific PDF grid cell in C#. Before we can follow the code snippet below to accomplish the task, we have to prepare the environment first.

Download Spire.PDF and install it on system, create or open a .NET class application in Visual Studio 2005 or above versions, add Spire.PDF.dll to your .NET project assemblies.Then let's code step by step to make a better understanding about the whole procedure.

Step 1: Create a PDF document and add a new page.

PdfDocument doc = new PdfDocument();
PdfPageBase page = doc.Pages.Add();

Step 2: Create a 2×2 grid to PDF.

PdfGrid grid = new PdfGrid();
PdfGridRow row = grid.Rows.Add();
           row = grid.Rows.Add();
                 grid.Columns.Add(2);

Step 3: Set the cell padding of the PDF grid.

grid.Style.CellPadding = new PdfPaddings(1, 1, 1, 1);

Step 4: Set the width of the columns.

float width = page.Canvas.ClientSize.Width - (grid.Columns.Count + 1);
      grid.Columns[0].Width = width * 0.25f;
      grid.Columns[1].Width = width * 0.25f;

Step 5: Load an image from disk.

PdfGridCellContentList lst = new PdfGridCellContentList();
PdfGridCellContent textAndStyle = new PdfGridCellContent();
textAndStyle.Image = PdfImage.FromFile("..\\..\\image1.jpg");

Step 6: Set the size of image and insert it to the first cell.

textAndStyle.ImageSize = new SizeF(50, 50);
lst.List.Add(textAndStyle);
          
grid.Rows[0].Cells[0].Value = lst;
grid.Rows[1].Height = grid.Rows[0].Height;

Step 7: Draw PDF grid into page at the specific location.

PdfLayoutResult result = grid.Draw(page, new PointF(10, 30));

Step 8: Save to a PDF file and launch the file.

doc.SaveToFile(outputFile, FileFormat.PDF);
System.Diagnostics.Process.Start(outputFile);

Result:

Insert an Image to PDF Grid Cell in C#

Full C# Code:

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

namespace InsertImage
{
    class Program
    {
        static void Main(string[] args)
        {
            string outputFile = @"..\..\output.pdf";
            //Create a pdf document
            PdfDocument doc = new PdfDocument();
            //Add a page for the pdf document
            PdfPageBase page = doc.Pages.Add();
            //Create a pdf grid
            PdfGrid grid = new PdfGrid();
            //Set the cell padding of pdf grid
            grid.Style.CellPadding = new PdfPaddings(1, 1, 1, 1);
            //Add a row for pdf grid
            PdfGridRow row = grid.Rows.Add();
            //Add two columns for pdf grid 
            grid.Columns.Add(2);
            float width = page.Canvas.ClientSize.Width - (grid.Columns.Count + 1);
            //Set the width of the first column
            grid.Columns[0].Width = width * 0.25f;
            grid.Columns[1].Width = width * 0.25f;
            //Add a image
            PdfGridCellContentList lst = new PdfGridCellContentList();
            PdfGridCellContent textAndStyle = new PdfGridCellContent();
            textAndStyle.Image = PdfImage.FromFile("..\\..\\image1.jpg");
            //Set the size of image
            textAndStyle.ImageSize = new SizeF(50, 50);
            lst.List.Add(textAndStyle);
            //Add a image into the first cell. 
            row.Cells[0].Value = lst;
            //Draw pdf grid into page at the specific location
            PdfLayoutResult result = grid.Draw(page, new PointF(10, 30));
            //Save to a pdf file 
            doc.SaveToFile(outputFile, FileFormat.PDF);
            System.Diagnostics.Process.Start(outputFile);
        }
    }
}

Counting the number of pages in a PDF file is essential for various purposes, such as determining document length, organizing content, and evaluating printing requirements. Apart from knowing page count information using PDF viewers, you can also automate the task through programming. In this article, you will learn how to use C# to get the number of pages in a PDF file 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

Get the Number of Pages in a PDF File in C#

Spire.PDF for .NET offers the PdfDocument.Pages.Count property to quickly count the number of pages in a PDF file without opening it. The following are the detailed steps.

  • Create a PdfDocument object.
  • Load a sample PDF file using PdfDocument.LoadFromFile() method.
  • Count the number of pages in the PDF file using PdfDocument.Pages.Count property.
  • Output the result and close the PDF.
  • C#
using Spire.Pdf;

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

            //Load a sample PDF file 
            pdf.LoadFromFile("Contract.pdf");

            //Count the number of pages in the PDF
            int PageNumber = pdf.Pages.Count;
            Console.WriteLine("The PDF file has {0} pages", PageNumber);

            //Close the PDF
            pdf.Close();
        }
    }
}

C#: Get the Number of Pages in a PDF File

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.Presentation is a powerful and easy-to-use .NET component, especially designed for developers. Using Spire.Presentation you can generate, modify, convert, render, and print documents without installing Microsoft PowerPoint on your machine. There is a document in our website introducing you how to insert table. And in this document, I will introduce you how to remove tables within a PPT document.

Step 1: Create Presentation instance and load file.

Presentation presentation = new Presentation();
presentation.LoadFromFile("sample.ppt");

Step 2: Get the tables within the PPT document.

 List<IShape> shape_tems = new List<IShape>();
foreach (IShape shape in presentation.Slides[0].Shapes)
{
    if (shape is ITable)
    {
        //add new table to table list
        shape_tems.Add(shape);
    }
}

Step 3: Remove all tables.

foreach (IShape shape in shape_tems)
{
    presentation.Slides[0].Shapes.Remove(shape);
}

Step 4: Save the document.

presentation.SaveToFile("result.pptx", FileFormat.Pptx2010);

Download and install Spire.Presentation for .NET and refer to below code to remove tables within PPT document.

Screenshots:

Before:

Remove Table from PowerPoint document

After:

Remove Table from PowerPoint document

Full Code:

[C#]
//create Presentation instance and load file
Presentation presentation = new Presentation();
presentation.LoadFromFile("sample.ppt");

//get the tables in PowerPoint document
List<IShape> shape_tems = new List<IShape>();
foreach (IShape shape in presentation.Slides[0].Shapes)
{
    if (shape is ITable)
    {
        //add new table to table list
        shape_tems.Add(shape);
    }
}

//remove all tables
foreach (IShape shape in shape_tems)
{
    presentation.Slides[0].Shapes.Remove(shape);
}

//save the document
presentation.SaveToFile("result.pptx", FileFormat.Pptx2010);
System.Diagnostics.Process.Start("result.pptx");
[VB.NET]
'create Presentation instance and load file
Dim presentation As New Presentation()
presentation.LoadFromFile("sample.ppt")

'get the tables in PowerPoint document
Dim shape_tems As New List(Of IShape)()
For Each shape As IShape In presentation.Slides(0).Shapes
    If TypeOf shape Is ITable Then
        'add new table to table list
        shape_tems.Add(shape)
    End If
Next

'remove all tables
For Each shape As IShape In shape_tems
    presentation.Slides(0).Shapes.Remove(shape)
Next

'save the document
presentation.SaveToFile("result.pptx", FileFormat.Pptx2010)
System.Diagnostics.Process.Start("result.pptx")

If you couldn't successfully use Spire.Presentation, please refer Spire.Presentation Quick Start which can guide you quickly use Spire.Presentation.

C#/VB.NET: Edit Hyperlinks in Word

2023-01-29 08:50:00 Written by Koohji

In MS Word, a hyperlink is a clickable link that allows you to jump to a web page, a file, an email address, or even another location in the same document. It is undeniable that adding hyperlinks in Word documents is one of the most common operations in daily work, but there are times when you may also need to change the address or update the display text of an existing hyperlink. This article will demonstrate how to programmatically edit a hyperlink in 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

Edit a Hyperlink in a Word Document in C# and VB.NET

A hyperlink consists of two basic parts: the hyperlink address (URL) and its display text. With Spire.Doc for .NET, you are allowed to modify both the address and display text of an existing hyperlink using Field.Code and Field.FieldText properties. The detailed steps are as follows.

  • Create a Document object.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Create an object of List<Field>.
  • Traverse through all body child objects of sections in the sample document to find all hyperlinks.
  • Modify the address (URL) of a specified hyperlink using Field.Code property.
  • Modify the display text of a specified hyperlink using Field.FieldText property.
  • Save the document to another file using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Collections.Generic;

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

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

            //Create an object of List 
            List<Field> hyperlinks = new List<Field>();

            //Loop through the items in the sections to find all hyperlinks
            foreach (Section section in doc.Sections)
            {
                foreach (DocumentObject sec in section.Body.ChildObjects)
                {
                    if (sec.DocumentObjectType == DocumentObjectType.Paragraph)
                    {
                        //Loop through all paragraphs in the sections
                        foreach (DocumentObject para in (sec as Paragraph).ChildObjects)
                        {
                            if (para.DocumentObjectType == DocumentObjectType.Field)
                            {
                                Field field = para as Field;

                                if (field.Type == FieldType.FieldHyperlink)
                                {
                                    hyperlinks.Add(field);
                                }
                            }
                        }
                    }
                }
            }
            //Modify the address (URL) of the first hyperlink 
            hyperlinks[0].Code = "HYPERLINK \"" + "https://www.e-iceblue.com/Introduce/word-for-net-introduce.html" + "\"";

            //Modify the display text of the first hyperlink 
            hyperlinks[0].FieldText = "Spire.Doc for .NET";

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

C#/VB.NET: Edit Hyperlinks 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.

Hyperlinks can point to files, emails, websites, imagers or video when readers click on it. Hyperlinks are widely used in word document for it is very convenient to direct readers to related, useful content. By using Spire.Doc, developers can add hyperlinks, finding hyperlinks and modify hyperlinks. This article will show you how to find all the existing hyperlinks in a word document in C#.

Download and install Spire.Doc for .NET and then add Spire.Doc.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll". Here comes to the details of how to finding hyperlinks in C#.

Firstly, view the word document which contains many hyperlinks:

Finding Hyperlinks in a word document

Please check the code of how to find all the hyperlinks in word document:

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Collections.Generic;
using System.Drawing;
namespace FindHyperlink
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("Spire.docx");
            List hyperlinks = new List();
            foreach (Section section in doc.Sections)
            {
                foreach (DocumentObject sec in section.Body.ChildObjects)
                {
                    if (sec.DocumentObjectType == DocumentObjectType.Paragraph)
                    {
                        foreach (DocumentObject para in (sec as Paragraph).ChildObjects)
                        {
                            if (para.DocumentObjectType == DocumentObjectType.Field)
                            {
                                Field field = para as Field;

                                if (field.Type == FieldType.FieldHyperlink)
                                {
                                    hyperlinks.Add(field);
                                }

                            }
                        }
                    }
                }
            }
        }

The effective screenshot of the finding hyperlinks:

Finding Hyperlinks in a word document

Save a PDF file to a stream.

PDF documents are ubiquitous in modern applications, and efficient handling of these files is crucial for developers. In C#, working with PDF files using streams offers memory efficiency and flexibility, especially in web applications, cloud services, or when handling dynamic content.

Spire.PDF, a robust PDF processing library, simplifies these operations with its intuitive API. This article explores how to create, load, and save PDF documents using streams in C#, covering the following aspects.

Why Use Streams for PDF Processing?

Stream-based PDF handling in C# offers significant advantages for modern applications:

  • Memory Efficiency: Process large PDFs without loading entire files into memory.
  • Scalability: Ideal for web applications and cloud environments.
  • Reduced I/O Operations: Minimize disk reads/writes for faster performance.
  • Flexibility: Integrate with APIs, databases, and cloud storage seamlessly.

Getting Started with Spire.PDF

Spire.PDF is a feature-rich library that simplifies PDF manipulation in .NET applications. Here’s how to install it:

  • Via NuGet Package Manager (Recommended):

    In Package Manager Console, run the following command to install:

    PM> Install-Package Spire.PDF 
  • 2Manual Installation:

    Download the DLL files from the official website and add a reference to your project.

Create a PDF File and Save it to Stream in C#

This task can be divided into three main parts. Follow the steps below to dynamically create a PDF file and save it to the stream.

  • Create a PDF document.
    • Initialize an instance of the PdfDocument class to represent a PDF file.
    • Add a page to the PDF file.
  • Add content to the PDF (in this case, a simple text string).
  • 3. Save to a Stream
    • Initialize an instance of the FileStream or the MemoryStream class.
    • Call the PdfDocument.SaveToStream(Stream stream) method to save the PDF file to stream.

Code Example:

  • C#
using Spire.Pdf;
using System.IO;
using Spire.Pdf.Graphics;
using System.Drawing;

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

            // Create a PdfDocument instance
            PdfDocument pdf = new PdfDocument();

            // Add a page
            PdfPageBase page = pdf.Pages.Add();

            // Draw text on the page
            page.Canvas.DrawString("Hello, World!",
                                   new PdfFont(PdfFontFamily.Helvetica, 30f),
                                   new PdfSolidBrush(Color.Blue),
                                   100, 100);

            // Save the PDF file to Stream
            FileStream toStream = new FileStream("SavePdfToStream.pdf", FileMode.OpenOrCreate);
            pdf.SaveToStream(toStream);
            toStream.Close();
            pdf.Close();
        }
    }
}

A screenshot of the generated PDF:

Save a PDF file to a stream.

Load a PDF from Stream in C#

Streams provide a flexible way to read PDFs from different sources, such as:

  • FileStream: represents a stream of data stored in a physical file.
  • MemoryStream: represents a stream of data stored in memory (RAM).

Their differences lie in:

Feature FileStream MemoryStream
Storage Disk Memory (RAM)
Performance Slower (disk I/O) Faster (no disk access)
Use Case Persistent files, large data Temporary data, in-memory processing
Size Limit Limited by disk space Limited by available RAM

The PdfDocument.LoadFromStream(Stream stream) method of Spire.PDF library supports loading an existing PDF from a stream directly. The code example is shown below:

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

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

            // Create a PdfDocument instance
            PdfDocument pdf = new PdfDocument();

            // Load PDF file from memory stream
            MemoryStream stream = new MemoryStream();
            File.OpenRead("sample.pdf").CopyTo(stream);
            pdf.LoadFromStream(stream);

            // Load PDF file from file stream
            //FileStream stream = File.OpenRead("sample.pdf");
            //pdf.LoadFromStream(stream);

            // Save the PDF file to disk
            pdf.SaveToFile("LoadPdfFromStream.pdf", FileFormat.PDF);
            pdf.Close();
        }
    }
}

A screenshot of the loaded PDF file:

Load a PDF file from memory stream.

Advanced Example: Merge Multiple PDFs by Streams

By mastering the skills of loading and saving PDFs using streams, you can combine it with other PDF processing functions to perform advanced PDF stream operations.

Below is an example on how to combine multiple PDFs into a single document using streams:

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

namespace MergePDFsByStream
{
    class Program
    {
        static void Main(string[] args)
        {
            // Specify the files to be merged
            string[] pdfFiles = {
                "MergePdfsTemplate_1.pdf",
                "MergePdfsTemplate_2.pdf",
                "MergePdfsTemplate_3.pdf"
            };

            // Initialize FileStreams for input PDF files
            FileStream[] streams = new FileStream[pdfFiles.Length];
            for (int i = 0; i < pdfFiles.Length; i++)
            {
                streams[i] = File.OpenRead(pdfFiles[i]);
            }

            // Merge the PDF files using the streams
            PdfDocumentBase pdf = PdfDocument.MergeFiles(streams);

            // Save the merged PDF file
            pdf.Save("MergePDFByStream.pdf", FileFormat.PDF);

        }
    }
}

Conclusion

Working with PDF files in streams using C# and Spire.PDF provides a flexible and efficient way to handle document processing tasks. Whether you’re loading, modifying existing PDF documents, or saving PDF files, streams offer a memory-efficient alternative to traditional file-based approaches.

To learn more advanced PDF processing features, explore Spire.PDF’s official documentation.

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.

XLS and XLSX are two different file formats for Microsoft Excel spreadsheets. XLS is the default file format for Microsoft Excel 2003 and earlier versions, while XLSX is the default file format for Microsoft Excel 2007 and later versions. In some cases, developers may need to convert between Excel XLS and XLSX file formats. In this article, we will explain how to convert XLS to XLSX or XLSX to XLS 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

Convert XLS to XLSX in C# and VB.NET

The following are the steps to convert an XLS file to XLSX format using Spire.XLS for .NET:

  • Create a Workbook instance.
  • Load the XLS file using Workbook.LoadFromFile() method.
  • Save the XLS file to XLSX format using Workbook.SaveToFile(string, ExcelVersion) method.
  • C#
  • VB.NET
using Spire.Xls;

namespace ConvertXlsToXlsx
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook workbook = new Workbook();
            //Load an XLS file
            workbook.LoadFromFile("Input.xls");

            //Convert the file to XLSX format
            workbook.SaveToFile("ToXlsx.xlsx", ExcelVersion.Version2016);
        }
    }
}

C#/VB.NET: Convert XLS to XLSX and Vice versa

Convert XLSX to XLS in C# and VB.NET

The following are the steps to convert an XLSX file to XLS format using Spire.XLS for .NET:

  • Create a Workbook instance.
  • Load the XLSX file using Workbook.LoadFromFile() method.
  • Save the XLSX file to XLS format using Workbook.SaveToFile(string, ExcelVersion) method.
  • C#
  • VB.NET
using Spire.Xls;

namespace ConvertXlsxToXls
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook workbook = new Workbook();
            //Load an XLSX file
            workbook.LoadFromFile("Input.xlsx");

            //Convert the file to XLS format
            workbook.SaveToFile("ToXls.xls", ExcelVersion.Version97to2003);
        }
    }
}

C#/VB.NET: Convert XLS to XLSX and Vice versa

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.

Traverse through the cells of Table

2014-06-19 07:17:19 Written by Koohji

Spire.Presentation is a powerful and easy-to-use .NET component, especially designed for developers. Using Spire.Presentation you can generate, modify, convert, render, and print documents without installing Microsoft PowerPoint on your machine. There are documents on our site introducing how to insert table and edit table in PowerPoint file. In this document, I will introduce you how to traverse through the cells of table.

It is very easy to traverse through the cells of table using Spire.Presentation. Just get the row collection using the property - TableRows of Table. Then traverse through each cell of each row. Or you can get the column collection using the property – ColumnsList of Table. Then traverse through each cell of each column.

Step 1: Create Presentation instance and load file.

Presentation presentation = new Presentation();
presentation.LoadFromFile("table.pptx");

Step 2: Get the table in PowerPoint file.

foreach (IShape shape in presentation.Slides[0].Shapes)
{
    if (shape is ITable)
    {
        table = (ITable)shape;
    }
}

Step 3: Traverse through the rows in row collection and traverse through each cell in each row.

foreach (TableRow row in table.TableRows)
{
    foreach (Cell cell in row)
    {
        //print the data in cell
        Console.Write("{0,15}", cell.TextFrame.Text);
    }
    Console.WriteLine();
}

Download and install Spire.Presentation for .NET and refer to below code to traverse through the cells in PowerPoint document.

Screenshots and Full code:

Traverse through the cells of Table

Traverse through the cells of Table

[C#]
using Spire.Presentation;
using System;

namespace Trasverse
{

    class Program
    {

        static void Main(string[] args)
        {
            //create Presentation instance and load file
            Presentation presentation = new Presentation();
            presentation.LoadFromFile("table.pptx");

            ITable table = null;

            //get the table
            foreach (IShape shape in presentation.Slides[0].Shapes)
            {
                if (shape is ITable)
                {
                    table = (ITable)shape;

                    //traverse through the cells of table
                    foreach (TableRow row in table.TableRows)
                    {
                        foreach (Cell cell in row)
                        {
                            //print the data in cell
                            Console.Write("{0,15}", cell.TextFrame.Text);
                        }
                        Console.WriteLine();
                    }
                }
            }
            Console.ReadLine();

        }

    }
}

If you couldn't successfully use Spire.Presentation, please refer Spire.Presentation Quick Start which can guide you quickly use Spire.Presentation.

page 60