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

Instalado via NuGet

PM> Install-Package Spire.PDF

Links Relacionados

XPS é um formato semelhante ao PDF, mas usa XML no layout, aparência e informações de impressão de um arquivo. O formato XPS foi desenvolvido pela Microsoft e é suportado nativamente pelos sistemas operacionais Windows. Se você deseja trabalhar com seus arquivos PDF em um computador com Windows sem instalar outro software, pode convertê-lo para o formato XPS. Da mesma forma, se você precisar compartilhar um arquivo XPS com um usuário de Mac ou usá-lo em vários dispositivos, é mais recomendável convertê-lo em PDF. Este artigo demonstrará como programaticamente converta PDF para XPS ou XPS para PDF usando Spire.PDF for .NET.

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 

Converta PDF para XPS em C# e VB.NET

O Spire.PDF for .NET oferece suporte à conversão de PDF para vários formatos de arquivo e, para obter a conversão de PDF para XPS, você só precisa de três linhas de código principal. A seguir estão as etapas detalhadas.

  • Crie uma instância PdfDocument.
  • Carregue um documento PDF de amostra usando o método PdfDocument.LoadFromFile().
  • Converta o documento PDF em um arquivo XPS usando o método PdfDocument.SaveToFile (string filename, FileFormat.XPS).
  • C#
  • VB.NET
using Spire.Pdf;
    
    namespace ConvertPdfToXps
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
    
                //Load sample PDF document
                pdf.LoadFromFile("sample.pdf");
    
                //Save it to XPS format
                pdf.SaveToFile("ToXPS.xps", FileFormat.XPS);
                pdf.Close();
            }
        }
    }

C#/VB.NET: Convert PDF to XPS or XPS to PDF

Converter XPS para PDF em C# e VB.NET

A conversão de XPS para PDF também pode ser obtida com o Spire.PDF for .NET. Durante a conversão, você pode definir para manter a imagem de alta qualidade no arquivo PDF gerado usando o método PdfDocument.ConvertOptions.SetXpsToPdfOptions(). A seguir estão as etapas detalhadas.

  • Crie uma instância PdfDocument.
  • Carregue um arquivo XPS usando o método PdfDocument.LoadFromFile(string filename, FileFormat.XPS) ou o método PdfDocument.LoadFromXPS().
  • Durante a conversão, defina as opções de conversão de XPS para PDF para manter imagens de alta qualidade usando o método PdfDocument.ConvertOptions.SetXpsToPdfOptions().
  • Salve o arquivo XPS em um arquivo PDF usando o método PdfDocument.SaveToFile(string filename, FileFormat.PDF).
  • C#
  • VB.NET
using Spire.Pdf;
    
    namespace ConvertXPStoPDF
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
    
                //Load a sample XPS file
                pdf.LoadFromFile("Sample.xps", FileFormat.XPS);
                //pdf.LoadFromXPS("Sample.xps");
    
                //Keep high quality images when converting XPS to PDF
                pdf.ConvertOptions.SetXpsToPdfOptions(true);
    
                //Save the XPS file to PDF
                pdf.SaveToFile("XPStoPDF.pdf", FileFormat.PDF);
            }
        }
    }

C#/VB.NET: Convert PDF to XPS or XPS to PDF

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

Установлено через NuGet

PM> Install-Package Spire.PDF

Ссылки по теме

XPS — это формат, похожий на PDF, но использующий XML в макете, внешнем виде и информации о печати файла. Формат XPS был разработан Microsoft и изначально поддерживается операционными системами Windows. Если вы хотите работать с файлами PDF на компьютере с Windows без установки другого программного обеспечения, вы можете преобразовать его в формат XPS. Точно так же, если вам нужно поделиться файлом XPS с пользователем Mac или использовать его на различных устройствах, рекомендуется преобразовать его в PDF. В этой статье будет показано, как программно конвертировать PDF в XPS или XPS в PDF используя Spire.PDF for .NET.

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

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

PM> Install-Package Spire.PDF 

Преобразование PDF в XPS в C# и VB.NET

Spire.PDF for .NET поддерживает преобразование PDF в файлы различных форматов, а для преобразования PDF в XPS вам потребуется всего три строки основного кода. Ниже приведены подробные шаги.

  • Создайте экземпляр PdfDocument.
  • Загрузите образец PDF-документа с помощью метода PdfDocument.LoadFromFile().
  • Преобразуйте документ PDF в файл XPS, используя метод PdfDocument.SaveToFile (строковое имя файла, FileFormat.XPS).
  • C#
  • VB.NET
