There is an article in the tutorials which demonstrates how to insert textbox with contents in Excel. Sometime back, a user of Spire.XLS wanted to know if it is possible to remove the borderline of the textbox that has been inserted in Excel chart. Yes, of course. This article focuses on delivering a solution to this issue.

In the following section, we're going to create two textboxes in the same chart, one textbox is built with borderline, the other one without. Then we can learn how to remove borderline using Spire.XLS by comparison.

Code snippet for remove borderline of textbox:

Step 1: Create a new instance of workbook.

Workbook workbook = new Workbook();
workbook.Version=ExcelVersion.Version2010;

Step 2: Create a new worksheet named "Remove Borderline" and add a chart to the worksheet.

Worksheet sheet = workbook.Worksheets[0];
sheet.Name = "Remove Borderline";
Chart chart = sheet.Charts.Add();

Step 3: Create textbox1 in the chart and input text information.

XlsTextBoxShape textbox1 = chart.TextBoxes.AddTextBox(50, 50, 100, 500) as XlsTextBoxShape;

Step 4: Create textbox2 in the chart, input text information and remove borderline.

XlsTextBoxShape textbox = chart.TextBoxes.AddTextBox(500, 50, 100, 500) as XlsTextBoxShape;
textbox.Text = "The solution without borderline";
textbox.Line.Weight = 0;

Step 5: Save and launch the file.

workbook.SaveToFile("Sample.xlsx", ExcelVersion.Version2010);
Process.Start("Sample.xlsx");

Result:

Remove borderline of textbox in Excel chart in C#, VB.NET

Full code:

[C#]
using Spire.Xls;
using Spire.Xls.Core.Spreadsheet.Shapes;
using System.Diagnostics;

namespace RemoveBorderlineofTextbox
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new workbook
            Workbook workbook = new Workbook();
            workbook.Version = ExcelVersion.Version2010;
            // Get the first worksheet and rename it
            Worksheet sheet = workbook.Worksheets[0];
            sheet.Name = "Remove Borderline";
            // Add a chart to the worksheet
            Chart chart = sheet.Charts.Add();
            // Add the first text box (with visible border)
            XlsTextBoxShape textbox1 = chart.TextBoxes.AddTextBox(50, 50, 100, 500) as XlsTextBoxShape ;
            textbox1.Text = "The original with borderline";
            // Add the second text box (border will be hidden)
            XlsTextBoxShape textbox2 = chart.TextBoxes.AddTextBox(500, 50, 100, 500) as XlsTextBoxShape;
            textbox2.Text = "The solution without borderline";
            // Hide the border by setting line weight to 0
            textbox2.Line.Weight = 0;
            // Save the result file
            workbook.SaveToFile("Sample.xlsx", ExcelVersion.Version2010);
            Process.Start("Sample.xlsx");
        }
    }
}
[VB.NET]
Imports Spire.Xls
Imports Spire.Xls.Core.Spreadsheet.Shapes
Imports System.Diagnostics
Namespace RemoveBorderlineofTextbox
	Class Program

		Private Shared Sub Main(args As String())
			'Create a new workbook
			Dim workbook As New Workbook()
			workbook.Version = ExcelVersion.Version2010
			'  Get the first worksheet And rename it
			Dim sheet As Worksheet = workbook.Worksheets(0)
			sheet.Name = "Remove Borderline"
			'  Add a chart to the worksheet
			Dim chart As Chart = sheet.Charts.Add()
			'  Add the first text box (with visible border)
			Dim textbox1 As XlsTextBoxShape = TryCast(chart.TextBoxes.AddTextBox(50, 50, 100, 500), XlsTextBoxShape)
			textbox1.Text = "The original with borderline"
			'Add the second text box (border will be hidden)
			Dim textbox2 As XlsTextBoxShape = TryCast(chart.TextBoxes.AddTextBox(500, 50, 100, 500), XlsTextBoxShape)
			textbox2.Text = "The solution without borderline"
			'Hide the border by setting line weight to 0
			textbox2.Line.Weight = 0
			'Save the result file
			workbook.SaveToFile("Sample.xlsx", ExcelVersion.Version2010)
			Process.Start("Sample.xlsx")

		End Class
End Namespace

Various kinds of shapes like triangle, rectangle, ellipse, star, line and etc, can be created with Spire.Presentation. To make shapes more compatible with the entire slide, not only can we set color and choose fill style of the shape, we can also rotate shapes to a desired degree. This article is aimed to provide a simple example.

To begin with, create or open a .NET class application in Visual Studio 2005 or above versions, add Spire.Presentation.dll to your .NET project assemblies. Then, you are able create and format shapes using the sample C# code we have offered below.

Code snippets for rotate shapes on slide:

Step 1: Create an instance of Presentation class.

Presentation presentation = new Presentation();

Step 2: Add a new shape - Triangle ,to PPT slide.

