C# Convert Excel to PDF
Table of Contents
Installed via NuGet
PM> Install-Package Spire.XLS
Related Links
By converting an Excel file to PDF format, anyone can open the file even when there is no Office installed in the system. Also, converting Excel documents to PDF is useful as PDF files can be easily shared and printed. In this article, you will learn how to convert a whole Excel document or a specific worksheet into PDF 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
Convert a Whole Excel Document to PDF
The following are the steps to convert a whole Excel document to PDF using Spire.XLS for .NET.
- Create a Workbook object.
- Load a sample Excel document using Workbook.LoadFromFile() method.
- Set the Excel to PDF conversion options through the properties under the ConverterSetting class.
- Convert the whole Excel document to PDF using Workbook.SaveToFile() method.
- C#
- VB.NET
using Spire.Xls;
namespace ConvertExcelToPDF
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");
//Set worksheets to fit to page when converting
workbook.ConverterSetting.SheetFitToPage = true;
//Save to PDF
workbook.SaveToFile("ExcelToPdf.pdf", FileFormat.PDF);
}
}
}

Convert a Specific Worksheet to PDF
The following are the steps to convert a specific worksheet to PDF using Spire.XLS for .NET.
- Create a Workbook object.
- Load a sample Excel document using Workbook.LoadFromFile() method.
- Set the Excel to PDF conversion options through the properties under the ConverterSetting class.
- Get a specific worksheet through the Workbook.Worksheets[index] property.
- Convert the worksheet to PDF using Worksheet.SaveToPdf() method.
- C#
- VB.NET
using Spire.Xls;
namespace ConvertWorksheetToPdf
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");
//Set worksheets to fit to page when converting
workbook.ConverterSetting.SheetFitToPage = true;
//Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
//Save to PDF
worksheet.SaveToPdf("WorksheetToPdf.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.
C# Converter Excel em PDF
Ao converter um arquivo Excel para o formato PDF, qualquer pessoa pode abrir o arquivo mesmo quando não há nenhum Office instalado no sistema. Além disso, converter documentos Excel em PDF é útil porque os arquivos PDF podem ser facilmente compartilhados e impressos. Neste artigo você aprenderá como converter um documento Excel inteiro ou uma planilha específica em PDF usando Spire.XLS for .NET.
Instale o Spire.XLS for .NET
Para começar, você precisa adicionar os arquivos DLL incluídos no pacote Spire.XLS for .NET como referências em seu projeto .NET. Os arquivos DLL podem ser baixados de esse link ou instalado via NuGet.
PM> Install-Package Spire.XLS
Converta um documento Excel inteiro em PDF
A seguir estão as etapas para converter um documento Excel inteiro em PDF usando Spire.XLS for .NET.
- Crie um objeto Pasta de Trabalho.
- Carregue um documento Excel de amostra usando o método Workbook.LoadFromFile().
- Defina as opções de conversão de Excel para PDF por meio das propriedades da classe ConverterSetting.
- Converta todo o documento Excel em PDF usando o método Workbook.SaveToFile().
- C#
- VB.NET
using Spire.Xls;
namespace ConvertExcelToPDF
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");
//Set worksheets to fit to page when converting
workbook.ConverterSetting.SheetFitToPage = true;
//Save to PDF
workbook.SaveToFile("ExcelToPdf.pdf", FileFormat.PDF);
}
}
}

Converter uma planilha específica em PDF
A seguir estão as etapas para converter uma planilha específica em PDF usando Spire.XLS for .NET.
- Crie um objeto Pasta de Trabalho.
- Carregue um documento Excel de amostra usando o método Workbook.LoadFromFile().
- Defina as opções de conversão de Excel para PDF por meio das propriedades da classe ConverterSetting.
- Obtenha uma planilha específica através da propriedade Workbook.Worksheets[index].
- Converta a planilha em PDF usando o método Worksheet.SaveToPdf().
- C#
- VB.NET
using Spire.Xls;
namespace ConvertWorksheetToPdf
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");
//Set worksheets to fit to page when converting
workbook.ConverterSetting.SheetFitToPage = true;
//Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
//Save to PDF
worksheet.SaveToPdf("WorksheetToPdf.pdf");
}
}
}

