Lock pdf from edit

It there a way to set a ddf document to read only?

@abrice

To set a PDF document to read-only and restrict editing, you can use the Aspose.PDF library to apply document privileges. This involves encrypting the PDF with a user and owner password while specifying the desired permissions.

Here’s a code example in C# that demonstrates how to set the document to read-only by forbidding all privileges except for screen reading:

using System;
using Aspose.Pdf;
using Aspose.Pdf.Facades;

namespace Aspose.Pdf.Examples
{
    public class SetPrivileges
    {
        public static void Run()
        {
            // Load the source PDF file
            using (Document document = new Document("input.pdf"))
            {
                // Create a DocumentPrivilege object to set restrictions
                DocumentPrivilege documentPrivilege = DocumentPrivilege.ForbidAll;
                // Allow screen reading
                documentPrivilege.AllowScreenReaders = true;

                // Encrypt the file with user and owner passwords
                document.Encrypt("userPassword", "ownerPassword", documentPrivilege, CryptoAlgorithm.AESx128, false);
                
                // Save the updated document
                document.Save("SetPrivileges_out.pdf");
            }
        }
    }
}

In this example:

  • The DocumentPrivilege.ForbidAll method is used to restrict all actions on the document.
  • The AllowScreenReaders property is set to true, allowing screen reading while preventing other modifications.
  • The document is then saved with the specified permissions.

You can also achieve similar functionality in Java using the following code snippet:

import com.aspose.pdf.CryptoAlgorithm;
import com.aspose.pdf.Document;
import com.aspose.pdf.facades.DocumentPrivilege;

public class SetPrivilegesOnExistingPDFFile {
    public static void main(String[] args) {
        Document document = new Document("inputFile.pdf");
        try {
            DocumentPrivilege documentPrivilege = DocumentPrivilege.getForbidAll();
            documentPrivilege.setAllowScreenReaders(true);
            document.encrypt("userPassword", "ownerPassword", documentPrivilege, CryptoAlgorithm.AESx128, false);
            document.save("outputFile.pdf");
        } finally {
            if (document != null) {
                document.dispose();
            }
        }
    }
}

This Java example follows the same logic as the C# example, ensuring that the PDF is secured against editing while allowing screen reading.

For more detailed information, you can refer to the official documentation on setting privileges for PDF files here.

Feel free to ask if you have any further questions!