NuGet을 통해 설치됨

PM> Install-Package Spire.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 파일 암호화

PDF 파일을 암호화하기 위한 두 가지 종류의 암호가 있습니다 비밀번호 열기 그리고 권한 암호. 전자는 PDF 파일을 열도록 설정되어 있고 후자는 인쇄, 내용 복사, 주석 달기 등을 제한하도록 설정되어 있습니다.

Spire.PDF for .NET에서 제공하는 PdfSecurity.Encrypt(string openPassword, string permissionPassword, PdfPermissionsFlags permission, PdfEncryptionKeySize keySize) 메서드를 사용하면 PDF 파일을 암호화하기 위해 열기 암호와 권한 암호를 모두 설정할 수 있습니다. 자세한 단계는 다음과 같습니다.

  • PdfDocument 개체를 만듭니다.
  • PdfDocument.LoadFromFile() 메서드를 사용하여 샘플 PDF 파일을 로드합니다.
  • PdfDocument.Security 속성을 사용하여 문서의 보안 매개변수를 가져옵니다.
  • PdfSecurity.Encrypt(string openPassword, string permissionPassword, PdfPermissionsFlags rights, PdfEncryptionKeySize keySize) 메서드를 사용하여 열기 암호 및 권한 암호로 PDF 파일을 암호화합니다.
  • PdfDocument.SaveToFile() 메서드를 사용하여 결과 파일을 저장합니다.
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Security;
    
    namespace EncryptPDF
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument pdf = new PdfDocument();
    
                //Load a sample PDF file
                pdf.LoadFromFile(@"E:\Files\sample.pdf");
    
                //Encrypt the PDF file with password
                pdf.Security.Encrypt("open", "permission", PdfPermissionsFlags.Print | PdfPermissionsFlags.CopyContent, PdfEncryptionKeySize.Key128Bit);
    
                //Save the result file
                pdf.SaveToFile("Encrypt.pdf", FileFormat.PDF);
            }
        }
    }

C#/VB.NET: Encrypt or Decrypt PDF Files

PDF 파일을 해독하기 위해 암호 제거

PDF 파일에서 암호를 제거해야 하는 경우 PdfSecurity.Encrypt(string openPassword, string permissionPassword, PdfPermissionsFlags permission, PdfEncryptionKeySize keySize, string originalPermissionPassword) 메서드를 호출하는 동안 열기 암호와 권한 암호를 비워 둘 수 있습니다. 자세한 단계는 다음과 같습니다.

  • PdfDocument 개체를 만듭니다.
  • PdfDocument.LoadFromFile(문자열 파일 이름, 문자열 암호) 메서드를 사용하여 암호로 암호화된 PDF 파일을 로드합니다.
  • PdfDocument.Security 속성을 사용하여 문서의 보안 매개변수를 가져옵니다.
  • PdfSecurity.Encrypt(string openPassword, string permissionPassword, PdfPermissionsFlags rights, PdfEncryptionKeySize keySize, string originalPermissionPassword) 메서드를 사용하여 열기 암호 및 권한 암호를 비워 설정하여 PDF 파일을 해독합니다.
  • PdfDocument.SaveToFile() 메서드를 사용하여 결과 파일을 저장합니다.
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Security;
    
    namespace DecryptPDF
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument pdf = new PdfDocument();
    
                //Load the encrypted PDF file with password
                pdf.LoadFromFile("Encrypt.pdf", "open");
    
                //Set the password as empty to decrypt PDF
                pdf.Security.Encrypt(string.Empty, string.Empty, PdfPermissionsFlags.Default, PdfEncryptionKeySize.Key128Bit, "permission");
    
                //Save the result file
                pdf.SaveToFile("Decrypt.pdf", FileFormat.PDF);
            }
        }
    } 

C#/VB.NET: Encrypt or Decrypt PDF Files

임시 면허 신청

생성된 문서에서 평가 메시지를 제거하거나 기능 제한을 제거하려면 다음을 수행하십시오 30일 평가판 라이선스 요청 자신을 위해.

또한보십시오

Installato tramite NuGet

PM> Install-Package Spire.PDF

Link correlati

La crittografia dei PDF è un compito cruciale quando si tratta di condividere documenti riservati su Internet. Crittografando i file PDF con password complesse, è possibile proteggere i dati del file dall'accesso da parte di soggetti non autorizzati. In alcuni casi, potrebbe anche essere necessario rimuovere la password per rendere pubblico il documento. In questo articolo imparerai a programmaticamente crittografare o decrittografare un file PDF utilizzando Spire.PDF for .NET.

Installa Spire.PDF for .NET

Per cominciare, è necessario aggiungere i file DLL inclusi nel pacchetto Spire.PDF for.NET come riferimenti nel progetto .NET. I file DLL possono essere scaricati da questo link o installato tramite NuGet.

PM> Install-Package Spire.PDF

Crittografare un file PDF con password

Esistono due tipi di password per crittografare un file PDF: password di apertura e password di autorizzazione. Il primo è impostato per aprire il file PDF, mentre il secondo è impostato per limitare la stampa, la copia dei contenuti, i commenti, ecc. Se un file PDF è protetto con entrambi i tipi di password, può essere aperto con entrambe le password.

