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.
C#/VB.NET: добавление или удаление цифровых подписей в PDF
Оглавление
Установлено через NuGet
PM> Install-Package Spire.PDF
Ссылки по теме
Поскольку PDF-документы становятся все более популярными в бизнесе, обеспечение их подлинности становится ключевой задачей. Подписание PDF-файлов с помощью подписи на основе сертификата может защитить содержимое, а также сообщить другим, кто подписал или утвердил документ. В этой статье вы узнаете, как цифровая подпись PDF-файла с помощью невидимой или видимой подписи, и как удалить цифровые подписи из PDF с помощью Spire.PDF for .NET.
- Добавьте невидимую цифровую подпись в PDF
- Добавьте видимую цифровую подпись в PDF
- Удалить цифровые подписи из PDF
Установите 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();
}
}
}

Добавьте видимую цифровую подпись в 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();
}
}
}

Удалить цифровые подписи из 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-дневную пробную лицензию для себя.
C#/VB.NET: Digitale Signaturen in PDF hinzufügen oder entfernen
Inhaltsverzeichnis
Über NuGet installiert
PM> Install-Package Spire.PDF
verwandte Links
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.
- Fügen Sie PDF eine unsichtbare digitale Signatur hinzu
- Fügen Sie dem PDF eine sichtbare digitale Signatur hinzu
- Entfernen Sie digitale Signaturen aus PDF
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();
}
}
}

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

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.
C#/VB.NET: agregar o eliminar firmas digitales en PDF
Tabla de contenido
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.
- Agregar una firma digital invisible a PDF
- Agregar una firma digital visible a PDF
- Eliminar firmas digitales de PDF
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();
}
}
}

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

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.
C#/VB.NET: PDF에서 디지털 서명 추가 또는 제거
NuGet을 통해 설치됨
PM> Install-Package Spire.PDF
관련된 링크들
PDF 문서가 비즈니스에서 점점 더 인기를 끌면서 문서의 신뢰성을 보장하는 것이 주요 관심사가 되었습니다. 인증서 기반 서명으로 PDF에 서명하면 콘텐츠를 보호할 수 있으며 문서에 서명하거나 승인한 사람을 다른 사람에게 알릴 수도 있습니다. 이 기사에서는 다음 방법을 배웁니다 보이지 않거나 보이는 서명을 사용하여 PDF에 디지털 서명을 하고, 그리고 어떻게 PDF에서 디지털 서명 제거 Spire.PDF for .NET 사용합니다.
Spire.PDF for .NET 설치
저 Spire.PDF for.NET 패키지에 포함된 DLL 파일을 .NET 프로젝트의 참조로 추가해야 합니다. DLL 파일은 이 링크 에서 다운로드하거나 NuGet을 통해 설치할 수 있습니다.
PM> Install-Package Spire.PDF
PDF에 보이지 않는 디지털 서명 추가
다음은 Spire.PDF for .NET 사용하여 PDF에 보이지 않는 디지털 서명을 추가하는 단계입니다.
- PdfDocument 개체를 만듭니다.
- PdfDocument.LoadFromFile() 메서드를 사용하여 샘플 PDF 파일을 로드합니다.
- PdfCertificate 객체를 초기화하는 동안 pfx 인증서 파일을 로드합니다.
- 인증서를 기반으로 PdfSignature 개체를 만듭니다.
- PdfSignature 개체를 통해 문서 권한을 설정합니다.
- PdfDocument.SaveToFile() 메서드를 사용하여 문서를 다른 PDF 파일에 저장합니다.
- 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();
}
}
}

PDF에 보이는 디지털 서명 추가
다음은 Spire.PDF for .NET 사용하여 PDF에 눈에 보이는 디지털 서명을 추가하는 단계입니다.
- PdfDocument 개체를 만듭니다.
- PdfDocument.LoadFromFile() 메서드를 사용하여 샘플 PDF 파일을 로드합니다.
- PdfCertificate 객체를 초기화하는 동안 pfx 인증서 파일을 로드합니다.
- PdfSignature 개체를 만들고 문서에서 위치와 크기를 지정합니다.
- 날짜, 이름, 위치, 사유, 자필 서명 이미지, 문서 권한 등 서명 세부 사항을 설정합니다.
- PdfDocument.SaveToFile() 메서드를 사용하여 문서를 다른 PDF 파일에 저장합니다.
- 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();
}
}
}