IAutoShape shape = presentation.Slides[0].Shapes.AppendShape(ShapeType.Triangle, new RectangleF(100, 100, 100, 100));

Step 3: Rotate the shape to 180 degree.

shape.Rotation = 180;  

Step 4: Set the color and fill style of shape.

shape.Fill.FillType = FillFormatType.Solid;
shape.Fill.SolidColor.Color = Color.BlueViolet;
shape.ShapeStyle.LineColor.Color = Color.Black;

Step 5: Save and launch the file.

presentation.SaveToFile("shape.pptx", FileFormat.Pptx2010);
System.Diagnostics.Process.Start("shape.pptx");

Effect Screenshot:

Rotate Shapes on PowerPoint Slide with .NET

Full code:

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

namespace RotateShape
{

    class Program
    {

        static void Main(string[] args)
        {
           //create PPT document 
            Presentation presentation = new Presentation();

            //append new shape - Triangle
            IAutoShape shape = presentation.Slides[0].Shapes.AppendShape(ShapeType.Triangle, new RectangleF(100, 100, 100, 100));                     
            //set rotation to 180
            shape.Rotation = 180;  

            //set the color and fill style of shape
            shape.Fill.FillType = FillFormatType.Solid;
            shape.Fill.SolidColor.Color = Color.BlueViolet;
            shape.ShapeStyle.LineColor.Color = Color.Black;

            //save the document
            presentation.SaveToFile("shape.pptx", FileFormat.Pptx2010);
            System.Diagnostics.Process.Start("shape.pptx");
        }

        }
    }
[VB.NET]
Imports Spire.Presentation
Imports Spire.Presentation.Drawing
Imports System.Drawing

Namespace RotateShape

	Class Program

		Private Shared Sub Main(args As String())
			'create PPT document 
			Dim presentation As New Presentation()

			'append new shape - Triangle
			Dim shape As IAutoShape = presentation.Slides(0).Shapes.AppendShape(ShapeType.Triangle, New RectangleF(100, 100, 100, 100))
			'set rotation to 180
			shape.Rotation = 180

			'set the color and fill style of shape
			shape.Fill.FillType = FillFormatType.Solid
			shape.Fill.SolidColor.Color = Color.BlueViolet
			shape.ShapeStyle.LineColor.Color = Color.Black

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

	End Class
End Namespace

Replace Text in Word with Table in C#

2014-08-07 03:54:58 Written by Koohji

This topic is just another request from one of our users on Spire.Doc Forum. In order to let more people know about this function, we’re going to present the whole procedure through a sample demo in the article. Additionally, we would like to remind you that we offer free customized demo for both pay users and test users.

As a professional .NET Word component, Spire.Doc enables developers to replace specified paragraph with a newly created table or an existing table. In this example, the paragraph 3 in main body of the sample word file will be replaced by a newly-built table.

Test file:

Replace Text in Word with Table in C#

Code snippets for replacing text with table:

Step 1: Create a new word document and load the test file.

Document doc = new Document();
doc.LoadFromFile(@"..\..\test.docx");

Step 2: Return TextSection by finding the key text string "classical antiquity science".

Section section = doc.Sections[0];     
TextSelection selection = doc.FindString("classical antiquity science", true, true);

Step 3: Return TextRange from TextSection, then get OwnerParagraph through TextRange.

TextRange range = selection.GetAsOneRange();
Paragraph paragraph = range.OwnerParagraph;

Step 4: Return the zero-based index of the specified paragraph.

Body body = paragraph.OwnerTextBody;
int index = body.ChildObjects.IndexOf(paragraph);

Step 5: Create a new table.

Table table = section.AddTable(true);
table.ResetCells(3, 3);

Step 6: Remove the paragraph and insert table into the collection at the specified index.

body.ChildObjects.Remove(paragraph);
body.ChildObjects.Insert(index, table);

Step 7: Save and launch the file.

doc.SaveToFile("result.doc", FileFormat.Doc);
System.Diagnostics.Process.Start("result.doc");

Result:

Replace Text in Word with Table in C#

Full C# code:

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace ReplaceText
{

    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile(@"..\..\test.docx");
            Section section = doc.Sections[0];
            TextSelection selection = doc.FindString("classical antiquity science", true, true);
            TextRange range = selection.GetAsOneRange();
            Paragraph paragraph = range.OwnerParagraph;
            Body body = paragraph.OwnerTextBody;
            int index = body.ChildObjects.IndexOf(paragraph);

            Table table = section.AddTable(true);
            table.ResetCells(3, 3);
            body.ChildObjects.Remove(paragraph);
            body.ChildObjects.Insert(index, table);

            doc.SaveToFile("result.doc", FileFormat.Doc);
            System.Diagnostics.Process.Start("result.doc");

        }
    }
}