Solicite uma licença temporária
Se desejar remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.
C# конвертировать Excel в PDF
Преобразовав файл Excel в формат PDF, любой сможет открыть файл, даже если в системе не установлен Office. Кроме того, преобразование документов Excel в PDF полезно, поскольку файлы PDF можно легко публиковать и распечатывать. В этой статье вы узнаете, как конвертировать весь документ Excel или конкретный рабочий лист в PDF с помощью Spire.XLS for .NET.
Установите Spire.XLS for .NET
Для начала вам необходимо добавить файлы DLL, включенные в пакет Spire.XLS for .NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить по этой ссылке или установить через NuGet.
PM> Install-Package Spire.XLS
Преобразование всего документа Excel в PDF
Ниже приведены шаги по преобразованию всего документа Excel в PDF с помощью Spire.XLS for .NET.
- Создайте объект Workbook.
- Загрузите образец документа Excel с помощью метода Workbook.LoadFromFile().
- Задайте параметры преобразования Excel в PDF с помощью свойств класса ConverterSetting.
- Преобразуйте весь документ Excel в PDF с помощью метода Workbook.SaveToFile().
- C#
- VB.NET
using Spire.Xls;
namespace ConvertExcelToPDF
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");
//Set worksheets to fit to page when converting
workbook.ConverterSetting.SheetFitToPage = true;
//Save to PDF
workbook.SaveToFile("ExcelToPdf.pdf", FileFormat.PDF);
}
}
}

Преобразование определенного листа в PDF
Ниже приведены шаги по преобразованию определенного листа в PDF с помощью Spire.XLS for .NET.
- Создайте объект Workbook.
- Загрузите образец документа Excel с помощью метода Workbook.LoadFromFile().
- Задайте параметры преобразования Excel в PDF с помощью свойств класса ConverterSetting.
- Получите конкретный лист с помощью свойства Workbook.Worksheets[index].
- Преобразуйте рабочий лист в PDF с помощью метода Worksheet.SaveToPdf().
- C#
- VB.NET
using Spire.Xls;
namespace ConvertWorksheetToPdf
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");
//Set worksheets to fit to page when converting
workbook.ConverterSetting.SheetFitToPage = true;
//Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
//Save to PDF
worksheet.SaveToPdf("WorksheetToPdf.pdf");
}
}
}

Подать заявку на временную лицензию
Если вы хотите удалить сообщение об оценке из сгенерированных документов или избавиться от ограничений функции, пожалуйста запросите 30-дневную пробную лицензию для себя.
C# Excel in PDF konvertieren
Durch die Konvertierung einer Excel-Datei in das PDF-Format kann jeder die Datei öffnen, auch wenn kein Office auf dem System installiert ist. Auch das Konvertieren von Excel-Dokumenten in PDF ist nützlich, da PDF-Dateien problemlos geteilt und gedruckt werden können. In diesem Artikel erfahren Sie, wie das geht Konvertieren Sie ein ganzes Excel-Dokument oder ein bestimmtes Arbeitsblatt in PDF mithilfe von Spire.XLS for .NET.
- Konvertieren Sie ein ganzes Excel-Dokument in PDF
- Konvertieren Sie ein bestimmtes Arbeitsblatt in PDF
Installieren Sie Spire.XLS for .NET
Zunächst müssen Sie die im Spire.XLS for .NET-Paket enthaltenen DLL-Dateien als Referenzen in Ihrem .NET-Projekt hinzufügen. Die DLL-Dateien können entweder über diesen Link heruntergeladen oder über NuGet installiert werden.
PM> Install-Package Spire.XLS
Konvertieren Sie ein ganzes Excel-Dokument in PDF
Im Folgenden finden Sie die Schritte zum Konvertieren eines gesamten Excel-Dokuments in PDF mit Spire.XLS for .NET.
- Erstellen Sie ein Workbook-Objekt.
- Laden Sie ein Beispiel-Excel-Dokument mit der Methode Workbook.LoadFromFile().
- Legen Sie die Optionen für die Konvertierung von Excel in PDF über die Eigenschaften unter der Klasse „ConverterSetting“ fest.
- Konvertieren Sie das gesamte Excel-Dokument mit der Methode Workbook.SaveToFile() in PDF.
- C#
- VB.NET
using Spire.Xls;
namespace ConvertExcelToPDF
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");
//Set worksheets to fit to page when converting
workbook.ConverterSetting.SheetFitToPage = true;
//Save to PDF
workbook.SaveToFile("ExcelToPdf.pdf", FileFormat.PDF);
}
}
}

