Saltar al pie de página
USANDO IRONPDF

x509certificate2 Añadir Firma Digital a PDF Programáticamente

x509certificate2 can be used to get important information about an existing certificate (valid dates, issuer, etc.). IronPDF allows you to digitally sign a PDF using C#. You can create a new document or sign an existing PDF file. It requires just a single line of code, as illustrated in the simple steps below.


Step 1

1. Get IronPDF

First, install IronPDF to your Visual Studio project. Get it in whichever way is easier for you, either from DLL download or on the NuGet website. Access the C# Library in Visual Studio and let's add a signature.

# Product Installation using NuGet
nuget install IronPdf
# Product Installation using NuGet
nuget install IronPdf
SHELL

How to Tutorial

2. Understanding Digital Signatures

A Digital Signature is like an electronic driver's license or passport that proves your identity. A digital ID typically contains your name and email address, the name of the organization that issued it, a serial number, and an expiration date. Digital IDs are used for certificate security and digital signatures. This will need to be created with Adobe Acrobat for it to work.


3. Digitally Sign a PDF

Now, let's see the steps for creating an x509certificate2 to digitally sign a PDF using C#.

Today, the IronPDF library offers a simple way to apply signatures, saving time and effort with just a single line of code. You can use it for free during development to test your work. Then, decide on your project. Will you be creating a new document or signing an existing PDF?

In the code example below, a C# form is used to allow the user to select their desired PDF, which can receive a digital signature with a single click.

A .pfx file (Personal Information Exchange Format) should be prepared, which is used to transfer a certificate with the help of a private key.

The SignPdfFile(FileName) method from the PdfSignature class is the main method for a digital signature. Simply select the desired file.

using System.Drawing;
using System.Windows.Forms;
using IronPdf;

namespace DigitalSign
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent(); 
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            // Open a dialog to select the desired PDF file
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = openFileDialog1.FileName; // Display selected PDF path in the textbox
            }
        }

        private void button2_Click(object sender, System.EventArgs e)
        {
            // Use PdfSignature method to digitally sign the selected PDF
            new PdfSignature("Ironpdf.pfx", "123456").SignPdfFile(textBox1.Text);

            // Provide user feedback that signing is complete
            label3.Text = "Completed!";
            label3.BackColor = Color.LightGreen;
            label3.ForeColor = Color.Black;
        }
    }
}
using System.Drawing;
using System.Windows.Forms;
using IronPdf;

namespace DigitalSign
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent(); 
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            // Open a dialog to select the desired PDF file
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = openFileDialog1.FileName; // Display selected PDF path in the textbox
            }
        }

        private void button2_Click(object sender, System.EventArgs e)
        {
            // Use PdfSignature method to digitally sign the selected PDF
            new PdfSignature("Ironpdf.pfx", "123456").SignPdfFile(textBox1.Text);

            // Provide user feedback that signing is complete
            label3.Text = "Completed!";
            label3.BackColor = Color.LightGreen;
            label3.ForeColor = Color.Black;
        }
    }
}
Imports System.Drawing
Imports System.Windows.Forms
Imports IronPdf

Namespace DigitalSign
	Partial Public Class Form1
		Inherits Form

		Public Sub New()
			InitializeComponent()
		End Sub

		Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			' Open a dialog to select the desired PDF file
			If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
				textBox1.Text = openFileDialog1.FileName ' Display selected PDF path in the textbox
			End If
		End Sub

		Private Sub button2_Click(ByVal sender As Object, ByVal e As System.EventArgs)
			' Use PdfSignature method to digitally sign the selected PDF
			Call (New PdfSignature("Ironpdf.pfx", "123456")).SignPdfFile(textBox1.Text)

			' Provide user feedback that signing is complete
			label3.Text = "Completed!"
			label3.BackColor = Color.LightGreen
			label3.ForeColor = Color.Black
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