PDF에서 디지털 서명 제거
다음은 Spire.PDF for .NET 사용하여 PDF에서 디지털 서명을 제거하는 단계입니다.
- PdfDocument 개체를 만듭니다.
- PdfDocument.Form 속성을 통해 문서에서 양식 위젯을 가져옵니다.
- 위젯을 반복하고 특정 위젯이 PdfSignatureFieldWidget인지 확인합니다.
- PdfFieldCollection.RemoveAt() 메서드를 사용하여 서명 위젯을 제거합니다.
- PdfDocument.SaveToFile() 메서드를 사용하여 문서를 다른 PDF 파일에 저장합니다.
- 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일 평가판 라이센스 요청 자신을 위해.
C#/VB.NET: aggiungi o rimuovi firme digitali in PDF
Sommario
Installato tramite NuGet
PM> Install-Package Spire.PDF
Link correlati
Poiché i documenti PDF diventano sempre più popolari nel mondo degli affari, garantirne l'autenticità è diventata una preoccupazione fondamentale. Firmare i PDF con una firma basata su certificato può proteggere il contenuto e anche far sapere ad altri chi ha firmato o approvato il documento. In questo articolo imparerai come farlo firmare digitalmente i PDF con una firma invisibile o visibile e come rimuovere le firme digitali dai PDF utilizzando Spire.PDF for .NET.
- Aggiungi una firma digitale invisibile al PDF
- Aggiungi una firma digitale visibile al PDF
- Rimuovere le firme digitali dai PDF
Installa Spire.PDF for .NET
Per cominciare, devi aggiungere i file DLL inclusi nel pacchetto Spire.PDF 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.PDF
Aggiungi una firma digitale invisibile al PDF
Di seguito sono riportati i passaggi per aggiungere una firma digitale invisibile al PDF utilizzando Spire.PDF for .NET.
- Crea un oggetto PdfDocument.
- Carica un file PDF di esempio utilizzando il metodo PdfDocument.LoadFromFile().
- Carica un file di certificato pfx durante l'inizializzazione dell'oggetto PdfCertificate.
- Crea un oggetto PdfSignature basato sul certificato.
- Imposta i permessi del documento tramite l'oggetto PdfSignature.
- Salva il documento in un altro file PDF utilizzando il metodo 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();
}
}
}

Aggiungi una firma digitale visibile al PDF
Di seguito sono riportati i passaggi per aggiungere una firma digitale visibile al PDF utilizzando Spire.PDF for .NET.
- Crea un oggetto PdfDocument.
- Carica un file PDF di esempio utilizzando il metodo PdfDocument.LoadFromFile().
- Carica un file di certificato pfx durante l'inizializzazione dell'oggetto PdfCertificate.
- Crea un oggetto PdfSignature e specificane la posizione e le dimensioni sul documento.
- Imposta i dettagli della firma tra cui data, nome, posizione, motivo, immagine della firma scritta a mano e autorizzazioni del documento.
- Salva il documento in un altro file PDF utilizzando il metodo 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();
}
}
}

Rimuovere le firme digitali dai PDF
Di seguito sono riportati i passaggi per rimuovere le firme digitali dal PDF utilizzando Spire.PDF for .NET.
- Crea un oggetto PdfDocument.
- Ottieni i widget del modulo dal documento tramite la proprietà PdfDocument.Form.
- Passa in rassegna i widget e determina se un widget specifico è un PdfSignatureFieldWidget.
- Rimuovere il widget della firma utilizzando il metodo PdfFieldCollection.RemoveAt().
- Salva il documento in un altro file PDF utilizzando il metodo 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");
}
}
}
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#/VB.NET : ajouter ou supprimer des signatures numériques dans un PDF
Table des matières
Installé via NuGet
PM> Install-Package Spire.PDF
Liens connexes
Alors que les documents PDF deviennent de plus en plus populaires dans les entreprises, garantir leur authenticité est devenu une préoccupation majeure. La signature de PDF avec une signature basée sur un certificat peut protéger le contenu et également permettre aux autres de savoir qui a signé ou approuvé le document. Dans cet article, vous apprendrez comment signer numériquement un PDF avec une signature invisible ou visible, et comment supprimer les signatures numériques d'un PDF à l'aide de Spire.PDF for .NET.
- Ajouter une signature numérique invisible au PDF
- Ajouter une signature numérique visible au PDF
- Supprimer les signatures numériques du PDF
Installer Spire.PDF for .NET
Pour commencer, vous devez ajouter les fichiers DLL inclus dans le package Spire.PDF 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.PDF
Ajouter une signature numérique invisible au PDF
Voici les étapes pour ajouter une signature numérique invisible au PDF à l'aide de Spire.PDF for .NET.
- Créez un objet PdfDocument.
- Chargez un exemple de fichier PDF à l'aide de la méthode PdfDocument.LoadFromFile().
- Chargez un fichier de certificat pfx lors de l'initialisation de l'objet PdfCertificate.
- Créez un objet PdfSignature basé sur le certificat.
- Définissez les autorisations du document via l'objet PdfSignature.
- Enregistrez le document dans un autre fichier PDF à l'aide de la méthode 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();
}
}
}