Konvertieren Sie ein bestimmtes Arbeitsblatt in PDF
Im Folgenden finden Sie die Schritte zum Konvertieren eines bestimmten Arbeitsblatts in PDF mit Spire.XLS for .NET.
- Erstellen Sie ein Workbook-Objekt.
- Laden Sie ein Beispiel-Excel-Dokument mit der Methode Workbook.LoadFromFile().
- Legen Sie die Optionen für die Konvertierung von Excel in PDF über die Eigenschaften unter der Klasse „ConverterSetting“ fest.
- Rufen Sie ein bestimmtes Arbeitsblatt über die Eigenschaft Workbook.Worksheets[index] ab.
- Konvertieren Sie das Arbeitsblatt mit der Methode Worksheet.SaveToPdf() in PDF.
- C#
- VB.NET
using Spire.Xls;
namespace ConvertWorksheetToPdf
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");
//Set worksheets to fit to page when converting
workbook.ConverterSetting.SheetFitToPage = true;
//Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
//Save to PDF
worksheet.SaveToPdf("WorksheetToPdf.pdf");
}
}
}

Beantragen Sie eine temporäre Lizenz
Wenn Sie die Bewertungsmeldung aus den generierten Dokumenten entfernen oder die Funktionseinschränkungen beseitigen möchten, wenden Sie sich bitte an uns Fordern Sie eine 30-Tage-Testlizenz an für sich selbst.
C# Convertir Excel a PDF
Al convertir un archivo de Excel a formato PDF, cualquiera puede abrir el archivo incluso cuando no hay Office instalado en el sistema. Además, convertir documentos de Excel a PDF es útil ya que los archivos PDF se pueden compartir e imprimir fácilmente. En este artículo, aprenderá cómo convertir un documento completo de Excel o una hoja de trabajo específica en PDF utilizando Spire.XLS for .NET.
Instalar Spire.XLS for .NET
Para empezar, debe agregar los archivos DLL incluidos en el paquete Spire.XLS for .NET como referencias en su proyecto .NET. Los archivos DLL se pueden descargar desde este enlace o instalado a través de NuGet.
PM> Install-Package Spire.XLS
Convertir un documento completo de Excel a PDF
Los siguientes son los pasos para convertir un documento completo de Excel a PDF usando Spire.XLS for .NET.
- Cree un objeto de libro de trabajo.
- Cargue un documento de Excel de muestra utilizando el método Workbook.LoadFromFile().
- Configure las opciones de conversión de Excel a PDF a través de las propiedades de la clase ConverterSetting.
- Convierta todo el documento de Excel a PDF utilizando el método Workbook.SaveToFile().
- C#
- VB.NET
using Spire.Xls;
namespace ConvertExcelToPDF
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");
//Set worksheets to fit to page when converting
workbook.ConverterSetting.SheetFitToPage = true;
//Save to PDF
workbook.SaveToFile("ExcelToPdf.pdf", FileFormat.PDF);
}
}
}