using Spire.Pdf;
    
    namespace ConvertPdfToXps
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
    
                //Load sample PDF document
                pdf.LoadFromFile("sample.pdf");
    
                //Save it to XPS format
                pdf.SaveToFile("ToXPS.xps", FileFormat.XPS);
                pdf.Close();
            }
        }
    }

C#/VB.NET: Convert PDF to XPS or XPS to PDF

Преобразование XPS в PDF на C# и VB.NET

Преобразование XPS в PDF также можно выполнить с помощью Spire.PDF for .NET. Во время преобразования вы можете настроить сохранение изображения высокого качества в сгенерированном PDF-файле с помощью метода PdfDocument.ConvertOptions.SetXpsToPdfOptions(). Ниже приведены подробные шаги.

  • Создайте экземпляр PdfDocument.
  • Загрузите файл XPS с помощью метода PdfDocument.LoadFromFile(string filename, FileFormat.XPS) или метода PdfDocument.LoadFromXPS().
  • Во время преобразования установите параметры преобразования XPS в PDF, чтобы сохранить изображения высокого качества с помощью метода PdfDocument.ConvertOptions.SetXpsToPdfOptions().
  • Сохраните файл XPS в файл PDF с помощью метода PdfDocument.SaveToFile(строковое имя файла, FileFormat.PDF).
  • C#
  • VB.NET
using Spire.Pdf;
    
    namespace ConvertXPStoPDF
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
    
                //Load a sample XPS file
                pdf.LoadFromFile("Sample.xps", FileFormat.XPS);
                //pdf.LoadFromXPS("Sample.xps");
    
                //Keep high quality images when converting XPS to PDF
                pdf.ConvertOptions.SetXpsToPdfOptions(true);
    
                //Save the XPS file to PDF
                pdf.SaveToFile("XPStoPDF.pdf", FileFormat.PDF);
            }
        }
    }

C#/VB.NET: Convert PDF to XPS or XPS to PDF

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

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

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

Über NuGet installiert

PM> Install-Package Spire.PDF

verwandte Links

XPS ist ein Format ähnlich wie PDF, verwendet jedoch XML für Layout, Erscheinungsbild und Druckinformationen einer Datei. Das XPS-Format wurde von Microsoft entwickelt und wird von den Windows-Betriebssystemen nativ unterstützt. Wenn Sie Ihre PDF-Dateien auf einem Windows-Computer bearbeiten möchten, ohne andere Software zu installieren, können Sie sie in das XPS-Format konvertieren. Wenn Sie eine XPS-Datei mit einem Mac-Benutzer teilen oder auf verschiedenen Geräten verwenden müssen, ist es ebenfalls empfehlenswerter, sie in PDF zu konvertieren. In diesem Artikel wird gezeigt, wie man programmgesteuert vorgeht Konvertieren Sie PDF in XPS oder XPS in PDF Verwendung von Spire.PDF for .NET.

Installieren Sie Spire.PDF for .NET

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

PM> Install-Package Spire.PDF 

Konvertieren Sie PDF in XPS in C# und VB.NET

Spire.PDF for .NET unterstützt die Konvertierung von PDF in verschiedene Dateiformate. Für die Konvertierung von PDF in XPS benötigen Sie lediglich drei Zeilen Kerncode. Im Folgenden finden Sie die detaillierten Schritte.

  • Erstellen Sie eine PdfDocument-Instanz.
  • Laden Sie ein Beispiel-PDF-Dokument mit der Methode PdfDocument.LoadFromFile().
  • Konvertieren Sie das PDF-Dokument mit der Methode PdfDocument.SaveToFile (Zeichenfolge Dateiname, FileFormat.XPS) in eine XPS-Datei.
  • C#
  • VB.NET
using Spire.Pdf;
    
    namespace ConvertPdfToXps
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
    
                //Load sample PDF document
                pdf.LoadFromFile("sample.pdf");
    
                //Save it to XPS format
                pdf.SaveToFile("ToXPS.xps", FileFormat.XPS);
                pdf.Close();
            }
        }
    }

C#/VB.NET: Convert PDF to XPS or XPS to PDF

Konvertieren Sie XPS in PDF in C# und VB.NET