Ajouter une signature numérique visible au PDF
Voici les étapes pour ajouter une signature numérique visible au PDF à l'aide de Spire.PDF for .NET.
- Créez un objet PdfDocument.
- Chargez un exemple de fichier PDF à l'aide de la méthode PdfDocument.LoadFromFile().
- Chargez un fichier de certificat pfx lors de l'initialisation de l'objet PdfCertificate.
- Créez un objet PdfSignature et spécifiez sa position et sa taille sur le document.
- Définissez les détails de la signature, notamment la date, le nom, le lieu, le motif, l'image de la signature manuscrite et les autorisations du document.
- Enregistrez le document dans un autre fichier PDF à l'aide de la méthode 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();
}
}
}

Supprimer les signatures numériques du PDF
Voici les étapes pour supprimer les signatures numériques d'un PDF à l'aide de Spire.PDF for .NET.
- Créez un objet PdfDocument.
- Obtenez des widgets de formulaire à partir du document via la propriété PdfDocument.Form.
- Parcourez les widgets et déterminez si un widget spécifique est un PdfSignatureFieldWidget.
- Supprimez le widget de signature à l'aide de la méthode PdfFieldCollection.RemoveAt().
- Enregistrez le document dans un autre fichier PDF à l'aide de la méthode 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");
}
}
}
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: Convert Multiple Images into a Single PDF
Table of Contents
Installed via NuGet
PM> Install-Package Spire.PDF
Related Links
If you have multiple images that you want to combine into one file for easier distribution or storage, converting them into a single PDF document is a great solution. This process not only saves space but also ensures that all your images are kept together in one file, making it convenient to share or transfer. In this article, you will learn how to combine several images into a single PDF document in C# and VB.NET 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 DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.PDF
Combine Multiple Images into a Single PDF in C# and VB.NET
In order to convert all the images in a folder to a PDF, we iterate through each image, add a new page to the PDF with the same size as the image, and then draw the image onto the new page. The following are the detailed steps.
- Create a PdfDocument object.
- Set the page margins to zero using PdfDocument.PageSettings.SetMargins() method.
- Get the folder where the images are stored.
- Iterate through each image file in the folder, and get the width and height of a specific image.
- Add a new page that has the same width and height as the image to the PDF document using PdfDocument.Pages.Add() method.
- Draw the image on the page using PdfPageBase.Canvas.DrawImage() method.
- Save the document using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace ConvertMultipleImagesIntoPdf
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Set the page margins to 0
doc.PageSettings.SetMargins(0);
//Get the folder where the images are stored
DirectoryInfo folder = new DirectoryInfo(@"C:\Users\Administrator\Desktop\Images");
//Iterate through the files in the folder
foreach (FileInfo file in folder.GetFiles())
{
//Load a particular image
Image image = Image.FromFile(file.FullName);
//Get the image width and height
float width = image.PhysicalDimension.Width;
float height = image.PhysicalDimension.Height;
//Add a page that has the same size as the image
PdfPageBase page = doc.Pages.Add(new SizeF(width, height));
//Create a PdfImage object based on the image
PdfImage pdfImage = PdfImage.FromImage(image);
//Draw image at (0, 0) of the page
page.Canvas.DrawImage(pdfImage, 0, 0, pdfImage.Width, pdfImage.Height);
}
//Save to file
doc.SaveToFile("CombinaImagesToPdf.pdf");
doc.Dispose();
}
}
}

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: Converta várias imagens em um único PDF
Índice
Instalado via NuGet
PM> Install-Package Spire.PDF
Links Relacionados
Se você tiver várias imagens que deseja combinar em um arquivo para facilitar a distribuição ou armazenamento, convertê-las em um único documento PDF é uma ótima solução. Esse processo não apenas economiza espaço, mas também garante que todas as suas imagens sejam mantidas juntas em um arquivo, facilitando o compartilhamento ou a transferência. Neste artigo você aprenderá como combine várias imagens em um único documento PDF em C# e VB.NET 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 DLL podem ser baixados deste link ou instalados via NuGet.
PM> Install-Package Spire.PDF
Combine várias imagens em um único PDF em C# e VB.NET
Para converter todas as imagens de uma pasta em PDF, iteramos cada imagem, adicionamos uma nova página ao PDF com o mesmo tamanho da imagem e, em seguida, desenhamos a imagem na nova página. A seguir estão as etapas detalhadas.
- Crie um objeto PdfDocument.
- Defina as margens da página como zero usando o método PdfDocument.PageSettings.SetMargins().
- Obtenha a pasta onde as imagens estão armazenadas.
- Itere cada arquivo de imagem na pasta e obtenha a largura e a altura de uma imagem específica.
- Adicione uma nova página que tenha a mesma largura e altura da imagem ao documento PDF usando o método PdfDocument.Pages.Add().
- Desenhe a imagem na página usando o método PdfPageBase.Canvas.DrawImage().
- Salve o documento usando o método PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace ConvertMultipleImagesIntoPdf
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Set the page margins to 0
doc.PageSettings.SetMargins(0);
//Get the folder where the images are stored
DirectoryInfo folder = new DirectoryInfo(@"C:\Users\Administrator\Desktop\Images");
//Iterate through the files in the folder
foreach (FileInfo file in folder.GetFiles())
{
//Load a particular image
Image image = Image.FromFile(file.FullName);
//Get the image width and height
float width = image.PhysicalDimension.Width;
float height = image.PhysicalDimension.Height;
//Add a page that has the same size as the image
PdfPageBase page = doc.Pages.Add(new SizeF(width, height));
//Create a PdfImage object based on the image
PdfImage pdfImage = PdfImage.FromImage(image);
//Draw image at (0, 0) of the page
page.Canvas.DrawImage(pdfImage, 0, 0, pdfImage.Width, pdfImage.Height);
}
//Save to file
doc.SaveToFile("CombinaImagesToPdf.pdf");
doc.Dispose();
}
}
}

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#/VB.NET: преобразование нескольких изображений в один PDF-файл
Оглавление
Установлено через NuGet
PM> Install-Package Spire.PDF
Ссылки по теме
Если у вас есть несколько изображений, которые вы хотите объединить в один файл для упрощения распространения или хранения, отличным решением будет их преобразование в один PDF-документ. Этот процесс не только экономит место, но и гарантирует, что все ваши изображения будут храниться в одном файле, что делает их удобными для совместного использования или передачи. В этой статье вы узнаете, как объединить несколько изображений в один PDF-документ на C# и VB.NET с помощью Spire.PDF for .NET.
Установите Spire.PDF for .NET
Для начала вам необходимо добавить файлы DLL, включенные в пакет Spire.PDF for.NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить по этой ссылке или установить через NuGet.
PM> Install-Package Spire.PDF
Объединение нескольких изображений в один PDF-файл в C# и VB.NET
Чтобы преобразовать все изображения в папке в PDF-файл, мы перебираем каждое изображение, добавляем в PDF-файл новую страницу того же размера, что и изображение, а затем рисуем изображение на новой странице. Ниже приведены подробные шаги.
- Создайте объект PDFDocument.
- Установите поля страницы на ноль, используя метод PdfDocument.PageSettings.SetMargins().
- Получите папку, в которой хранятся изображения.
- Переберите каждый файл изображения в папке и получите ширину и высоту определенного изображения.
- Добавьте в PDF-документ новую страницу той же ширины и высоты, что и изображение, с помощью метода PdfDocument.Pages.Add().
- Нарисуйте изображение на странице, используя метод PdfPageBase.Canvas.DrawImage().
- Сохраните документ, используя метод PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
namespace ConvertMultipleImagesIntoPdf
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Set the page margins to 0
doc.PageSettings.SetMargins(0);
//Get the folder where the images are stored
DirectoryInfo folder = new DirectoryInfo(@"C:\Users\Administrator\Desktop\Images");
//Iterate through the files in the folder
foreach (FileInfo file in folder.GetFiles())
{
//Load a particular image
Image image = Image.FromFile(file.FullName);
//Get the image width and height
float width = image.PhysicalDimension.Width;
float height = image.PhysicalDimension.Height;
//Add a page that has the same size as the image
PdfPageBase page = doc.Pages.Add(new SizeF(width, height));
//Create a PdfImage object based on the image
PdfImage pdfImage = PdfImage.FromImage(image);
//Draw image at (0, 0) of the page
page.Canvas.DrawImage(pdfImage, 0, 0, pdfImage.Width, pdfImage.Height);
}
//Save to file
doc.SaveToFile("CombinaImagesToPdf.pdf");
doc.Dispose();
}
}
}

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