Convertir una hoja de trabajo específica a PDF
Los siguientes son los pasos para convertir una hoja de trabajo específica a PDF usando Spire.XLS for .NET.
- Cree un objeto de libro de trabajo.
- Cargue un documento de Excel de muestra utilizando el método Workbook.LoadFromFile().
- Configure las opciones de conversión de Excel a PDF a través de las propiedades de la clase ConverterSetting.
- Obtenga una hoja de trabajo específica a través de la propiedad Workbook.Worksheets[index].
- Convierta la hoja de trabajo a PDF usando el método Worksheet.SaveToPdf().
- C#
- VB.NET
using Spire.Xls;
namespace ConvertWorksheetToPdf
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");
//Set worksheets to fit to page when converting
workbook.ConverterSetting.SheetFitToPage = true;
//Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
//Save to PDF
worksheet.SaveToPdf("WorksheetToPdf.pdf");
}
}
}

Solicite una licencia temporal
Si desea eliminar el mensaje de evaluación de los documentos generados o deshacerse de las limitaciones de la función, por favor solicitar una licencia de prueba de 30 días para ti.
C# Excel을 PDF로 변환
Excel 파일을 PDF 형식으로 변환하면 시스템에 Office가 설치되어 있지 않아도 누구나 파일을 열 수 있습니다. 또한 PDF 파일을 쉽게 공유하고 인쇄할 수 있으므로 Excel 문서를 PDF로 변환하는 것이 유용합니다. 이 기사에서는 다음 방법을 배웁니다 전체 Excel 문서 변환 또는 특정 워크시트 Spire.XLS for .NET사용하여 PDF로 변환합니다.
Spire.XLS for .NET 설치
먼저 .NET 프로젝트의 참조로 Spire.XLS for .NET 패키지에 포함된 DLL 파일을 추가해야 합니다. DLL 파일은 이 링크 에서 다운로드하거나 NuGet을 통해 설치할 수 있습니다.
PM> Install-Package Spire.XLS
전체 Excel 문서를 PDF로 변환
다음은 Spire.XLS for .NET 사용하여 전체 Excel 문서를 PDF로 변환하는 단계입니다.
- 통합 문서 개체를 만듭니다.
- Workbook.LoadFromFile() 메서드를 사용하여 샘플 Excel 문서를 로드합니다.
- ConverterSetting 클래스 아래의 속성을 통해 Excel에서 PDF로의 변환 옵션을 설정합니다.
- Workbook.SaveToFile() 메서드를 사용하여 전체 Excel 문서를 PDF로 변환합니다.
- C#
- VB.NET
using Spire.Xls;
namespace ConvertExcelToPDF
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");
//Set worksheets to fit to page when converting
workbook.ConverterSetting.SheetFitToPage = true;
//Save to PDF
workbook.SaveToFile("ExcelToPdf.pdf", FileFormat.PDF);
}
}
}

특정 워크시트를 PDF로 변환
다음은 Spire.XLS for .NET 사용하여 특정 워크시트를 PDF로 변환하는 단계입니다.
- 통합 문서 개체를 만듭니다.
- Workbook.LoadFromFile() 메서드를 사용하여 샘플 Excel 문서를 로드합니다.
- ConverterSetting 클래스 아래의 속성을 통해 Excel에서 PDF로의 변환 옵션을 설정합니다.
- Workbook.Worksheets[index] 속성을 통해 특정 워크시트를 가져옵니다.
- Worksheet.SaveToPdf() 메서드를 사용하여 워크시트를 PDF로 변환합니다.
- C#
- VB.NET
using Spire.Xls;
namespace ConvertWorksheetToPdf
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");
//Set worksheets to fit to page when converting
workbook.ConverterSetting.SheetFitToPage = true;
//Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
//Save to PDF
worksheet.SaveToPdf("WorksheetToPdf.pdf");
}
}
}