Auch die Konvertierung von XPS nach PDF ist mit Spire.PDF for .NET möglich. Während der Konvertierung können Sie mit der Methode PdfDocument.ConvertOptions.SetXpsToPdfOptions() festlegen, dass in der generierten PDF-Datei eine hohe Bildqualität erhalten bleibt. Im Folgenden finden Sie die detaillierten Schritte.

  • Erstellen Sie eine PdfDocument-Instanz.
  • Laden Sie eine XPS-Datei mit der Methode PdfDocument.LoadFromFile(string filename, FileFormat.XPS) oder der Methode PdfDocument.LoadFromXPS().
  • Legen Sie während der Konvertierung mithilfe der Methode PdfDocument.ConvertOptions.SetXpsToPdfOptions() die XPS-zu-PDF-Konvertierungsoptionen fest, um qualitativ hochwertige Bilder beizubehalten.
  • Speichern Sie die XPS-Datei mit der Methode PdfDocument.SaveToFile(string filename, FileFormat.PDF) in einer PDF-Datei.
  • C#
  • VB.NET
using Spire.Pdf;
    
    namespace ConvertXPStoPDF
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
    
                //Load a sample XPS file
                pdf.LoadFromFile("Sample.xps", FileFormat.XPS);
                //pdf.LoadFromXPS("Sample.xps");
    
                //Keep high quality images when converting XPS to PDF
                pdf.ConvertOptions.SetXpsToPdfOptions(true);
    
                //Save the XPS file to PDF
                pdf.SaveToFile("XPStoPDF.pdf", FileFormat.PDF);
            }
        }
    }

C#/VB.NET: Convert PDF to XPS or XPS to PDF

Beantragen Sie eine temporäre Lizenz

Wenn Sie die Bewertungsmeldung aus den generierten Dokumenten entfernen oder die Funktionseinschränkungen beseitigen möchten, wenden Sie sich bitte an uns Fordern Sie eine 30-Tage-Testlizenz an für sich selbst.

Siehe auch

Instalado a través de NuGet

PM> Install-Package Spire.PDF

enlaces relacionados

XPS es un formato similar a PDF pero utiliza XML en el diseño, la apariencia y la información de impresión de un archivo. El formato XPS fue desarrollado por Microsoft y es compatible de forma nativa con los sistemas operativos Windows. Si desea trabajar con sus archivos PDF en una computadora con Windows sin instalar otro software, puede convertirlos al formato XPS. Asimismo, si necesita compartir un archivo XPS con un usuario de Mac o usarlo en varios dispositivos, es más recomendable convertirlo a PDF. Este artículo demostrará cómo programáticamente convierta PDF a XPS o XPS a PDF utilizando Spire.PDF for .NET.

Instalar Spire.PDF for .NET

Para empezar, debe agregar los archivos DLL incluidos en el paquete Spire.PDF for .NET como referencias en su proyecto .NET. Los archivos DLL se pueden descargar desde este enlace o instalar a través de NuGet.

PM> Install-Package Spire.PDF 

Convierta PDF a XPS en C# y VB.NET

Spire.PDF for .NET admite la conversión de PDF a varios formatos de archivo y, para lograr la conversión de PDF a XPS, solo necesita tres líneas de código central. Los siguientes son los pasos detallados.

  • Cree una instancia de PdfDocument.
  • Cargue un documento PDF de muestra utilizando el método PdfDocument.LoadFromFile().
  • Convierta el documento PDF en un archivo XPS utilizando el método PdfDocument.SaveToFile (nombre de archivo de cadena, FileFormat.XPS).
  • C#
  • VB.NET
using Spire.Pdf;
    
    namespace ConvertPdfToXps
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
    
                //Load sample PDF document
                pdf.LoadFromFile("sample.pdf");
    
                //Save it to XPS format
                pdf.SaveToFile("ToXPS.xps", FileFormat.XPS);
                pdf.Close();
            }
        }
    }

C#/VB.NET: Convert PDF to XPS or XPS to PDF

Convierta XPS a PDF en C# y VB.NET

La conversión de XPS a PDF también se puede lograr con Spire.PDF for .NET. Durante la conversión, puede configurar para mantener una imagen de alta calidad en el archivo PDF generado utilizando el método PdfDocument.ConvertOptions.SetXpsToPdfOptions(). Los siguientes son los pasos detallados.

  • Cree una instancia de PdfDocument.
  • Cargue un archivo XPS usando el método PdfDocument.LoadFromFile(string filename, FileFormat.XPS) o el método PdfDocument.LoadFromXPS().
  • Durante la conversión, configure las opciones de conversión de XPS a PDF para mantener imágenes de alta calidad utilizando el método PdfDocument.ConvertOptions.SetXpsToPdfOptions().
  • Guarde el archivo XPS en un archivo PDF usando el método PdfDocument.SaveToFile(string filename, FileFormat.PDF).
  • C#
  • VB.NET