Word bookmarks are widely used for point out a specified location or give brief information of the paragraph. If you add an image into the bookmark position, the bookmarks will be more obviously and clearly. This article will show you how to insert an image at bookmark position in C# with the help of Spire.Doc.

Spire.Doc offers an instance of BookmarksNavigator to find the bookmarks, and then developers use AppendPicture to add an image. Here comes to the steps:

Step 1: Load a word documents with bookmarks.

Document document = new Document();
document.LoadFromFile("Test.docx");

Step 2: Create an instance of BookmarksNavigator and find the bookmark where you want to insert an image.

//Create an instance of BookmarksNavigator
BookmarksNavigator bn = new BookmarksNavigator(document);
//Find a bookmark and its name is Spire
bn.MoveToBookmark("Spire", true, true);

Step 3: Insert an image at the position of bookmarks you found.

//Add a section and named it section0
Section section0 = document.AddSection();
//Add a paragraph for section0
Paragraph paragraph = section0.AddParagraph();
Image image = Image.FromFile("step.png");
//Add a picture into paragraph
DocPicture picture = paragraph.AppendPicture(image);
//Add a paragraph with picture at the position of bookmark
bn.InsertParagraph(paragraph);
document.Sections.Remove(section0);

Step 4: Save the new document and process it.

string output = "sample3.docx";
document.SaveToFile(output, FileFormat.Docx);
System.Diagnostics.Process.Start(output);

Spire.Doc also offers the following properties to set the image position based on developers' requirements.

picture.TextWrappingStyle
picture.HorizontalAlignment
picture.HorizontalOrigin
picture.HorizontalPosition
picture.VerticalAlignment
picture.VerticalOrigin
picture.VerticalPosition

Effective screenshot:

Insert an image at bookmark in word documents

Full codes:

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
namespace InsertImage
{
    class Program
    {

        static void Main(string[] args)
        {

            Document document = new Document();
            document.LoadFromFile("Test.docx");
            BookmarksNavigator bn = new BookmarksNavigator(document);
            bn.MoveToBookmark("Spire", true, true);
            Section section0 = document.AddSection();
            Paragraph paragraph = section0.AddParagraph();
            Image image = Image.FromFile("step.png");
            DocPicture picture = paragraph.AppendPicture(image);
            bn.InsertParagraph(paragraph);
            document.Sections.Remove(section0);
            string output = "sample.docx";
            document.SaveToFile(output, FileFormat.Docx);
            System.Diagnostics.Process.Start(output);
        }
    }
}

Bookmarks give convenience when users want go to specified location and it is clearly to know the contents brief information. Spire.Doc for .NET has a powerful function of operating the word elements of bookmarks. Developers can add bookmarks, Edit/replace bookmarks and remove bookmarks in word documents. Now Spire.Doc starts to support preserve bookmarks in DOCX to PDF conversion. This article will show you how to preserve bookmarks in C# when converting word document into PDF file format.

Download and install Spire.Doc for .NET (Version 5.2.20 or above) 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 preserve the bookmarks from word to PDF conversion in C#.

Step 1: Load a word documents with bookmarks.

Document doc = new Document();
doc.LoadFromFile("test.docx", FileFormat.Docx);

Step 2: Create an instance of ToPdfParameterList

ToPdfParameterList toPdf = new ToPdfParameterList();

Step 3: Set CreateWordBookmarks to true to use word bookmarks when create the bookmarks.

toPdf.CreateWordBookmarks = true;

Step 4: Save the PDF file.

doc.SaveToFile("test.Pdf",toPdf);

Effective screenshot of preserve the bookmarks in result PDF page:

Preserve bookmarks in PDF from word

Full codes:

[C#]
using Spire.Doc;
namespace PreventBookmark
{
    class Program
    {

        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("test.docx", FileFormat.Docx);
            ToPdfParameterList toPdf = new ToPdfParameterList();
            toPdf.CreateWordBookmarks = true;
            doc.SaveToFile("test.Pdf", toPdf);
            System.Diagnostics.Process.Start("test.Pdf");

        }
    }
}

As is shown in the following presentation slide, shapes automatically stack in separate layers as you add them. To change the order of overlapping shapes, we can move the layers forward and backward. But how can we achieve this task programmatically using C# or VB.NET? This article is aimed to present you a solution on how to reorder overlapping shapes using Spire.Presentation.

Reorder overlapping shapes in presentation

In the early edition, Spire.Presentation is already capable of adding different kinds of shapes to the slides, setting color and fill style of the shape. In the Version2.0.18, we add reordering overlapping shapes as a new feature to satisfy our customer’s demands. Now, let’s see how to make it happen with sample code snippet.

Step 1: Create a new instance of Spire.Presentation class and load the test file.

Spire.Presentation.Presentation presentation = new Presentation();
presentation.LoadFromFile("..\\..\\test.pptx");

Step 2: Get the first shape from the slide.

IShape shape = presentation.Slides[0].Shapes[0];

