Cifrado y descifrado de PDF

Este ejemplo de código muestra cómo modificar metadatos, hacer que el PDF sea de sólo lectura, configurar permisos y cambiar la contraseña de cifrado del documento utilizando la potente biblioteca PDF .NET de C# de IronPDF.

Para empezar, importe un documento PDF existente utilizando el método open. Este método se puede utilizar para abrir documentos protegidos con contraseña especificando la contraseña como el segundo parámetro, ofreciendo un manejo robusto de archivos protegidos.

Para establecer nueva información de metadatos, comience creando un diccionario y agregue pares clave-valor para los metadatos, como el autor y las palabras clave. Utilice el método overrideMetadata en IronPDF para aplicar eficazmente los nuevos metadatos al documento PDF.

A continuación, elimine las contraseñas y el cifrado utilizando el método removePasswordsAndEncryption proporcionado por IronPDF, y configure el PDF para que sea de sólo lectura estableciendo una nueva contraseña con el método makePdfDocumentReadOnly, garantizando la integridad y seguridad del documento.

Los permisos para el documento PDF se configuran mediante un objeto denominado "permissions", que especifica si se permiten o no determinadas acciones, como anotaciones, extracción de contenido, cumplimentación de formularios e impresión. Pase el objeto permissions al método setPermission para controlar con precisión las características de accesibilidad del documento.

Finalmente, cambie o establezca la contraseña de cifrado del documento a "mi-contraseña" y guarde el PDF modificado como "secured.pdf", demostrando la capacidad de IronPDF para la gestión segura de documentos en el desarrollo de aplicaciones.

// Import the necessary namespace.
using IronPdf;

class PdfExample
{
    static void Main()
    {
        // Open an existing PDF document. If the document is password protected, provide the password.
        var pdf = IronPdf.PdfDocument.FromFile("existing.pdf", "document-password");

        // Initialize a dictionary to store metadata key-value pairs.
        var newMetadata = new Dictionary<string, string>
        {
            { "Author", "New Author" },
            { "Keywords", "PDF, Documentation, Example" }
        };

        // Apply the new metadata to the PDF document.
        pdf.OverrideMetadata(newMetadata);

        // Remove any existing passwords and encryption.
        pdf.RemovePasswordsAndEncryption();

        // Make the PDF document read-only by setting a read-only password.
        pdf.MakePdfDocumentReadOnly("read-only-password");

        // Define and set the permissions for the PDF document.
        var permissions = new PdfPermissions
        {
            AllowAnnotations = false,
            AllowContentExtraction = false,
            AllowFormFilling = true,
            AllowPrinting = false,
            AllowDocumentAssembly = false
        };
        pdf.SetPermissions(permissions);

        // Change the document encryption password.
        pdf.SaveAs("secured.pdf", "my-password"); // Save the modified PDF with a new security password.
    }
}
// Import the necessary namespace.
using IronPdf;

class PdfExample
{
    static void Main()
    {
        // Open an existing PDF document. If the document is password protected, provide the password.
        var pdf = IronPdf.PdfDocument.FromFile("existing.pdf", "document-password");

        // Initialize a dictionary to store metadata key-value pairs.
        var newMetadata = new Dictionary<string, string>
        {
            { "Author", "New Author" },
            { "Keywords", "PDF, Documentation, Example" }
        };

        // Apply the new metadata to the PDF document.
        pdf.OverrideMetadata(newMetadata);

        // Remove any existing passwords and encryption.
        pdf.RemovePasswordsAndEncryption();

        // Make the PDF document read-only by setting a read-only password.
        pdf.MakePdfDocumentReadOnly("read-only-password");

        // Define and set the permissions for the PDF document.
        var permissions = new PdfPermissions
        {
            AllowAnnotations = false,
            AllowContentExtraction = false,
            AllowFormFilling = true,
            AllowPrinting = false,
            AllowDocumentAssembly = false
        };
        pdf.SetPermissions(permissions);

        // Change the document encryption password.
        pdf.SaveAs("secured.pdf", "my-password"); // Save the modified PDF with a new security password.
    }
}
' Import the necessary namespace.
Imports IronPdf

Friend Class PdfExample
	Shared Sub Main()
		' Open an existing PDF document. If the document is password protected, provide the password.
		Dim pdf = IronPdf.PdfDocument.FromFile("existing.pdf", "document-password")

		' Initialize a dictionary to store metadata key-value pairs.
		Dim newMetadata = New Dictionary(Of String, String) From {
			{"Author", "New Author"},
			{"Keywords", "PDF, Documentation, Example"}
		}

		' Apply the new metadata to the PDF document.
		pdf.OverrideMetadata(newMetadata)

		' Remove any existing passwords and encryption.
		pdf.RemovePasswordsAndEncryption()

		' Make the PDF document read-only by setting a read-only password.
		pdf.MakePdfDocumentReadOnly("read-only-password")

		' Define and set the permissions for the PDF document.
		Dim permissions = New PdfPermissions With {
			.AllowAnnotations = False,
			.AllowContentExtraction = False,
			.AllowFormFilling = True,
			.AllowPrinting = False,
			.AllowDocumentAssembly = False
		}
		pdf.SetPermissions(permissions)

		' Change the document encryption password.
		pdf.SaveAs("secured.pdf", "my-password") ' Save the modified PDF with a new security password.
	End Sub
End Class
$vbLabelText   $csharpLabel

Explorar el ejemplo de código de cifrado y descifrado de PDF

¿Listo para empezar?
Versión: 2025.12 recién lanzado