임시 라이센스 신청
생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.
C# converti Excel in PDF
Convertendo un file Excel in formato PDF, chiunque può aprire il file anche quando nel sistema non è installato Office. Inoltre, la conversione di documenti Excel in PDF è utile poiché i file PDF possono essere facilmente condivisi e stampati. In questo articolo imparerai come farlo convertire un intero documento Excel o un foglio di lavoro specifico in PDF utilizzando Spire.XLS for .NET.
Installa Spire.XLS for .NET
Per cominciare, devi aggiungere i file DLL inclusi nel pacchetto Spire.XLS for .NET come riferimenti nel tuo progetto .NET. I file DLL possono essere scaricati da questo link o installato tramite NuGet.
PM> Install-Package Spire.XLS
Converti un intero documento Excel in PDF
Di seguito sono riportati i passaggi per convertire un intero documento Excel in PDF utilizzando Spire.XLS for .NET.
- Creare un oggetto cartella di lavoro.
- Carica un documento Excel di esempio utilizzando il metodo Workbook.LoadFromFile().
- Imposta le opzioni di conversione da Excel a PDF tramite le proprietà nella classe ConverterSetting.
- Converti l'intero documento Excel in PDF utilizzando il metodo Workbook.SaveToFile().
- C#
- VB.NET
using Spire.Xls;
namespace ConvertExcelToPDF
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");
//Set worksheets to fit to page when converting
workbook.ConverterSetting.SheetFitToPage = true;
//Save to PDF
workbook.SaveToFile("ExcelToPdf.pdf", FileFormat.PDF);
}
}
}

Converti un foglio di lavoro specifico in PDF
Di seguito sono riportati i passaggi per convertire un foglio di lavoro specifico in PDF utilizzando Spire.XLS for .NET.
- Creare un oggetto cartella di lavoro.
- Carica un documento Excel di esempio utilizzando il metodo Workbook.LoadFromFile().
- Imposta le opzioni di conversione da Excel a PDF tramite le proprietà nella classe ConverterSetting.
- Ottieni un foglio di lavoro specifico tramite la proprietà Workbook.Worksheets[index].
- Converti il foglio di lavoro in PDF utilizzando il metodo Worksheet.SaveToPdf().
- C#
- VB.NET
using Spire.Xls;
namespace ConvertWorksheetToPdf
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");
//Set worksheets to fit to page when converting
workbook.ConverterSetting.SheetFitToPage = true;
//Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
//Save to PDF
worksheet.SaveToPdf("WorksheetToPdf.pdf");
}
}
}

Richiedi una licenza temporanea
Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni della funzione, per favore richiedere una licenza di prova di 30 giorni per te.
C# convertir Excel en PDF
En convertissant un fichier Excel au format PDF, n'importe qui peut ouvrir le fichier même si aucun Office n'est installé sur le système. De plus, la conversion de documents Excel en PDF est utile car les fichiers PDF peuvent être facilement partagés et imprimés. Dans cet article, vous apprendrez comment convertir un document Excel entier ou une feuille de travail spécifique en PDF en utilisant Spire.XLS for .NET.
Installez Spire.XLS for .NET
Pour commencer, vous devez ajouter les fichiers DLL inclus dans le package Spire.XLS for .NET comme références dans votre projet .NET. Les fichiers DLL peuvent être téléchargés à partir de ce lien ou installés via NuGet.
PM> Install-Package Spire.XLS
Convertir un document Excel entier en PDF
Voici les étapes pour convertir un document Excel entier en PDF à l'aide de Spire.XLS for .NET.
- Créez un objet Workbook.
- Chargez un exemple de document Excel à l’aide de la méthode Workbook.LoadFromFile().
- Définissez les options de conversion Excel en PDF via les propriétés de la classe ConverterSetting.
- Convertissez l'intégralité du document Excel en PDF à l'aide de la méthode Workbook.SaveToFile().
- C#
- VB.NET
using Spire.Xls;
namespace ConvertExcelToPDF
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");
//Set worksheets to fit to page when converting
workbook.ConverterSetting.SheetFitToPage = true;
//Save to PDF
workbook.SaveToFile("ExcelToPdf.pdf", FileFormat.PDF);
}
}
}