Step 3: Change the shape's Zorder by setting its position index.

presentation.Slides[0].Shapes.ZOrder(1, shape);

Step 4: Save to a PPTX file and launch the file.

string output = "output.pptx";
presentation.SaveToFile(output,FileFormat.Pptx2010);
System.Diagnostics.Process.Start(output);

Output:

Reorder overlapping shapes in presentation

Full code:

[C#]
using Spire.Presentation;

namespace ReorderOverlappingShape
{

    class Program
    {

        static void Main(string[] args)
        {
            //Create an instance of Spire.Presentation
            Spire.Presentation.Presentation presentation = new Presentation();
            //Load a pptx file
            presentation.LoadFromFile("..\\..\\test.pptx");

            //Get the first shape of the first slide
            IShape shape = presentation.Slides[0].Shapes[0];
            //Change the shape's zorder
            presentation.Slides[0].Shapes.ZOrder(1, shape);

            //Save to a pptx2010 file.
            string output = "output.pptx";
            presentation.SaveToFile(output, FileFormat.Pptx2010);
            //Launch the output file
            System.Diagnostics.Process.Start(output);

        }
    }
}
[VB.NET]
Imports Spire.Presentation

Namespace ReorderOverlappingShape

	Class Program

		Private Shared Sub Main(args As String())
			'Create an instance of Spire.Presentation
			Dim presentation As Spire.Presentation.Presentation = New Presentation()
			'Load a pptx file
			presentation.LoadFromFile("..\..\test.pptx")

			'Get the first shape of the first slide
			Dim shape As IShape = presentation.Slides(0).Shapes(0)
			'Change the shape's zorder
			presentation.Slides(0).Shapes.ZOrder(1, shape)

			'Save to a pptx2010 file.
			Dim output As String = "output.pptx"
			presentation.SaveToFile(output, FileFormat.Pptx2010)
			'Launch the output file
			System.Diagnostics.Process.Start(output)

		End Sub
	End Class
End Namespace

Everytime we try to open a password-protected PowerPoint file, we will then be prompted to enter the password. This can be really a bothering thing itself. But things get worse if we forget the password. To avoid this situation from being occurred, we can choose to remove the encryption if the PowerPoint file is not necessarily protected. In this article, I’ll introduce you how to remove encryption on password-protected PowerPoint file using Spire.Presentation.

In the classes of Spire.Presentation, you can invoke Presentation.LoadFromFile(string file, string password) method to load the file that you want to remove protection, then you're entitled to remove encryption by calling Presentation.RemoveEncryption() method. More details:

Step 1: Create Presentation instance and load file.

Presentation presentation = new Presentation();
presentation.LoadFromFile("Presentation1.pptx", "test");

Step 2: Remove encryption.

presentation.RemoveEncryption();

Step 3: Save and launch the file.

presentation.SaveToFile("result.pptx", FileFormat.Pptx2010);
System.Diagnostics.Process.Start("result.pptx");

Effect Screenshot:

Remove Encryption on Password-Protected PowerPoint File

Full Code:

[C#]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Presentation;

namespace RemoveProtect
{
    class Program
    {
        static void Main(string[] args)
        {
            // create Presentation instance and load file
            Presentation presentation = new Presentation();
            presentation.LoadFromFile("Presentation1.pptx", "test");

            //remove encryption
            presentation.RemoveEncryption();

            //save the file
            presentation.SaveToFile("result.pptx", FileFormat.Pptx2010);
            System.Diagnostics.Process.Start("result.pptx");
        }
    }
}
[VB.NET]
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports Spire.Presentation
 
Namespace RemoveProtect
    Class Program
        Shared  Sub Main(ByVal args() As String)
            ' create Presentation instance and load file
            Dim presentation As Presentation =  New Presentation() 
            presentation.LoadFromFile("Presentation1.pptx", "test")
 
            'remove encryption
            presentation.RemoveEncryption()
 
            'save the file
            presentation.SaveToFile("result.pptx", FileFormat.Pptx2010)
            System.Diagnostics.Process.Start("result.pptx")
        End Sub
    End Class
End Namespace

Merge table cells on PowerPoint Slide

2014-07-25 07:07:42 Written by Koohji

A table, as a great way to present data into groups, always plays an important role in any type of electronic documents. A well formatted table must contains larger or smaller cells without influencing the entire row or colum - and that's something that can be easily achieved by merging or splitting cells in your existing table.

In the next section, we will introduce you how to merge cells on en existing table which is embedded on a PowerPoint slide using Spire.Presentation for .NET. By convention, we need to download and install Spire.Presentation first, add its dll as a reference in you Visual C# or VB.NET project.

Assume you got a sample PPT file which contains a table like this, obviously you can merge cell 2 and cell 3 in the first column to display the account information more clearly.

Merge table cells on PowerPoint Slide

How to achieve this programmatically using Spire.Presentation?

Step 1: Create a PPT document and load the sample file.

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

Step 2: Get the table and merge the second row and third row of the first column.

ITable table = null;

foreach (IShape shape in presentation.Slides[0].Shapes)
{
  if (shape is ITable)
    {
      table = (ITable)shape;
      table.MergeCells(table[0, 1], table[0, 2], false);

    }
}

Step 3: Save and launch the file.

presentation.SaveToFile("result.pptx", FileFormat.Pptx2010);
System.Diagnostics.Process.Start("result.pptx");

Result:

Merge table cells on PowerPoint Slide

Full code:

[C#]
using Spire.Presentation;

namespace MergeCells
{

    class Program
    {

        static void Main(string[] args)
        {
            // create a PPT document and load file
            Presentation presentation = new Presentation();
            presentation.LoadFromFile("table.pptx");
            // get the table in PPT document
            ITable table = null;
            foreach (IShape shape in presentation.Slides[0].Shapes)
            {
                if (shape is ITable)
                {
                    table = (ITable)shape;
                    //merge the second row and third row of the first column
                    table.MergeCells(table[0, 1], table[0, 2], false);

                }
            }

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

        }

    }
}
[VB.NET]
Imports Spire.Presentation

Namespace MergeCells

	Class Program

		Private Shared Sub Main(args As String())
			' create a PPT document and load file
			Dim presentation As New Presentation()
			presentation.LoadFromFile("table.pptx")
			' get the table in PPT document
			Dim table As ITable = Nothing
			For Each shape As IShape In presentation.Slides(0).Shapes
				If TypeOf shape Is ITable Then
					table = DirectCast(shape, ITable)
					'merge the second row and third row of the first column

					table.MergeCells(table(0, 1), table(0, 2), False)
				End If
			Next

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

		End Sub

	End Class
End Namespace

Pivot table displays the data in sort, count total or give the average of the data stored in one table or spreadsheet. So it gives readers clear information of the data's trends and patterns rather than a large amount of similar data. Sometimes, there are so many rows in one pivot table and we may need to expand or collapse them to make the pivot table more clearly.

By using Spire.XLS for .NET, developers can create pivot table. This article will show you how to expand and collapse the rows in an existing Pivot table in C#.

Firstly, make sure that Spire.XLS for .NET (version7.5.5 or above) has been installed on your machine. And then, adds Spire.XLS.dll as reference in the downloaded Bin folder thought the below path: "..\Spire.XLS\Bin\NET4.0\ Spire.XLS.dll".

//Create a new excel document
Workbook book = new Workbook();

//load an excel document with Pivot table from the file
book.LoadFromFile("test.xlsx");

//Find the Pivot Table sheet
Worksheet sheet = book.Worksheets["Pivot Table"];

//Get the data in Pivot Table
Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotTable pivotTable = sheet.PivotTables[0] as Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotTable;

//Calculate Data
pivotTable.CalculateData();

//Collapse the rows
(pivotTable.PivotFields["Vendor No"] as Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotField).HideItemDetail("1501", true);

//Expand the rows
(pivotTable.PivotFields["Vendor No"] as Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotField).HideItemDetail("1502", false);

//Save the document to file
book.SaveToFile("result.xlsx", ExcelVersion.Version2007);

Effective screenshots:

Collapse the rows in Pivot table in C#

Collapse the rows in Pivot table in C#

Expand the rows in Pivot table in C#

Expand the rows in Pivot table in C#

Full codes:

using Spire.Xls;

namespace HighlightValues
{
    class  Program
    {
        static void Main(string[] args)
        {
            Workbook book = new Workbook();
            book.LoadFromFile("test.xlsx");
            Worksheet sheet = book.Worksheets["Pivot Table"];

            Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotTable pivotTable = sheet.PivotTables[0] as Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotTable;
            pivotTable.CalculateData();
            (pivotTable.PivotFields["Vendor No"] as Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotField).HideItemDetail("1501", true);
            (pivotTable.PivotFields["Vendor No"] as Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotField).HideItemDetail("1502", true);

            book.SaveToFile("result_1.xlsx", ExcelVersion.Version2007);

            (pivotTable.PivotFields["Vendor No"] as Spire.Xls.Core.Spreadsheet.PivotTables.XlsPivotField).HideItemDetail("1502", false);
            book.SaveToFile("result_2.xlsx", ExcelVersion.Version2007);
        }
    }
}

Tutorial on How to Convert Tiff to PDF Using C#

Converting TIFF to PDF using C# is a common requirement in .NET document processing workflows. Developers often need to transform scanned documents or multi-page TIFF files into PDF format for better compatibility, easier distribution, and standardized document management.

TIFF files are widely used in scanning and archiving systems, especially for storing multiple pages in a single file. However, they are not always ideal for sharing or cross-platform viewing, while PDF provides a more universal and consistent format.

With Spire.PDF for .NET, you can efficiently convert TIFF images to PDF using simple and reliable C# code. This article demonstrates how to perform TIFF to PDF conversion in .NET, including handling multi-page TIFF images, adjusting page layouts, and applying best practices for real-world applications.


1. Understanding the Task

TIFF (Tagged Image File Format) is a flexible image format that supports multiple pages within a single file. This makes it popular for:

  • Scanned documents: Multi-page contracts, invoices, and forms
  • Document archiving: Preserving document history in a single file
  • Medical imaging: Storing diagnostic images with multiple views
  • Fax transmissions: Traditional fax systems often use TIFF format

Converting TIFF to PDF offers several advantages:

  • Universal compatibility: PDF viewers are available on all platforms
  • Smaller file size: PDF compression can reduce storage requirements
  • Better distribution: PDF is the standard for document sharing
  • Enhanced security: PDF supports encryption and access controls

2. Convert TIFF to PDF Using Spire.PDF

This section provides step-by-step examples for converting TIFF images to PDF using Spire.PDF in C#.

Install Spire.PDF for .NET

First, install the library via NuGet Package Manager:

Install-Package FreeSpire.PDF

Or using the .NET CLI:

dotnet add package FreeSpire.PDF

You can also download the Spire.PDF for .NET package and add it to your project manually.

Convert a Single-Page TIFF to PDF

For single-page TIFF files, the simplest approach is to create a PDF page that matches the original image dimensions and draw the image directly onto it. This ensures the TIFF content fills the entire PDF page without unwanted margins or scaling issues.

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

// Load the TIFF image
PdfImage tiffImage = PdfImage.FromFile("Sample_Page.tiff");

// Create a new PDF document
PdfDocument pdf = new PdfDocument();

// Remove default page margins
pdf.PageSettings.Margins.All = 0;

// Get image dimensions
float width = tiffImage.PhysicalDimension.Width;
float height = tiffImage.PhysicalDimension.Height;

// Add a PDF page with the same size as the TIFF image
PdfPageBase page = pdf.Pages.Add(new SizeF(width, height));

// Draw the image to fully fill the page
page.Canvas.DrawImage(tiffImage, 0, 0, width, height);

// Save the PDF document
pdf.SaveToFile("Sample_Page.pdf");
pdf.Close();

Convert Single-Page TIFF to PDF

Key API calls:

  • PdfImage.FromFile: Loads the TIFF image into a PDF-compatible object
  • PageSettings.Margins.All: Removes default margins to allow full-page rendering
  • Pages.Add(SizeF): Creates a PDF page that matches the TIFF dimensions
  • Canvas.DrawImage: Draws the TIFF image to completely fill the page
  • SaveToFile: Saves the converted PDF file

This method preserves the original TIFF dimensions and ensures the output PDF displays the image cleanly across the full page.

For more image-to-PDF scenarios, see how to convert images to PDF in C#.

Convert Multi-Page TIFF to PDF

Multi-page TIFF files contain multiple frames, with each frame representing a separate page. During conversion, you can iterate through each frame and create a PDF page that matches the dimensions of the current TIFF frame to preserve the original layout.

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

// Load the multi-page TIFF file
Image tiffImage = Image.FromFile("Sample89.tiff");

// Get frame information
FrameDimension dimension = new FrameDimension(tiffImage.FrameDimensionsList[0]);
int frameCount = tiffImage.GetFrameCount(dimension);

// Create a new PDF document
PdfDocument pdf = new PdfDocument();

// Remove default margins
pdf.PageSettings.Margins.All = 0;

// Process each TIFF frame
for (int i = 0; i < frameCount; i++)
{
    // Select current frame
    tiffImage.SelectActiveFrame(dimension, i);

    // Convert current frame to PdfImage
    PdfImage pdfImage = PdfImage.FromImage(tiffImage);

    // Get current frame dimensions
    float width = pdfImage.PhysicalDimension.Width;
    float height = pdfImage.PhysicalDimension.Height;

    // Create a PDF page matching the frame size
    PdfPageBase page = pdf.Pages.Add(new SizeF(width, height));

    // Draw the frame to fill the page
    page.Canvas.DrawImage(pdfImage, 0, 0, width, height);
}

// Save the PDF document
pdf.SaveToFile("Sample89.pdf");
pdf.Close();

// Release resources
tiffImage.Dispose();

Convert Multi-Page TIFF to PDF

Key concepts:

  • FrameDimension: Identifies the frame collection in a multi-page TIFF file
  • GetFrameCount: Retrieves the total number of TIFF pages
  • SelectActiveFrame: Switches to a specific TIFF frame for processing
  • Pages.Add(SizeF): Creates a PDF page that matches each TIFF page size
  • Canvas.DrawImage: Renders each TIFF frame onto the corresponding PDF page

This approach preserves all pages in the original TIFF file while ensuring each page fully occupies the PDF canvas without extra margins or scaling issues.

Fit TIFF Images into Standard PDF Pages

In some workflows, the output PDF must follow a standard page size such as A4 or Letter for printing, document sharing, or archival purposes. Instead of creating a PDF page based on the original TIFF dimensions, you can scale the image proportionally to fit within a fixed page size while keeping it horizontally centered.

using Spire.Pdf;
using Spire.Pdf.Graphics;

PdfDocument pdf = new PdfDocument();
PdfImage image = PdfImage.FromFile("Sample_Page.tiff");

// Create an A4 page with margins
PdfPageBase page = pdf.Pages.Add(PdfPageSize.A4, new PdfMargins(20));

// Calculate proportional scaling
float scale = Math.Min(
    page.Canvas.ClientSize.Width / image.PhysicalDimension.Width,
    page.Canvas.ClientSize.Height / image.PhysicalDimension.Height
);

// Calculate final image size
float width = image.PhysicalDimension.Width * scale;
float height = image.PhysicalDimension.Height * scale;

// Center horizontally and align to the top
float x = (page.Canvas.ClientSize.Width - width) / 2;

// Draw image onto the PDF page
page.Canvas.DrawImage(image, x, 0, width, height);

// Save the PDF file
pdf.SaveToFile("Sample89.pdf");
pdf.Close();

The Generated PDF will fit the standard page size while maintaining the original image dimensions.

Fit TIFF Images into Standard PDF Pages

Why use this approach?

  • Standardized output: Ensures all converted PDFs use consistent page sizes such as A4 or Letter
  • Better for printing: Prevents unusually sized PDF pages caused by large TIFF dimensions
  • Maintains aspect ratio: Scales the image proportionally without distortion
  • Cleaner document formatting: Keeps content properly aligned for business and archival workflows

This method works well when you need TIFF files to fit standardized PDF layouts rather than preserving their original dimensions.

You can also explore more PDF layout and page settings tutorials using C#.


3. Advanced TIFF to PDF Conversion Scenarios

For production applications, you often need additional control over the conversion process.

Batch Convert Multiple TIFF Files

In document management systems, scanned archives, or automated workflows, you may need to convert multiple TIFF files into PDF format at once. The following example processes all TIFF files in a folder and converts each file into a separate PDF while preserving the original image dimensions.

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

string inputFolder = @"C:\Documents\TIFF";
string outputFolder = @"C:\Documents\PDF";

// Create the output folder if it doesn't exist
Directory.CreateDirectory(outputFolder);

// Process all TIFF files in the folder
foreach (string tiffFile in Directory.GetFiles(inputFolder, "*.tiff"))
{
    PdfImage image = PdfImage.FromFile(tiffFile);

    using (PdfDocument pdf = new PdfDocument())
    {
        // Create a PDF page matching the TIFF dimensions
        PdfPageBase page = pdf.Pages.Add(
            new SizeF(
                image.PhysicalDimension.Width,
                image.PhysicalDimension.Height
            )
        );

        // Draw the TIFF image onto the page
        page.Canvas.DrawImage(
            image,
            0,
            0,
            image.PhysicalDimension.Width,
            image.PhysicalDimension.Height
        );

        // Generate output file path
        string outputFile = Path.Combine(
            outputFolder,
            Path.GetFileNameWithoutExtension(tiffFile) + ".pdf"
        );

        // Save PDF
        pdf.SaveToFile(outputFile);
    }
}

Why use batch conversion?

  • Automatically processes large numbers of TIFF files
  • Reduces manual conversion work
  • Preserves original image dimensions for each file
  • Useful for archive migration and document automation workflows

This method works well for converting large collections of single-page TIFF files. If your folder contains multi-page TIFF documents, you can combine this approach with the multi-page conversion logic introduced earlier.

Merge Multiple TIFF Files into One PDF

If you need to combine several TIFF images into a single PDF document, you can add each TIFF file as a separate PDF page. This is useful when consolidating scanned documents, invoices, or image-based reports into one file.

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

string[] tiffFiles =
{
    "Page1.tiff",
    "Page2.tiff",
    "Page3.tiff"
};

PdfDocument pdf = new PdfDocument();

foreach (string file in tiffFiles)
{
    PdfImage image = PdfImage.FromFile(file);

    float width = image.PhysicalDimension.Width;
    float height = image.PhysicalDimension.Height;

    // Create page matching TIFF dimensions
    PdfPageBase page = pdf.Pages.Add(new SizeF(width, height));

    // Draw TIFF image
    page.Canvas.DrawImage(image, 0, 0, width, height);
}

// Save merged PDF
pdf.SaveToFile("CombinedDocument.pdf");
pdf.Close();

Benefits of merging TIFF files:

  • Combine multiple scanned pages into one PDF
  • Simplify document sharing
  • Preserve original image quality
  • Useful for contracts, invoices, and archived records

This method works best when each TIFF file should appear as an individual page in a single PDF document.

If you need to combine multiple converted PDF files into one document, you can also check how to merge PDF files in C#.

Handle Large TIFF Files Efficiently

Large multi-page TIFF files can consume significant memory during conversion. To improve performance, process each frame sequentially and release resources immediately after use.

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

// Process large TIFF files efficiently
using (Image tiffImage = Image.FromFile("LargeDocument.tiff"))
using (PdfDocument pdf = new PdfDocument())
{
    FrameDimension dimension =
        new FrameDimension(tiffImage.FrameDimensionsList[0]);

    int frameCount = tiffImage.GetFrameCount(dimension);

    for (int i = 0; i < frameCount; i++)
    {
        // Activate current frame
        tiffImage.SelectActiveFrame(dimension, i);

        using (PdfImage image = PdfImage.FromImage(tiffImage))
        {
            float width = image.PhysicalDimension.Width;
            float height = image.PhysicalDimension.Height;

            // Create page matching frame size
            PdfPageBase page = pdf.Pages.Add(
                new SizeF(width, height)
            );

            // Draw current frame
            page.Canvas.DrawImage(
                image,
                0,
                0,
                width,
                height
            );
        }
    }

    pdf.SaveToFile("LargeDocument.pdf");
}

Memory optimization tips:

  • Use using statements to automatically release resources
  • Process TIFF frames one at a time
  • Avoid loading multiple large images simultaneously
  • Improve performance when converting high-resolution scanned documents

This approach is particularly useful for large archival TIFF files, medical scans, and enterprise document migration tasks.


4. Common Issues and Solutions

When converting TIFF to PDF, developers may encounter the following issues.

Multi-Page TIFF Not Fully Converted

Symptoms: Only the first page appears in the PDF output.

Cause: Frames in the TIFF file are not properly iterated.

Solution: Use GetFrameCount and SelectActiveFrame to process each frame.

int frameCount = tiffImage.GetFrameCount(dimension);

for (int i = 0; i < frameCount; i++)
{
    tiffImage.SelectActiveFrame(dimension, i);
    // Process each frame
}

Image Distortion or Layout Issues

Symptoms: Image appears stretched or does not fit properly in the PDF page.

Cause: Incorrect scaling when fitting TIFF into a fixed-size page (e.g., A4).

Solution: Use proportional scaling while keeping aspect ratio.

float scale = Math.Min(
    page.Canvas.ClientSize.Width / image.PhysicalDimension.Width,
    page.Canvas.ClientSize.Height / image.PhysicalDimension.Height
);

float width = image.PhysicalDimension.Width * scale;
float height = image.PhysicalDimension.Height * scale;

High Memory Usage with Large Files

Symptoms: Slow performance or memory issues when processing large TIFF files.

Cause: Loading multi-page TIFF into memory without proper disposal.

Solution: Process frames sequentially and release resources promptly.

using (Image tiffImage = Image.FromFile("Large.tiff"))
using (PdfDocument pdf = new PdfDocument())
{
    // Process frames one by one
}

Unsupported TIFF Format

Symptoms: Errors occur when loading certain TIFF files.

Cause: Non-standard compression or color formats in the TIFF file.

Solution: Ensure the TIFF uses standard formats supported by the library.


Conclusion

Converting TIFF to PDF in C# is a straightforward process with Spire.PDF for .NET. The library provides efficient methods for handling both single-page and multi-page TIFF files while maintaining image quality and layout accuracy.

By following the examples and best practices demonstrated in this article, developers can implement reliable TIFF to PDF conversion for various scenarios including document archiving, batch processing, and enterprise document management systems.

If you want to evaluate the functionality of Spire.PDF for .NET, you can apply for a free trial license.


FAQ

How do I convert a multi-page TIFF to PDF in C#?

Use FrameDimension to access each frame in the TIFF file, then create a separate PDF page for each frame. The GetFrameCount method returns the total number of frames, and SelectActiveFrame allows you to process each frame individually.

What is the best approach for converting TIFF to PDF in .NET?

Using a dedicated library like Spire.PDF for .NET provides the most reliable and efficient solution. It handles image loading and PDF generation with minimal code while supporting multi-page TIFF files.

Does converting TIFF to PDF reduce file size?

PDF compression can reduce file size compared to uncompressed TIFF files. However, the actual size reduction depends on the original TIFF compression, image content, and PDF settings. High-resolution images may still result in large PDF files.

Can I convert TIFF to PDF without installing Microsoft Office or additional software?

Yes. Spire.PDF for .NET operates independently and does not require Microsoft Office, Adobe Acrobat, or any other external software. It performs all conversion operations using its own rendering engine.

How can I maintain image quality when converting TIFF to PDF?

To preserve image quality, avoid unnecessary scaling and match PDF page dimensions to the TIFF image size for best results.

page 59