Friday, 27 October 2023 09: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.

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);
        }
    }
}

C#/VB.NET: Convert Excel to 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");
        }
    }
}

C#/VB.NET: Convert Excel to 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.

Friday, 27 October 2023 09:29

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);
        }
    }
}

C#/VB.NET: Convert Excel to 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");
        }
    }
}

C#/VB.NET: Convert Excel to 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.

Friday, 27 October 2023 09:28

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);
        }
    }
}

C#/VB.NET: Convert Excel to 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");
        }
    }
}

C#/VB.NET: Convert Excel to PDF

임시 라이센스 신청

생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.

Friday, 27 October 2023 09:27

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);
        }
    }
}

C#/VB.NET: Convert Excel to 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");
        }
    }
}

C#/VB.NET: Convert Excel to 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.

Friday, 27 October 2023 09:24

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);
        }
    }
}

C#/VB.NET: Convert Excel to 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");
        }
    }
}

C#/VB.NET: Convert Excel to 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.

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.

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();
            }
        }
    }

C#/VB.NET: Add or Remove Digital Signatures in PDF

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();
            }
        }
    }

C#/VB.NET: Add or Remove Digital Signatures in PDF

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.

See Also

À 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.

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();
            }
        }
    }

C#/VB.NET: Add or Remove Digital Signatures in PDF

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();
            }
        }
    }

C#/VB.NET: Add or Remove Digital Signatures in PDF

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.

Veja também

Поскольку PDF-документы становятся все более популярными в бизнесе, обеспечение их подлинности становится ключевой задачей. Подписание PDF-файлов с помощью подписи на основе сертификата может защитить содержимое, а также сообщить другим, кто подписал или утвердил документ. В этой статье вы узнаете, как цифровая подпись PDF-файла с помощью невидимой или видимой подписи, и как удалить цифровые подписи из PDF с помощью Spire.PDF for .NET.

Установите Spire.PDF for .NET

Для начала вам необходимо добавить файлы DLL, включенные в пакет Spire.PDF for.NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить по этой ссылке или установить через NuGet.

PM> Install-Package Spire.PDF

Добавьте невидимую цифровую подпись в PDF

Ниже приведены шаги по добавлению невидимой цифровой подписи в PDF с помощью Spire.PDF for .NET.

  • Создайте объект PDFDocument.
  • Загрузите образец PDF-файла с помощью метода PdfDocument.LoadFromFile().
  • Загрузите файл сертификата PFX при инициализации объекта PdfCertificate.
  • Создайте объект PdfSignature на основе сертификата.
  • Установите разрешения для документа через объект PdfSignature.
  • Сохраните документ в другой PDF-файл, используя метод 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();
            }
        }
    }

C#/VB.NET: Add or Remove Digital Signatures in PDF

Добавьте видимую цифровую подпись в PDF

Ниже приведены шаги по добавлению видимой цифровой подписи в PDF с помощью Spire.PDF for .NET.

  • Создайте объект PDFDocument.
  • Загрузите образец PDF-файла с помощью метода PdfDocument.LoadFromFile().
  • Загрузите файл сертификата PFX при инициализации объекта PdfCertificate.
  • Создайте объект PdfSignature и укажите его положение и размер в документе.
  • Установите данные подписи, включая дату, имя, местоположение, причину, изображение рукописной подписи и разрешения для документа.
  • Сохраните документ в другой PDF-файл, используя метод 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();
            }
        }
    }

C#/VB.NET: Add or Remove Digital Signatures in PDF

Удалить цифровые подписи из PDF

Ниже приведены шаги по удалению цифровых подписей из PDF с помощью Spire.PDF for .NET.

  • Создайте объект PDFDocument.
  • Получить виджеты формы из документа через свойство PdfDocument.Form.
  • Просмотрите виджеты и определите, является ли конкретный виджет PdfSignatureFieldWidget.
  • Удалите виджет подписи с помощью метода PdfFieldCollection.RemoveAt().
  • Сохраните документ в другой PDF-файл, используя метод 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");
            }
        }
    }

Подать заявку на временную лицензию

Если вы хотите удалить сообщение об оценке из сгенерированных документов или избавиться от ограничений функции, пожалуйста запросите 30-дневную пробную лицензию для себя.

Смотрите также

Da PDF-Dokumente in Unternehmen immer beliebter werden, ist die Sicherstellung ihrer Authentizität zu einem zentralen Anliegen geworden. Das Signieren von PDFs mit einer zertifikatbasierten Signatur kann den Inhalt schützen und auch anderen mitteilen, wer das Dokument signiert oder genehmigt hat. In diesem Artikel erfahren Sie, wie das geht PDF mit einer unsichtbaren oder sichtbaren Signatur digital signieren, und wie Entfernen Sie digitale Signaturen aus PDF mit Spire.PDF for .NET.

Installieren Sie Spire.PDF for .NET

Zunächst müssen Sie die im Spire.PDF for.NET-Paket enthaltenen DLL-Dateien als Referenzen in Ihrem .NET-Projekt hinzufügen. Die DLLs-Dateien können entweder über diesen Link heruntergeladen oder über NuGet installiert werden.

PM> Install-Package Spire.PDF

Fügen Sie PDF eine unsichtbare digitale Signatur hinzu