The above C# code represents a Windows Form application, where:

  • A button is used to open a file dialog for selecting a PDF file.
  • A second button triggers the signing of the selected PDF using a predefined `.pfx` file and password.
  • Labels are updated to confirm the completion of the signing process.

4. Review Document Signature

As you can see in the output below, as long as a PDF file is selected and the Import Signature button is clicked, it successfully digitally signs the document. With IronPDF, it only took a single line of code.

x509certificate2 Add Digital Signature to PDF Programmatically, Figure 1:


x509certificate2 Add Digital Signature to PDF Programmatically, Figure 2:


IronPDF is the perfect tool for PDF-related tasks using C#. IronPDF offers developers methods to render PDF documents into images and extract text and content from a PDF. Additionally, IronPDF is capable of rendering charts in PDFs, adding barcodes using the IronBarcode library, enhancing security with passwords, watermarking, and even handling PDF forms programmatically.


Library Quick Access

Documentation related to Library Quick Access

API Reference

Read the IronPDF documentation and full list of functions.

API Reference

Preguntas Frecuentes

¿Cómo puedo agregar una firma digital a un PDF programáticamente en C#?

Para agregar una firma digital a un PDF en C#, usa IronPDF. Primero, instala IronPDF a través de NuGet o descarga el DLL. Luego, utiliza la clase `x509certificate2` para manejar el certificado y la clase `PdfSignature` para aplicar la firma con un archivo `.pfx` y contraseña utilizando el método `SignPdfFile`.

¿Cuál es la importancia de una firma digital en PDFs?

Las firmas digitales en PDFs proporcionan una capa adicional de protección al verificar la identidad del remitente, similar a un pasaporte electrónico. Aseguran la autenticidad e integridad del documento, evitando modificaciones no autorizadas.

¿Es fácil firmar un PDF usando IronPDF?

Sí, firmar un PDF con IronPDF es sencillo. Requiere solo una línea de código usando el método `SignPdfFile`, lo que facilita la incorporación de firmas digitales en tus archivos PDF.

¿Qué papel juega la clase `x509certificate2` en las firmas digitales?

La clase `x509certificate2` en C# se utiliza para gestionar y manejar certificados X.509, que son cruciales para aplicar firmas digitales. Proporciona información sobre el certificado y se utiliza junto a IronPDF para firmar PDFs.

¿Puedo probar IronPDF gratis antes de comprarlo?

Sí, IronPDF se puede usar gratis durante el desarrollo para probar sus características, incluida la firma digital, antes de tomar una decisión de compra.

¿Qué formato de archivo debo usar para transferir un certificado con una clave privada para la firma digital?

Para transferir un certificado con una clave privada, utiliza el formato de archivo `.pfx`, conocido como Formato de Intercambio de Información Personal.

¿Cómo instalo IronPDF en mi proyecto de Visual Studio?

Instale IronPDF en su proyecto de Visual Studio descargando la DLL directamente o usando NuGet con el comando `nuget install IronPdf`.

¿Cuál es el propósito del método `SignPdfFile`?

El método `SignPdfFile` en IronPDF se utiliza para firmar digitalmente un archivo PDF con un certificado y clave privada especificados, mejorando la seguridad del documento.

¿IronPDF es totalmente compatible con .NET 10 al agregar firmas digitales?

Sí. IronPDF es totalmente compatible con .NET 10 y todas las funciones de firma digital, incluidos los métodos `PdfSignature`, `x509certificate2`, `Sign` y `SignPdfFile`, funcionan sin necesidad de configuración adicional. IronPDF es compatible con .NET 10 y muchas otras versiones de .NET (p. ej., .NET 9, 8, 7, etc.).

¿Existen requisitos previos o requisitos de versión .NET antes de utilizar las funciones de firma digital de IronPDF?

Las funciones de firma digital de IronPDF requieren .NET versión 5 o superior, incluyendo .NET 10, .NET 9, .NET Core y .NET Standard. Para frameworks anteriores o versiones no compatibles, es posible que la biblioteca no ofrezca compatibilidad total o requiera dependencias adicionales.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más