Convertir une feuille de calcul spécifique en PDF
Voici les étapes pour convertir une feuille de calcul spécifique en PDF à l'aide de Spire.XLS for .NET.
- Créez un objet Workbook.
- Chargez un exemple de document Excel à l’aide de la méthode Workbook.LoadFromFile().
- Définissez les options de conversion Excel en PDF via les propriétés de la classe ConverterSetting.
- Obtenez une feuille de calcul spécifique via la propriété Workbook.Worksheets[index].
- Convertissez la feuille de calcul en PDF à l'aide de la méthode Worksheet.SaveToPdf().
- C#
- VB.NET
using Spire.Xls;
namespace ConvertWorksheetToPdf
{
class Program
{
static void Main(string[] args)
{
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load a sample Excel file
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");
//Set worksheets to fit to page when converting
workbook.ConverterSetting.SheetFitToPage = true;
//Get the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
//Save to PDF
worksheet.SaveToPdf("WorksheetToPdf.pdf");
}
}
}

Demander une licence temporaire
Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations fonctionnelles, veuillez demander une licence d'essai de 30 jours pour toi.
C#/VB.NET: Add or Remove Digital Signatures in PDF
Table of Contents
Installed via NuGet
PM> Install-Package Spire.PDF
Related Links
As PDF documents become increasingly popular in business, ensuring their authenticity has become a key concern. Signing PDFs with a certificate-based signature can protect the content and also let others know who signed or approved the document. In this article, you will learn how to digitally sign PDF with an invisible or a visible signature, and how to remove digital signatures from PDF by using Spire.PDF for .NET.
- Add an Invisible Digital Signature to PDF
- Add a Visible Digital Signature to PDF
- Remove Digital Signatures from PDF
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 DLLs files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.PDF
Add an Invisible Digital Signature to PDF
The following are the steps to add an invisible digital signature to PDF using Spire.PDF for .NET.
- Create a PdfDocument object.
- Load a sample PDF file using PdfDocument.LoadFromFile() method.
- Load a pfx certificate file while initializing the PdfCertificate object.
- Create a PdfSignature object based on the certificate.
- Set the document permissions through the PdfSignature object.
- Save the document to another PDF file using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Security;
namespace AddInvisibleSignature
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Load a sample PDF file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");
//Load the certificate
PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\MyCertificate.pfx", "e-iceblue");
//Create a PdfSignature object
PdfSignature signature = new PdfSignature(doc, doc.Pages[doc.Pages.Count - 1], cert, "MySignature");
//Set the document permission to forbid changes but allow form fill
signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges | PdfCertificationFlags.AllowFormFill;
//Save to another PDF file
doc.SaveToFile("InvisibleSignature.pdf");
doc.Close();
}
}
}

Add a Visible Digital Signature to PDF
The following are the steps to add a visible digital signature to PDF using Spire.PDF for .NET.
- Create a PdfDocument object.
- Load a sample PDF file using PdfDocument.LoadFromFile() method.
- Load a pfx certificate file while initializing the PdfCertificate object.
- Create a PdfSignature object and specify its position and size on the document.
- Set the signature details including date, name, location, reason, handwritten signature image, and document permissions.
- Save the document to another PDF file using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using System;
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Security;
using Spire.Pdf.Graphics;
namespace AddVisibleSignature
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Load a sample PDF file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");
//Load the certificate
PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\MyCertificate.pfx", "e-iceblue");
//Create a PdfSignature object and specify its position and size
PdfSignature signature = new PdfSignature(doc, doc.Pages[doc.Pages.Count - 1], cert, "MySignature");
RectangleF rectangleF = new RectangleF(doc.Pages[0].ActualSize.Width - 260 - 54 , 200, 260, 110);
signature.Bounds = rectangleF;
signature.Certificated = true;
//Set the graphics mode to ImageAndSignDetail
signature.GraphicsMode = GraphicMode.SignImageAndSignDetail;
//Set the signature content
signature.NameLabel = "Signer:";
signature.Name = "Gary";
signature.ContactInfoLabel = "Phone:";
signature.ContactInfo = "0123456";
signature.DateLabel = "Date:";
signature.Date = DateTime.Now;
signature.LocationInfoLabel = "Location:";
signature.LocationInfo = "USA";
signature.ReasonLabel = "Reason:";
signature.Reason = "I am the author";
signature.DistinguishedNameLabel = "DN:";
signature.DistinguishedName = signature.Certificate.IssuerName.Name;
//Set the signature image source
signature.SignImageSource = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\handwrittingSignature.png");
//Set the signature font
signature.SignDetailsFont = new PdfTrueTypeFont(new Font("Arial Unicode MS", 12f, FontStyle.Regular));
//Set the document permission to forbid changes but allow form fill
signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges | PdfCertificationFlags.AllowFormFill;
//Save to file
doc.SaveToFile("VisiableSignature.pdf");
doc.Close();
}
}
}