Im Folgenden finden Sie die Schritte zum Hinzufügen einer unsichtbaren digitalen Signatur zu PDF mit Spire.PDF for .NET.

  • Erstellen Sie ein PdfDocument-Objekt.
  • Laden Sie eine Beispiel-PDF-Datei mit der Methode PdfDocument.LoadFromFile().
  • Laden Sie eine PFX-Zertifikatdatei, während Sie das PdfCertificate-Objekt initialisieren.
  • Erstellen Sie ein PdfSignature-Objekt basierend auf dem Zertifikat.
  • Legen Sie die Dokumentberechtigungen über das PdfSignature-Objekt fest.
  • Speichern Sie das Dokument mit der Methode PdfDocument.SaveToFile() in einer anderen PDF-Datei.
  • 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();
            }
        }
    }

C#/VB.NET: Add or Remove Digital Signatures in PDF

Fügen Sie dem PDF eine sichtbare digitale Signatur hinzu

Im Folgenden finden Sie die Schritte zum Hinzufügen einer sichtbaren digitalen Signatur zu PDF mit Spire.PDF for .NET.

  • Erstellen Sie ein PdfDocument-Objekt.
  • Laden Sie eine Beispiel-PDF-Datei mit der Methode PdfDocument.LoadFromFile().
  • Laden Sie eine PFX-Zertifikatdatei, während Sie das PdfCertificate-Objekt initialisieren.
  • Erstellen Sie ein PdfSignature-Objekt und geben Sie seine Position und Größe im Dokument an.
  • Legen Sie die Unterschriftsdetails fest, einschließlich Datum, Name, Ort, Grund, Bild der handschriftlichen Unterschrift und Dokumentberechtigungen.
  • Speichern Sie das Dokument mit der Methode PdfDocument.SaveToFile() in einer anderen PDF-Datei.
  • 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();
            }
        }
    }

C#/VB.NET: Add or Remove Digital Signatures in PDF

Entfernen Sie digitale Signaturen aus PDF

Im Folgenden finden Sie die Schritte zum Entfernen digitaler Signaturen aus PDF mit Spire.PDF for .NET.

  • Erstellen Sie ein PdfDocument-Objekt.
  • Rufen Sie Formular-Widgets aus dem Dokument über die Eigenschaft PdfDocument.Form ab.
  • Durchlaufen Sie die Widgets und ermitteln Sie, ob es sich bei einem bestimmten Widget um ein PdfSignatureFieldWidget handelt.
  • Entfernen Sie das Signatur-Widget mit der Methode PdfFieldCollection.RemoveAt().
  • Speichern Sie das Dokument mit der Methode PdfDocument.SaveToFile() in einer anderen PDF-Datei.
  • 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");
            }
        }
    }

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.

Siehe auch

Instalado a través de NuGet

PM> Install-Package Spire.PDF

enlaces relacionados

A medida que los documentos PDF se vuelven cada vez más populares en los negocios, garantizar su autenticidad se ha convertido en una preocupación clave. Firmar archivos PDF con una firma basada en certificado puede proteger el contenido y también permitir que otros sepan quién firmó o aprobó el documento. En este artículo, aprenderá cómo firmar digitalmente PDF con una firma invisible o visible y cómo eliminar firmas digitales de PDF usando Spire.PDF for .NET.

Instalar Spire.PDF for .NET

Para empezar, debe agregar los archivos DLL incluidos en el paquete Spire.PDF 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.PDF

Agregar una firma digital invisible a PDF

Los siguientes son los pasos para agregar una firma digital invisible a un PDF usando Spire.PDF for .NET.

  • Cree un objeto PdfDocument.
  • Cargue un archivo PDF de muestra utilizando el método PdfDocument.LoadFromFile().
  • Cargue un archivo de certificado pfx mientras inicializa el objeto PdfCertificate.
  • Cree un objeto PdfSignature basado en el certificado.
  • Establezca los permisos del documento a través del objeto PdfSignature.
  • Guarde el documento en otro archivo PDF utilizando el 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();
            }
        }
    }

C#/VB.NET: Add or Remove Digital Signatures in PDF

Agregar una firma digital visible a PDF

Los siguientes son los pasos para agregar una firma digital visible a un PDF usando Spire.PDF for .NET.

  • Cree un objeto PdfDocument.
  • Cargue un archivo PDF de muestra utilizando el método PdfDocument.LoadFromFile().
  • Cargue un archivo de certificado pfx mientras inicializa el objeto PdfCertificate.
  • Cree un objeto PdfSignature y especifique su posición y tamaño en el documento.
  • Configure los detalles de la firma, incluida la fecha, el nombre, la ubicación, el motivo, la imagen de la firma manuscrita y los permisos del documento.
  • Guarde el documento en otro archivo PDF utilizando el 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();
            }
        }
    }

C#/VB.NET: Add or Remove Digital Signatures in PDF

Eliminar firmas digitales de PDF

Los siguientes son los pasos para eliminar firmas digitales de PDF usando Spire.PDF for .NET.

  • Cree un objeto PdfDocument.
  • Obtenga widgets de formulario del documento a través de la propiedad PdfDocument.Form.
  • Recorra los widgets y determine si un widget específico es un PdfSignatureFieldWidget.
  • Elimine el widget de firma utilizando el método PdfFieldCollection.RemoveAt().
  • Guarde el documento en otro archivo PDF utilizando el 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 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.

Ver también