Il metodo PdfSecurity.Encrypt(string openPassword, string permissionPassword, PdfPermissionsFlags permissions, PdfEncryptionKeySize keySize) offerto da Spire.PDF for .NET consente di impostare sia la password di apertura che la password di autorizzazione per crittografare i file PDF. I passaggi dettagliati sono i seguenti.

  • Creare un oggetto PdfDocument.
  • Carica un file PDF di esempio utilizzando il metodo PdfDocument.LoadFromFile().
  • Ottiene i parametri di sicurezza del documento utilizzando la proprietà PdfDocument.Security.
  • Crittografare il file PDF con password di apertura e password di autorizzazione utilizzando il metodo PdfSecurity.Encrypt(string openPassword, string permissionPassword, PdfPermissionsFlags, PdfEncryptionKeySize keySize).
  • Salvare il file dei risultati utilizzando il metodo PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Security;
    
    namespace EncryptPDF
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument pdf = new PdfDocument();
    
                //Load a sample PDF file
                pdf.LoadFromFile(@"E:\Files\sample.pdf");
    
                //Encrypt the PDF file with password
                pdf.Security.Encrypt("open", "permission", PdfPermissionsFlags.Print | PdfPermissionsFlags.CopyContent, PdfEncryptionKeySize.Key128Bit);
    
                //Save the result file
                pdf.SaveToFile("Encrypt.pdf", FileFormat.PDF);
            }
        }
    }

C#/VB.NET: Encrypt or Decrypt PDF Files

Rimuovi la password per decrittografare un file PDF

Quando è necessario rimuovere la password da un file PDF, è possibile impostare la password di apertura e la password di autorizzazione su vuoto durante la chiamata al metodo PdfSecurity.Encrypt(string openPassword, string permissionPassword, PdfPermissionsFlags, PdfEncryptionKeySize keySize, string originalPermissionPassword). I passaggi dettagliati sono i seguenti.

  • Creare un oggetto PdfDocument.
  • Caricare il file PDF crittografato con password utilizzando il metodo PdfDocument.LoadFromFile (nome file stringa, password stringa).
  • Ottiene i parametri di sicurezza del documento utilizzando la proprietà PdfDocument.Security.
  • Decrittografare il file PDF impostando la password di apertura e la password di autorizzazione su vuoto utilizzando PdfSecurity.Encrypt(string openPassword, string permissionPassword, PdfPermissionsFlags permissions, PdfEncryptionKeySize keySize, string originalPermissionPassword) metodo.
  • Salvare il file dei risultati utilizzando il metodo PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Security;
    
    namespace DecryptPDF
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument pdf = new PdfDocument();
    
                //Load the encrypted PDF file with password
                pdf.LoadFromFile("Encrypt.pdf", "open");
    
                //Set the password as empty to decrypt PDF
                pdf.Security.Encrypt(string.Empty, string.Empty, PdfPermissionsFlags.Default, PdfEncryptionKeySize.Key128Bit, "permission");
    
                //Save the result file
                pdf.SaveToFile("Decrypt.pdf", FileFormat.PDF);
            }
        }
    } 

C#/VB.NET: Encrypt or Decrypt PDF Files

Richiedi una licenza temporanea

Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni delle funzioni, per favore richiedere una licenza di prova di 30 giorni per te.

Guarda anche

Le cryptage PDF est une tâche cruciale lorsqu'il s'agit de partager des documents confidentiels sur Internet. En cryptant les fichiers PDF avec des mots de passe forts, vous pouvez protéger les données du fichier contre l'accès par des parties non autorisées. Dans certains cas, il peut également être nécessaire de supprimer le mot de passe pour rendre le document public. Dans cet article, vous apprendrez à programmer chiffrer ou déchiffrer un fichier PDF en utilisant Spire.PDF for .NET.

Installer Spire.PDF for .NET

Pour commencer, vous devez ajouter les fichiers DLL inclus dans le package Spire.PDF for .NET en tant que 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

Crypter un fichier PDF avec un mot de passe

Il existe deux types de mots de passe pour chiffrer un fichier PDF - ouvrir le mot de passe et le mot de passe d'autorisation. Le premier est configuré pour ouvrir le fichier PDF, tandis que le second est configuré pour restreindre l'impression, la copie de contenu, les commentaires, etc. Si un fichier PDF est sécurisé avec les deux types de mots de passe, il peut être ouvert avec l'un ou l'autre mot de passe.

La méthode PdfSecurity.Encrypt(string openPassword, string permissionPassword, PdfPermissionsFlags permissions, PdfEncryptionKeySize keySize) proposée par Spire.PDF for .NET vous permet de définir à la fois un mot de passe d'ouverture et un mot de passe d'autorisation pour chiffrer les fichiers PDF. Les étapes détaillées sont les suivantes.

  • Créez un objet PdfDocument.
  • Chargez un exemple de fichier PDF à l'aide de la méthode PdfDocument.LoadFromFile().
  • Obtient les paramètres de sécurité du document à l'aide de la propriété PdfDocument.Security.
  • Chiffrez le fichier PDF avec un mot de passe ouvert et un mot de passe d'autorisation à l'aide de la méthode PdfSecurity.Encrypt(string openPassword, string permissionPassword, PdfPermissionsFlags permissions, PdfEncryptionKeySize keySize).
  • Enregistrez le fichier de résultat à l'aide de la méthode PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Security;
    
    namespace EncryptPDF
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument pdf = new PdfDocument();
    
                //Load a sample PDF file
                pdf.LoadFromFile(@"E:\Files\sample.pdf");
    
                //Encrypt the PDF file with password
                pdf.Security.Encrypt("open", "permission", PdfPermissionsFlags.Print | PdfPermissionsFlags.CopyContent, PdfEncryptionKeySize.Key128Bit);
    
                //Save the result file
                pdf.SaveToFile("Encrypt.pdf", FileFormat.PDF);
            }
        }
    }