using Spire.Pdf;
    
    namespace ConvertXPStoPDF
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
    
                //Load a sample XPS file
                pdf.LoadFromFile("Sample.xps", FileFormat.XPS);
                //pdf.LoadFromXPS("Sample.xps");
    
                //Keep high quality images when converting XPS to PDF
                pdf.ConvertOptions.SetXpsToPdfOptions(true);
    
                //Save the XPS file to PDF
                pdf.SaveToFile("XPStoPDF.pdf", FileFormat.PDF);
            }
        }
    }

C#/VB.NET: Convert PDF to XPS or XPS to PDF

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

NuGet을 통해 설치됨

PM> Install-Package Spire.PDF

관련된 링크들

XPS는 PDF와 유사한 형식이지만 파일의 레이아웃, 모양 및 인쇄 정보에 XML을 사용합니다. XPS 형식은 Microsoft에서 개발했으며 기본적으로 Windows 운영 체제에서 지원됩니다. 다른 소프트웨어를 설치하지 않고 Windows 컴퓨터에서 PDF 파일로 작업하려면 XPS 형식으로 변환할 수 있습니다. 마찬가지로 XPS 파일을 Mac 사용자와 공유하거나 다양한 기기에서 사용해야 하는 경우 PDF로 변환하는 것이 좋습니다. 이 문서에서는 프로그래밍 방식으로 PDF를 XPS로 또는 XPS를 PDF로 변환Spire.PDF for .NET사용.

Spire.PDF for .NET 설치

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

PM> Install-Package Spire.PDF 

C# 및 VB.NET에서 PDF를 XPS로 변환

Spire.PDF for .NET 다양한 파일 형식으로 변환하는 것을 지원하며 PDF를 XPS로 변환하려면 세 줄의 핵심 코드만 있으면 됩니다. 다음은 세부 단계입니다.

  • PdfDocument 인스턴스를 만듭니다.
  • PdfDocument.LoadFromFile() 메서드를 사용하여 샘플 PDF 문서를 로드합니다.
  • PdfDocument.SaveToFile(문자열 파일 이름, FileFormat.XPS) 메서드를 사용하여 PDF 문서를 XPS 파일로 변환합니다.
  • C#
  • VB.NET
using Spire.Pdf;
    
    namespace ConvertPdfToXps
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
    
                //Load sample PDF document
                pdf.LoadFromFile("sample.pdf");
    
                //Save it to XPS format
                pdf.SaveToFile("ToXPS.xps", FileFormat.XPS);
                pdf.Close();
            }
        }
    }

C#/VB.NET: Convert PDF to XPS or XPS to PDF

C# 및 VB.NET에서 XPS를 PDF로 변환

Spire.PDF for .NET 사용하여 XPS에서 PDF로 변환할 수도 있습니다. 변환하는 동안 PdfDocument.ConvertOptions.SetXpsToPdfOptions() 메서드를 사용하여 생성된 PDF 파일에 고품질 이미지를 유지하도록 설정할 수 있습니다. 다음은 세부 단계입니다.

  • PdfDocument 인스턴스를 만듭니다.
  • PdfDocument.LoadFromFile(문자열 파일 이름, FileFormat.XPS) 메서드 또는 PdfDocument.LoadFromXPS() 메서드를 사용하여 XPS 파일을 로드합니다.
  • 변환하는 동안 XPS에서 PDF로 변환 옵션을 설정하여 PdfDocument.ConvertOptions.SetXpsToPdfOptions() 메서드를 사용하여 고품질 이미지를 유지합니다.
  • PdfDocument.SaveToFile(문자열 파일 이름, FileFormat.PDF) 메서드를 사용하여 XPS 파일을 PDF 파일로 저장합니다.
  • C#
  • VB.NET
using Spire.Pdf;
    
    namespace ConvertXPStoPDF
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
    
                //Load a sample XPS file
                pdf.LoadFromFile("Sample.xps", FileFormat.XPS);
                //pdf.LoadFromXPS("Sample.xps");
    
                //Keep high quality images when converting XPS to PDF
                pdf.ConvertOptions.SetXpsToPdfOptions(true);
    
                //Save the XPS file to PDF
                pdf.SaveToFile("XPStoPDF.pdf", FileFormat.PDF);
            }
        }
    }

C#/VB.NET: Convert PDF to XPS or XPS to PDF

임시 면허 신청

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

또한보십시오