Password protected PDF using C#

后端 未结 3 1542
陌清茗
陌清茗 2020-12-03 03:40

I am creating a pdf document using C# code in my process. I need to protect the docuemnt with some standard password like \"123456\" or some account number. I need to do th

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-03 04:02

    It would be very difficult to do this without using a PDF library. Basically, you'll need to develop such library yourselves.

    With help of a PDF library everything is much simpler. Here is a sample that shows how a document can easily be protected using Docotic.Pdf library:

    public static void protectWithPassword(string input, string output)
    {
        using (PdfDocument doc = new PdfDocument(input))
        {
            // set owner password (a password required to change permissions)
            doc.OwnerPassword = "pass";
    
            // set empty user password (this will allow anyone to
            // view document without need to enter password)
            doc.UserPassword = "";
    
            // setup encryption algorithm
            doc.Encryption = PdfEncryptionAlgorithm.Aes128Bit;
    
            // [optionally] setup permissions
            doc.Permissions.CopyContents = false;
            doc.Permissions.ExtractContents = false;
    
            doc.Save(output);
        }
    }
    

    Disclaimer: I work for the vendor of the library.

提交回复
热议问题