How to Convert Selected Range of Cells to PDF in C#, VB.NET

Using Spire.XLS, programmers are able to save the whole worksheet as PDF by calling the method SaveToPdf(). However, you may only want to save or export a part of worksheet as PDF. Since Spire.XLS doesn't provide a method to directly convert a range of cells to PDF, we can copy the selected ranges to a new worksheet and then save it as PDF file. This method seems complex, but it is still efficient with Spire.XLS.

Look at the test file below, we only want the cells from A1 to H11 converted as PDF. We will firstly create a new blank worksheet, copy the selected range to the new sheet using CellRange.Copy() method, then convert the new sheet as PDF.

How to Convert Selected Range of Cells to PDF in C#, VB.NET

Code Snippet:

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

Workbook workbook = new Workbook();
workbook.LoadFromFile("test.xlsx", ExcelVersion.Version2010);

Step 2: Add a new worksheet to workbook.

workbook.Worksheets.Add("newsheet");

Step 3: Copy the selected range from where it stores to the new worksheet.

workbook.Worksheets[0].Range["A1:H11"].Copy(workbook.Worksheets[1].Range["A1:H11"]);

Step 4: Convert the new worksheet to PDF.

workbook.Worksheets[1].SaveToPdf("result.pdf", Spire.Xls.FileFormat.PDF);

Result:

How to Convert Selected Range of Cells to PDF in C#, VB.NET

Full Code:

[C#]
Workbook workbook = new Workbook();
workbook.LoadFromFile("test.xlsx", ExcelVersion.Version2010);
// add a new sheet to workbook
workbook.Worksheets.Add("newsheet");        
//Copy your area to new sheet.
workbook.Worksheets[0].Range["A1:H11"].Copy(workbook.Worksheets[1].Range["A1:H11"]);
//convert new sheet to pdf
workbook.Worksheets[1].SaveToPdf("result.pdf", Spire.Xls.FileFormat.PDF);
[VB.NET]
Dim workbook As New Workbook()
workbook.LoadFromFile("test.xlsx", ExcelVersion.Version2010)
' add a new sheet to workbook
workbook.Worksheets.Add("newsheet")
'Copy your area to new sheet.
workbook.Worksheets(0).Range("A1:H11").Copy(workbook.Worksheets(1).Range("A1:H11"))
'convert new sheet to pdf
workbook.Worksheets(1).SaveToPdf("result.pdf", Spire.Xls.FileFormat.PDF)