C#/VB.NET: Encrypt or Decrypt PDF Files

Supprimer le mot de passe pour décrypter un fichier PDF

Lorsque vous devez supprimer le mot de passe d'un fichier PDF, vous pouvez définir le mot de passe d'ouverture et le mot de passe d'autorisation sur vide lors de l'appel de la méthode PdfSecurity.Encrypt(string openPassword, string permissionPassword, PdfPermissionsFlags permissions, PdfEncryptionKeySize keySize, string originalPermissionPassword). Les étapes détaillées sont les suivantes.

  • Créez un objet PdfDocument.
  • Chargez le fichier PDF crypté avec un mot de passe à l'aide de la méthode PdfDocument.LoadFromFile (nom de fichier de chaîne, mot de passe de chaîne).
  • Obtient les paramètres de sécurité du document à l'aide de la propriété PdfDocument.Security.
  • Décryptez le fichier PDF en définissant le mot de passe d'ouverture et le mot de passe d'autorisation sur vide à l'aide de la méthode PdfSecurity.Encrypt(string openPassword, string permissionPassword, PdfPermissionsFlags permissions, PdfEncryptionKeySize keySize, string originalPermissionPassword).
  • Enregistrez le fichier de résultat à l'aide de la méthode PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Security;
    
    namespace DecryptPDF
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument pdf = new PdfDocument();
    
                //Load the encrypted PDF file with password
                pdf.LoadFromFile("Encrypt.pdf", "open");
    
                //Set the password as empty to decrypt PDF
                pdf.Security.Encrypt(string.Empty, string.Empty, PdfPermissionsFlags.Default, PdfEncryptionKeySize.Key128Bit, "permission");
    
                //Save the result file
                pdf.SaveToFile("Decrypt.pdf", FileFormat.PDF);
            }
        }
    } 

C#/VB.NET: Encrypt or Decrypt PDF Files

Demander une licence temporaire

Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations de la fonction, veuillez demander une licence d'essai de 30 jours pour toi.

Voir également

A assinatura digital garante que o documento assinado não pode ser alterado por ninguém que não seja o seu autor. Adicionar assinaturas é a forma mais comum de garantir a autenticidade do conteúdo do documento. Uma assinatura digital visual em um documento PDF pode mostrar texto ou imagem (por exemplo, assinatura manuscrita). Este artigo apresenta como assinar digitalmente PDFs usando o Spire.PDF for .NET a partir dos três aspectos a seguir.

Instalar 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

Assinar digitalmente PDF com texto

A seguir estão as etapas para adicionar uma assinatura de texto simples a um documento PDF.

  • Crie um objeto PdfDocument e 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, especificando sua posição e tamanho no documento.
  • Defina o modo gráfico de assinatura como SignDetail, que mostrará os detalhes da assinatura em texto simples.
  • Defina os detalhes da assinatura, incluindo nome, informações de contato, motivo, data etc. por meio das propriedades no objeto PdfSignature.
  • Defina as permissões do documento certificado como ForbidChanges e AllowFormFill.
  • Salve o documento em outro arquivo usando o método PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Security;
    using System;
    using System.Drawing;
    using Spire.Pdf.Graphics;
    
    namespace AddTextSignature
    {
        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 - 340, 150, 290, 100);
                signature.Bounds = rectangleF;
                signature.Certificated = true;
    
                //Set the graphics mode to sign detail
                signature.GraphicsMode = GraphicMode.SignDetail;
    
                //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 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("TextSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Digitally Sign PDF with Text or/and Image

Assinar PDF digitalmente com uma imagem