Remove Digital Signatures from PDF
The following are the steps to remove digital signatures from PDF using Spire.PDF for .NET.
- Create a PdfDocument object.
- Get form widgets from the document through PdfDocument.Form property.
- Loop through the widgets and determine if a specific widget is a PdfSignatureFieldWidget.
- Remove the signature widget using PdfFieldCollection.RemoveAt() method.
- Save the document to another PDF file using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Widget;
namespace RemoveSignature
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument doc = new PdfDocument("C:\\Users\\Administrator\\Desktop\\VisiableSignature.pdf");
//Get form widgets from the document
PdfFormWidget widgets = doc.Form as PdfFormWidget;
//Loop through the widgets
for (int i = 0; i < widgets.FieldsWidget.List.Count; i++)
{
//Get the specific widget
PdfFieldWidget widget = widgets.FieldsWidget.List[i] as PdfFieldWidget;
//Determine if the widget is a PdfSignatureFieldWidget
if (widget is PdfSignatureFieldWidget)
{
//Remove the widget
widgets.FieldsWidget.RemoveAt(i);
}
}
//Save the document to another PDF file
doc.SaveToFile("RemoveSignatures.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.
C#/VB.NET: Adicionar ou remover assinaturas digitais em PDF
Índice
Instalado via NuGet
PM> Install-Package Spire.PDF
Links Relacionados
À medida que os documentos PDF se tornam cada vez mais populares nos negócios, garantir a sua autenticidade tornou-se uma preocupação fundamental. Assinar PDFs com uma assinatura baseada em certificado pode proteger o conteúdo e também permitir que outras pessoas saibam quem assinou ou aprovou o documento. Neste artigo você aprenderá como assinar digitalmente PDF com uma assinatura invisível ou visível e como remover assinaturas digitais de PDF usando Spire.PDF for .NET.
- Adicione uma assinatura digital invisível ao PDF
- Adicione uma assinatura digital visível ao PDF
- Remover assinaturas digitais de PDF
Instale o Spire.PDF for .NET
Para começar, você precisa adicionar os arquivos DLL incluídos no pacote Spire.PDF for.NET como referências em seu projeto .NET. Os arquivos DLLs podem ser baixados deste link ou instalados via NuGet.
PM> Install-Package Spire.PDF
Adicione uma assinatura digital invisível ao PDF
A seguir estão as etapas para adicionar uma assinatura digital invisível ao PDF usando Spire.PDF for .NET.
- Crie um objeto PdfDocument.
- Carregue um arquivo PDF de amostra usando o método PdfDocument.LoadFromFile().
- Carregue um arquivo de certificado pfx ao inicializar o objeto PdfCertificate.
- Crie um objeto PdfSignature com base no certificado.
- Defina as permissões do documento através do objeto PdfSignature.
- Salve o documento em outro arquivo PDF usando o método PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Security;
namespace AddInvisibleSignature
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Load a sample PDF file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");
//Load the certificate
PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\MyCertificate.pfx", "e-iceblue");
//Create a PdfSignature object
PdfSignature signature = new PdfSignature(doc, doc.Pages[doc.Pages.Count - 1], cert, "MySignature");
//Set the document permission to forbid changes but allow form fill
signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges | PdfCertificationFlags.AllowFormFill;
//Save to another PDF file
doc.SaveToFile("InvisibleSignature.pdf");
doc.Close();
}
}
}

