C#/VB.NET: Convert CSV to PDF

2022-07-07 08:46:00 Written by  support iceblue
Rate this item
(0 votes)

CSV is one of the commonly used file formats for exchanging tabular data between applications. However, in some circumstances, CSV may not be the most appropriate file format. For instance, if you have a CSV report that needs to be sent to an important customer, the best way to ensure the file appears as-is on the customer's device is to convert it to PDF. This article will demonstrate how to convert CSV to PDF 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 CSV to PDF in C# and VB.NET

The following are the steps to convert a CSV file to PDF:

  • Create an instance of Workbook class.
  • Load the CSV file using Workbook.LoadFromFile(filePath, separator) method.
  • Set the Workbook.ConverterSetting.SheetFitToPage property as true to ensure the worksheet is rendered to one PDF page.
  • Get the first worksheet in the Workbook using Workbook.Worksheets[0] property.
  • Loop through the columns in the worksheet and auto-fit the width of each column using Worksheet.AutoFitColumn() method.
  • Save the worksheet to PDF using Worksheet.SaveToPdf() method.
  • C#
  • VB.NET
using Spire.Xls;

namespace ConvertCsvToPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook wb = new Workbook();
            //Load a CSV file
            wb.LoadFromFile("Sample.csv", ",");

            //Set SheetFitToPage property as true to ensure the worksheet is converted to 1 PDF page
            wb.ConverterSetting.SheetFitToPage = true;

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

            //Loop through the columns in the worksheet
            for (int i = 1; i < sheet.Columns.Length; i++)
            {
                //AutoFit columns
                sheet.AutoFitColumn(i);
            }

            //Save the worksheet to PDF
            sheet.SaveToPdf("toPDF.pdf");
        }
    }
}

C#/VB.NET: Convert CSV to PDF

Apply for a Temporary License

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

Additional Info

  • tutorial_title:
Last modified on Thursday, 07 July 2022 08:05