A seguir estão as etapas para adicionar uma assinatura de imagem a um documento PDF.

  • Crie um objeto PdfDocument e 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, especificando sua posição e tamanho no documento.
  • Defina o modo gráfico de assinatura como SignImageOnly, que mostrará apenas a imagem da assinatura.
  • Defina a imagem da assinatura por meio da propriedade PdfSignature.SignImageSource.
  • Defina as permissões do documento certificado como ForbidChanges e AllowFormFill.
  • Salve o documento em outro arquivo usando o método PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Graphics;
    using Spire.Pdf.Security;
    using System.Drawing;
    
    namespace AddImageSignature
    {
        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 - 200, 150, 130, 130);
                signature.Bounds = rectangleF;
                signature.Certificated = true;
    
                //Set the graphics mode to image only
                signature.GraphicsMode = GraphicMode.SignImageOnly;
    
                //Set the sign image source
                signature.SignImageSource = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\verified.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("ImageSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Digitally Sign PDF with Text or/and Image

Assine PDF digitalmente com texto e uma imagem

A seguir estão as etapas para assinar digitalmente um documento PDF com texto e uma imagem.

  • Crie um objeto PdfDocument e 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, especificando sua posição e tamanho no documento.
  • Defina o modo gráfico de assinatura como SignImageAndSignDetail, que mostrará a imagem e os detalhes da assinatura.
  • Defina a imagem da assinatura por meio da propriedade PdfSignature.SignImageSource e defina os detalhes da assinatura, incluindo nome, informações de contato, motivo, data etc. por meio de outras propriedades no objeto PdfSignature.
  • Defina as permissões do documento certificado como ForbidChanges e AllowFormFill.
  • Salve o documento em outro arquivo usando o método PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Security;
    using System;
    using System.Drawing;
    using Spire.Pdf.Graphics;
    
    namespace AddTextAndImageSignature
    {
        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 - 320, 150, 260, 110);
                signature.Bounds = rectangleF;
                signature.Certificated = true;
    
                //Set the graphics mode to image and sign detail
                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\\handSignature.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("TextAndImageSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Digitally Sign PDF with Text or/and Image

Solicitar uma licença temporária

Se você deseja 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 avaliação de 30 dias para você mesmo.

Veja também

Цифровая подпись гарантирует, что подписанный документ не может быть изменен кем-либо, кроме его автора. Добавление подписей является наиболее распространенным способом обеспечения подлинности содержимого документа. Визуальная цифровая подпись в документе 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.

  • Создайте объект PdfDocument и загрузите образец PDF-файла с помощью метода PdfDocument.LoadFromFile().
  • Загрузите файл сертификата .pfx при инициализации объекта PdfCertificate.
  • Создайте объект PdfSignature, указав его положение и размер в документе.
  • Установите для графического режима подписи значение SignDetail, при котором сведения о подписи будут отображаться в виде простого текста.
  • Задайте сведения о подписи, включая имя, контактную информацию, причину, дату и т. д., в свойствах объекта PdfSignature.
  • Установите разрешения сертифицированного документа на ForbidChanges и AllowFormFill.
  • Сохраните документ в другой файл, используя метод PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Security;
    using System;
    using System.Drawing;
    using Spire.Pdf.Graphics;
    
    namespace AddTextSignature
    {
        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 - 340, 150, 290, 100);
                signature.Bounds = rectangleF;
                signature.Certificated = true;
    
                //Set the graphics mode to sign detail
                signature.GraphicsMode = GraphicMode.SignDetail;
    
                //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 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("TextSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Digitally Sign PDF with Text or/and Image

Цифровая подпись PDF с изображением

Ниже приведены шаги по добавлению подписи изображения в документ PDF.

  • Создайте объект PdfDocument и загрузите образец PDF-файла с помощью метода PdfDocument.LoadFromFile().
  • Загрузите файл сертификата .pfx при инициализации объекта PdfCertificate.
  • Создайте объект PdfSignature, указав его положение и размер в документе.
  • Установите для графического режима подписи значение SignImageOnly, при котором будет отображаться только изображение подписи.
  • Задайте изображение подписи через свойство PdfSignature.SignImageSource.
  • Установите разрешения сертифицированного документа на ForbidChanges и AllowFormFill.
  • Сохраните документ в другой файл, используя метод PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Graphics;
    using Spire.Pdf.Security;
    using System.Drawing;
    
    namespace AddImageSignature
    {
        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 - 200, 150, 130, 130);
                signature.Bounds = rectangleF;
                signature.Certificated = true;
    
                //Set the graphics mode to image only
                signature.GraphicsMode = GraphicMode.SignImageOnly;
    
                //Set the sign image source
                signature.SignImageSource = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\verified.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("ImageSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Digitally Sign PDF with Text or/and Image

Цифровая подпись PDF с текстом и изображением

Ниже приведены шаги для цифровой подписи документа PDF с текстом и изображением.

  • Создайте объект PdfDocument и загрузите образец PDF-файла с помощью метода PdfDocument.LoadFromFile().
  • Загрузите файл сертификата .pfx при инициализации объекта PdfCertificate.
  • Создайте объект PdfSignature, указав его положение и размер в документе.
  • Установите для графического режима подписи значение SignImageAndSignDetail, в котором будут отображаться как изображение подписи, так и детали.
  • Установите изображение подписи с помощью свойства PdfSignature.SignImageSource и задайте сведения о подписи, включая имя, контактную информацию, причину, дату и т. д., с помощью других свойств в объекте PdfSignature.
  • Установите разрешения сертифицированного документа на ForbidChanges и AllowFormFill.
  • Сохраните документ в другой файл, используя метод PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Security;
    using System;
    using System.Drawing;
    using Spire.Pdf.Graphics;
    
    namespace AddTextAndImageSignature
    {
        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 - 320, 150, 260, 110);
                signature.Bounds = rectangleF;
                signature.Certificated = true;
    
                //Set the graphics mode to image and sign detail
                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\\handSignature.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("TextAndImageSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Digitally Sign PDF with Text or/and Image

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

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

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

Die digitale Signatur stellt sicher, dass das signierte Dokument von niemand anderem als seinem Autor verändert werden kann. Das Hinzufügen von Signaturen ist die gebräuchlichste Methode, um die Authentizität des Dokumentinhalts sicherzustellen. Eine visuelle digitale Signatur in einem PDF-Dokument kann Text oder ein Bild anzeigen (z. B. eine handschriftliche Unterschrift). In diesem Artikel erfahren Sie, wie das geht PDFs digital signieren Die Verwendung von Spire.PDF for .NET unter den folgenden drei Gesichtspunkten.

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 DLL-Dateien können entweder über diesen Link heruntergeladen oder über NuGet installiert werden.

PM> Install-Package Spire.PDF

PDF mit Text digital signieren

Im Folgenden finden Sie die Schritte zum Hinzufügen einer Nur-Text-Signatur zu einem PDF-Dokument.

  • Erstellen Sie ein PdfDocument-Objekt und 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 dessen Position und Größe im Dokument an.
  • Stellen Sie den Signaturgrafikmodus auf SignDetail ein, wodurch die Signaturdetails im Klartext angezeigt werden.
  • Legen Sie die Signaturdetails, einschließlich Name, Kontaktinformationen, Grund, Datum usw., über die Eigenschaften unter dem PdfSignature-Objekt fest.
  • Legen Sie die Berechtigungen des zertifizierten Dokuments auf ForbidChanges und AllowFormFill fest.
  • Speichern Sie das Dokument mit der Methode PdfDocument.SaveToFile() in einer anderen Datei.
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Security;
    using System;
    using System.Drawing;
    using Spire.Pdf.Graphics;
    
    namespace AddTextSignature
    {
        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 - 340, 150, 290, 100);
                signature.Bounds = rectangleF;
                signature.Certificated = true;
    
                //Set the graphics mode to sign detail
                signature.GraphicsMode = GraphicMode.SignDetail;
    
                //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 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("TextSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Digitally Sign PDF with Text or/and Image

PDF mit einem Bild digital signieren

Im Folgenden finden Sie die Schritte zum Hinzufügen einer Bildsignatur zu einem PDF-Dokument.

  • Erstellen Sie ein PdfDocument-Objekt und 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 dessen Position und Größe im Dokument an.
  • Stellen Sie den Signaturgrafikmodus auf SignImageOnly ein, wodurch nur das Signaturbild angezeigt wird.
  • Legen Sie das Signaturbild über die Eigenschaft PdfSignature.SignImageSource fest.
  • Legen Sie die Berechtigungen des zertifizierten Dokuments auf ForbidChanges und AllowFormFill fest.
  • Speichern Sie das Dokument mit der Methode PdfDocument.SaveToFile() in einer anderen Datei.
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Graphics;
    using Spire.Pdf.Security;
    using System.Drawing;
    
    namespace AddImageSignature
    {
        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 - 200, 150, 130, 130);
                signature.Bounds = rectangleF;
                signature.Certificated = true;
    
                //Set the graphics mode to image only
                signature.GraphicsMode = GraphicMode.SignImageOnly;
    
                //Set the sign image source
                signature.SignImageSource = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\verified.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("ImageSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Digitally Sign PDF with Text or/and Image

Signieren Sie PDFs digital mit Text und einem Bild

Im Folgenden finden Sie die Schritte zum digitalen Signieren eines PDF-Dokuments mit Text und einem Bild.

  • Erstellen Sie ein PdfDocument-Objekt und 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 dessen Position und Größe im Dokument an.
  • Stellen Sie den Signaturgrafikmodus auf SignImageAndSignDetail ein, wodurch sowohl das Signaturbild als auch die Details angezeigt werden.
  • Legen Sie das Signaturbild über die Eigenschaft PdfSignature.SignImageSource fest und legen Sie die Signaturdetails, einschließlich Name, Kontaktinformationen, Grund, Datum usw., über andere Eigenschaften unter dem PdfSignature-Objekt fest.
  • Legen Sie die Berechtigungen des zertifizierten Dokuments auf ForbidChanges und AllowFormFill fest.
  • Speichern Sie das Dokument mit der Methode PdfDocument.SaveToFile() in einer anderen Datei.
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Security;
    using System;
    using System.Drawing;
    using Spire.Pdf.Graphics;
    
    namespace AddTextAndImageSignature
    {
        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 - 320, 150, 260, 110);
                signature.Bounds = rectangleF;
                signature.Certificated = true;
    
                //Set the graphics mode to image and sign detail
                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\\handSignature.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("TextAndImageSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Digitally Sign PDF with Text or/and Image

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

La firma digital asegura que el documento firmado no puede ser alterado por nadie más que su autor. Agregar firmas es la forma más común de asegurar la autenticidad del contenido del documento. Una firma digital visual en un documento PDF puede mostrar texto o una imagen (por ejemplo, una firma manuscrita). Este artículo presenta cómo firmar digitalmente archivos PDF usando Spire.PDF for .NET desde los siguientes tres aspectos.

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 instalar a través de NuGet.

PM> Install-Package Spire.PDF

Firme digitalmente PDF con texto

Los siguientes son los pasos para agregar una firma de texto sin formato a un documento PDF.

  • Cree un objeto PdfDocument y 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, especificando su posición y tamaño en el documento.
  • Establezca el modo de gráficos de firma en SignDetail, que mostrará los detalles de la firma en texto sin formato.
  • Establezca los detalles de la firma, incluido el nombre, la información de contacto, el motivo, la fecha, etc. a través de las propiedades del objeto PdfSignature.
  • Establezca los permisos del documento certificado en ForbidChanges y AllowFormFill.
  • Guarde el documento en otro archivo usando el método PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Security;
    using System;
    using System.Drawing;
    using Spire.Pdf.Graphics;
    
    namespace AddTextSignature
    {
        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 - 340, 150, 290, 100);
                signature.Bounds = rectangleF;
                signature.Certificated = true;
    
                //Set the graphics mode to sign detail
                signature.GraphicsMode = GraphicMode.SignDetail;
    
                //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 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("TextSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Digitally Sign PDF with Text or/and Image

Firme digitalmente PDF con una imagen

Los siguientes son los pasos para agregar una firma de imagen a un documento PDF.

  • Cree un objeto PdfDocument y 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, especificando su posición y tamaño en el documento.
  • Establezca el modo de gráficos de la firma en SignImageOnly, que mostrará solo la imagen de la firma.
  • Establezca la imagen de la firma a través de la propiedad PdfSignature.SignImageSource.
  • Establezca los permisos del documento certificado en ForbidChanges y AllowFormFill.
  • Guarde el documento en otro archivo usando el método PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Graphics;
    using Spire.Pdf.Security;
    using System.Drawing;
    
    namespace AddImageSignature
    {
        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 - 200, 150, 130, 130);
                signature.Bounds = rectangleF;
                signature.Certificated = true;
    
                //Set the graphics mode to image only
                signature.GraphicsMode = GraphicMode.SignImageOnly;
    
                //Set the sign image source
                signature.SignImageSource = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\verified.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("ImageSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Digitally Sign PDF with Text or/and Image

Firme digitalmente un PDF con texto y una imagen

Los siguientes son los pasos para firmar digitalmente un documento PDF con texto y una imagen.

  • Cree un objeto PdfDocument y 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, especificando su posición y tamaño en el documento.
  • Establezca el modo de gráficos de la firma en SignImageAndSignDetail, que mostrará tanto la imagen como los detalles de la firma.
  • Configure la imagen de la firma a través de la propiedad PdfSignature.SignImageSource y configure los detalles de la firma, incluidos el nombre, la información de contacto, el motivo, la fecha, etc. a través de otras propiedades en el objeto PdfSignature.
  • Establezca los permisos del documento certificado en ForbidChanges y AllowFormFill.
  • Guarde el documento en otro archivo usando el método PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Security;
    using System;
    using System.Drawing;
    using Spire.Pdf.Graphics;
    
    namespace AddTextAndImageSignature
    {
        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 - 320, 150, 260, 110);
                signature.Bounds = rectangleF;
                signature.Certificated = true;
    
                //Set the graphics mode to image and sign detail
                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\\handSignature.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("TextAndImageSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Digitally Sign PDF with Text or/and Image

Solicitar 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

디지털 서명은 서명된 문서를 작성자 이외의 다른 사람이 변경할 수 없도록 합니다. 서명을 추가하는 것은 문서 내용의 신뢰성을 보장하는 가장 일반적인 방법입니다. PDF 문서의 시각적 디지털 서명은 텍스트 또는 이미지(예: 자필 서명)를 표시할 수 있습니다. 이 문서에서는 방법을 소개합니다 PDF에 디지털 서명 다음 세 가지 측면에서 Spire.PDF for .NET 사용합니다.

Spire.PDF for .NET 설치

먼저 Spire.PDF for .NET 패키지에 포함된 DLL 파일을 .NET 프로젝트의 참조로 추가해야 합니다. DLL 파일은 이 링크에서 다운로드하거나 NuGet을 통해 설치할 수 있습니다.

PM> Install-Package Spire.PDF

텍스트로 PDF에 디지털 서명

다음은 PDF 문서에 일반 텍스트 서명을 추가하는 단계입니다.

  • PdfDocument 개체를 만들고 PdfDocument.LoadFromFile() 메서드를 사용하여 샘플 PDF 파일을 로드합니다.
  • PdfCertificate 개체를 초기화하는 동안 .pfx 인증서 파일을 로드합니다.
  • 문서에서 위치와 크기를 지정하여 PdfSignature 객체를 만듭니다.
  • 서명 그래픽 모드를 SignDetail로 설정하면 서명 세부 정보가 일반 텍스트로 표시됩니다.
  • PdfSignature 개체 아래의 속성을 통해 이름, 연락처 정보, 이유, 날짜 등 서명 세부 정보를 설정합니다.
  • 인증된 문서의 권한을 ForbidChangesAllowFormFill로 설정합니다.
  • PdfDocument.SaveToFile() 메서드를 사용하여 문서를 다른 파일로 저장합니다.
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Security;
    using System;
    using System.Drawing;
    using Spire.Pdf.Graphics;
    
    namespace AddTextSignature
    {
        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 - 340, 150, 290, 100);
                signature.Bounds = rectangleF;
                signature.Certificated = true;
    
                //Set the graphics mode to sign detail
                signature.GraphicsMode = GraphicMode.SignDetail;
    
                //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 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("TextSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Digitally Sign PDF with Text or/and Image

이미지로 PDF에 디지털 서명

다음은 PDF 문서에 이미지 서명을 추가하는 단계입니다.

  • PdfDocument 개체를 만들고 PdfDocument.LoadFromFile() 메서드를 사용하여 샘플 PDF 파일을 로드합니다.
  • PdfCertificate 개체를 초기화하는 동안 .pfx 인증서 파일을 로드합니다.
  • 문서에서 위치와 크기를 지정하여 PdfSignature 객체를 만듭니다.
  • 서명 그래픽 모드를 SignImageOnly로 설정하면 서명 이미지만 표시됩니다.
  • PdfSignature.SignImageSource 속성을 통해 서명 이미지를 설정합니다.
  • 인증된 문서의 권한을 ForbidChangesAllowFormFill로 설정합니다.
  • PdfDocument.SaveToFile() 메서드를 사용하여 문서를 다른 파일로 저장합니다.
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Graphics;
    using Spire.Pdf.Security;
    using System.Drawing;
    
    namespace AddImageSignature
    {
        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 - 200, 150, 130, 130);
                signature.Bounds = rectangleF;
                signature.Certificated = true;
    
                //Set the graphics mode to image only
                signature.GraphicsMode = GraphicMode.SignImageOnly;
    
                //Set the sign image source
                signature.SignImageSource = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\verified.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("ImageSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Digitally Sign PDF with Text or/and Image

텍스트와 이미지로 PDF에 디지털 서명

다음은 텍스트와 이미지가 포함된 PDF 문서에 디지털 서명하는 단계입니다.

  • PdfDocument 개체를 만들고 PdfDocument.LoadFromFile() 메서드를 사용하여 샘플 PDF 파일을 로드합니다.
  • PdfCertificate 개체를 초기화하는 동안 .pfx 인증서 파일을 로드합니다.
  • 문서에서 위치와 크기를 지정하여 PdfSignature 객체를 만듭니다.
  • 서명 그래픽 모드를 SignImageAndSignDetail로 설정하면 서명 이미지와 세부 정보가 모두 표시됩니다.
  • PdfSignature.SignImageSource 속성을 통해 서명 이미지를 설정하고, PdfSignature 객체 아래의 다른 속성을 통해 이름, 연락처, 이유, 날짜 등의 서명 세부 정보를 설정합니다.
  • 인증된 문서의 권한을 ForbidChanges 및 AllowFormFill로 설정합니다.
  • PdfDocument.SaveToFile() 메서드를 사용하여 문서를 다른 파일로 저장합니다.
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Security;
    using System;
    using System.Drawing;
    using Spire.Pdf.Graphics;
    
    namespace AddTextAndImageSignature
    {
        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 - 320, 150, 260, 110);
                signature.Bounds = rectangleF;
                signature.Certificated = true;
    
                //Set the graphics mode to image and sign detail
                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\\handSignature.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("TextAndImageSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Digitally Sign PDF with Text or/and Image

임시 면허 신청

생성된 문서에서 평가 메시지를 제거하거나 기능 제한을 제거하려면 다음을 수행하십시오 30일 평가판 라이선스 요청 자신을 위해.

또한보십시오

La firma digitale assicura che il documento firmato non possa essere alterato da nessuno che non sia il suo autore. L'aggiunta di firme è il modo più comune per garantire l'autenticità del contenuto del documento. Una firma digitale visiva in un documento PDF può mostrare testo o un'immagine (ad esempio, firma scritta a mano). Questo articolo introduce come firmare digitalmente i PDF utilizzando Spire.PDF for .NET dai seguenti tre aspetti.

Installa Spire.PDF for .NET

Per cominciare, è necessario aggiungere i file DLL inclusi nel pacchetto Spire.PDF for.NET come riferimenti nel progetto .NET. I file DLL possono essere scaricati da questo link o installato tramite NuGet.

PM> Install-Package Spire.PDF

Firma digitalmente PDF con testo

Di seguito sono riportati i passaggi per aggiungere una firma in testo normale a un documento PDF.

  • Creare un oggetto PdfDocument e caricare 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, specificandone la posizione e le dimensioni nel documento.
  • Imposta la modalità grafica della firma su SignDetail, che mostrerà i dettagli della firma in testo normale.
  • Imposta i dettagli della firma, inclusi nome, informazioni di contatto, motivo, data, ecc. tramite le proprietà sotto l'oggetto PdfSignature.
  • Impostare le autorizzazioni del documento certificato su ForbidChanges e AllowFormFill.
  • Salvare il documento in un altro file utilizzando il metodo PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Security;
    using System;
    using System.Drawing;
    using Spire.Pdf.Graphics;
    
    namespace AddTextSignature
    {
        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 - 340, 150, 290, 100);
                signature.Bounds = rectangleF;
                signature.Certificated = true;
    
                //Set the graphics mode to sign detail
                signature.GraphicsMode = GraphicMode.SignDetail;
    
                //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 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("TextSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Digitally Sign PDF with Text or/and Image

Firma digitalmente PDF con un'immagine

Di seguito sono riportati i passaggi per aggiungere una firma immagine a un documento PDF.

  • Creare un oggetto PdfDocument e caricare 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, specificandone la posizione e le dimensioni nel documento.
  • Imposta la modalità grafica della firma su SignImageOnly, che mostrerà solo l'immagine della firma.
  • Impostare l'immagine della firma tramite la proprietà PdfSignature.SignImageSource.
  • Impostare le autorizzazioni del documento certificato su ForbidChanges e AllowFormFill.
  • Salvare il documento in un altro file utilizzando il metodo PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Graphics;
    using Spire.Pdf.Security;
    using System.Drawing;
    
    namespace AddImageSignature
    {
        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 - 200, 150, 130, 130);
                signature.Bounds = rectangleF;
                signature.Certificated = true;
    
                //Set the graphics mode to image only
                signature.GraphicsMode = GraphicMode.SignImageOnly;
    
                //Set the sign image source
                signature.SignImageSource = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\verified.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("ImageSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Digitally Sign PDF with Text or/and Image

Firma digitalmente PDF con testo e un'immagine

Di seguito sono riportati i passaggi per firmare digitalmente un documento PDF con testo e un'immagine.

  • Creare un oggetto PdfDocument e caricare 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, specificandone la posizione e le dimensioni nel documento.
  • Imposta la modalità grafica della firma su SignImageAndSignDetail, che mostrerà sia l'immagine della firma che i dettagli.
  • Impostare l'immagine della firma tramite la proprietà PdfSignature.SignImageSource e impostare i dettagli della firma, inclusi nome, informazioni di contatto, motivo, data e così via tramite altre proprietà nell'oggetto PdfSignature.
  • Impostare le autorizzazioni del documento certificato su ForbidChanges e AllowFormFill.
  • Salvare il documento in un altro file utilizzando il metodo PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Security;
    using System;
    using System.Drawing;
    using Spire.Pdf.Graphics;
    
    namespace AddTextAndImageSignature
    {
        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 - 320, 150, 260, 110);
                signature.Bounds = rectangleF;
                signature.Certificated = true;
    
                //Set the graphics mode to image and sign detail
                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\\handSignature.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("TextAndImageSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Digitally Sign PDF with Text or/and Image

Richiedi una licenza temporanea

Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni delle funzioni, per favore richiedere una licenza di prova di 30 giorni per te.

Guarda anche

La signature numérique garantit que le document signé ne peut être modifié par personne d'autre que son auteur. L'ajout de signatures est le moyen le plus courant de garantir l'authenticité du contenu du document. Une signature numérique visuelle dans un document PDF peut afficher du texte ou une image (par exemple, une signature manuscrite). Cet article explique comment signer numériquement des PDF en utilisant Spire.PDF for .NET à partir des trois aspects suivants.

Installer Spire.PDF for .NET

Pour commencer, vous devez ajouter les fichiers DLL inclus dans le package Spire.PDF for .NET en tant que 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

Signer numériquement un PDF avec du texte

Voici les étapes pour ajouter une signature en texte brut à un document PDF.

  • Créez un objet PdfDocument et 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, en spécifiant sa position et sa taille dans le document.
  • Définissez le mode graphique de la signature sur SignDetail, qui affichera les détails de la signature en texte brut.
  • Définissez les détails de la signature, y compris le nom, les informations de contact, la raison, la date, etc. via les propriétés sous l'objet PdfSignature.
  • Définissez les autorisations du document certifié sur ForbidChanges et AllowFormFill.
  • Enregistrez le document dans un autre fichier à l'aide de la méthode PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Security;
    using System;
    using System.Drawing;
    using Spire.Pdf.Graphics;
    
    namespace AddTextSignature
    {
        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 - 340, 150, 290, 100);
                signature.Bounds = rectangleF;
                signature.Certificated = true;
    
                //Set the graphics mode to sign detail
                signature.GraphicsMode = GraphicMode.SignDetail;
    
                //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 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("TextSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Digitally Sign PDF with Text or/and Image

Signer numériquement un PDF avec une image

Voici les étapes pour ajouter une signature d'image à un document PDF.

  • Créez un objet PdfDocument et 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, en spécifiant sa position et sa taille dans le document.
  • Définissez le mode graphique de la signature sur SignImageOnly, qui n'affichera que l'image de la signature.
  • Définissez l'image de la signature via la propriété PdfSignature.SignImageSource.
  • Définissez les autorisations du document certifié sur ForbidChanges et AllowFormFill.
  • Enregistrez le document dans un autre fichier à l'aide de la méthode PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Graphics;
    using Spire.Pdf.Security;
    using System.Drawing;
    
    namespace AddImageSignature
    {
        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 - 200, 150, 130, 130);
                signature.Bounds = rectangleF;
                signature.Certificated = true;
    
                //Set the graphics mode to image only
                signature.GraphicsMode = GraphicMode.SignImageOnly;
    
                //Set the sign image source
                signature.SignImageSource = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\verified.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("ImageSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Digitally Sign PDF with Text or/and Image

Signer numériquement un PDF avec du texte et une image

Voici les étapes pour signer numériquement un document PDF avec du texte et une image.

  • Créez un objet PdfDocument et 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, en spécifiant sa position et sa taille dans le document.
  • Définissez le mode graphique de la signature sur SignImageAndSignDetail, qui affichera à la fois l'image et les détails de la signature.
  • Définissez l'image de la signature via la propriété PdfSignature.SignImageSource et définissez les détails de la signature, y compris le nom, les informations de contact, la raison, la date, etc. via d'autres propriétés sous l'objet PdfSignature.
  • Définissez les autorisations du document certifié sur ForbidChanges et AllowFormFill.
  • Enregistrez le document dans un autre fichier à l'aide de la méthode PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Security;
    using System;
    using System.Drawing;
    using Spire.Pdf.Graphics;
    
    namespace AddTextAndImageSignature
    {
        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 - 320, 150, 260, 110);
                signature.Bounds = rectangleF;
                signature.Certificated = true;
    
                //Set the graphics mode to image and sign detail
                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\\handSignature.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("TextAndImageSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Digitally Sign PDF with Text or/and Image

Demander une licence temporaire

Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations de la fonction, veuillez demander une licence d'essai de 30 jours pour toi.

Voir également