Adicione uma assinatura digital visível ao PDF
A seguir estão as etapas para adicionar uma assinatura digital visível ao PDF usando Spire.PDF for .NET.
- Crie um objeto PdfDocument.
- Carregue um arquivo PDF de amostra usando o método PdfDocument.LoadFromFile().
- Carregue um arquivo de certificado pfx ao inicializar o objeto PdfCertificate.
- Crie um objeto PdfSignature e especifique sua posição e tamanho no documento.
- Defina os detalhes da assinatura, incluindo data, nome, local, motivo, imagem da assinatura manuscrita e permissões do documento.
- Salve o documento em outro arquivo PDF usando o método PdfDocument.SaveToFile().
- C#
- VB.NET
using System;
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Security;
using Spire.Pdf.Graphics;
namespace AddVisibleSignature
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Load a sample PDF file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");
//Load the certificate
PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\MyCertificate.pfx", "e-iceblue");
//Create a PdfSignature object and specify its position and size
PdfSignature signature = new PdfSignature(doc, doc.Pages[doc.Pages.Count - 1], cert, "MySignature");
RectangleF rectangleF = new RectangleF(doc.Pages[0].ActualSize.Width - 260 - 54 , 200, 260, 110);
signature.Bounds = rectangleF;
signature.Certificated = true;
//Set the graphics mode to ImageAndSignDetail
signature.GraphicsMode = GraphicMode.SignImageAndSignDetail;
//Set the signature content
signature.NameLabel = "Signer:";
signature.Name = "Gary";
signature.ContactInfoLabel = "Phone:";
signature.ContactInfo = "0123456";
signature.DateLabel = "Date:";
signature.Date = DateTime.Now;
signature.LocationInfoLabel = "Location:";
signature.LocationInfo = "USA";
signature.ReasonLabel = "Reason:";
signature.Reason = "I am the author";
signature.DistinguishedNameLabel = "DN:";
signature.DistinguishedName = signature.Certificate.IssuerName.Name;
//Set the signature image source
signature.SignImageSource = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\handwrittingSignature.png");
//Set the signature font
signature.SignDetailsFont = new PdfTrueTypeFont(new Font("Arial Unicode MS", 12f, FontStyle.Regular));
//Set the document permission to forbid changes but allow form fill
signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges | PdfCertificationFlags.AllowFormFill;
//Save to file
doc.SaveToFile("VisiableSignature.pdf");
doc.Close();
}
}
}

Remover assinaturas digitais de PDF
A seguir estão as etapas para remover assinaturas digitais de PDF usando Spire.PDF for .NET.
- Crie um objeto PdfDocument.
- Obtenha widgets de formulário do documento por meio da propriedade PdfDocument.Form.
- Percorra os widgets e determine se um widget específico é um PdfSignatureFieldWidget.
- Remova o widget de assinatura usando o método PdfFieldCollection.RemoveAt().
- Salve o documento em outro arquivo PDF usando o método PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Widget;
namespace RemoveSignature
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument doc = new PdfDocument("C:\\Users\\Administrator\\Desktop\\VisiableSignature.pdf");
//Get form widgets from the document
PdfFormWidget widgets = doc.Form as PdfFormWidget;
//Loop through the widgets
for (int i = 0; i < widgets.FieldsWidget.List.Count; i++)
{
//Get the specific widget
PdfFieldWidget widget = widgets.FieldsWidget.List[i] as PdfFieldWidget;
//Determine if the widget is a PdfSignatureFieldWidget
if (widget is PdfSignatureFieldWidget)
{
//Remove the widget
widgets.FieldsWidget.RemoveAt(i);
}
}
//Save the document to another PDF file
doc.SaveToFile("RemoveSignatures.pdf");
}
}
}
Solicite uma licença temporária
Se desejar remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, por favor solicite uma licença de teste de 30 dias para você mesmo.