Password protected PDF using C#

后端 未结 3 1546
陌清茗
陌清茗 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:13

    If anyone is looking for a IText7 reference.

        private string password = "@d45235fewf";
        private const string pdfFile = @"C:\Temp\Old.pdf";
        private const string pdfFileOut = @"C:\Temp\New.pdf";
    
    public void DecryptPdf()
    {
            //Set reader properties and password
            ReaderProperties rp = new ReaderProperties();
            rp.SetPassword(new System.Text.UTF8Encoding().GetBytes(password));
    
            //Read the PDF and write to new pdf
            using (PdfReader reader = new PdfReader(pdfFile, rp))
            {
                reader.SetUnethicalReading(true);
                PdfDocument pdf = new PdfDocument(reader, new PdfWriter(pdfFileOut));
                pdf.GetFirstPage(); // Get at the very least the first page
            }               
    } 
    

提交回复
热议问题