简体   繁体   English

使用密码c#保护pdf文件

[英]protect pdf file with password c#

        connetionString = ConfigurationManager.ConnectionStrings["conString"].ToString();
        sql = "select Id,employeeName,employeePosition from Employee";
        connection = new SqlConnection(connetionString);
        connection.Open();
        command = new SqlCommand(sql, connection);
        adapter.SelectCommand = command;
        adapter.Fill(ds);
        connection.Close();

        PdfDocument pdf = new PdfDocument();
        pdf.Info.Title = "Database to PDF";
        PdfPage pdfPage = pdf.AddPage();
        XGraphics graph = XGraphics.FromPdfPage(pdfPage);
        XFont font = new XFont("Verdana", 20, XFontStyle.Regular);

        yPoint = yPoint + 100;

        for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
        {
            pubname = ds.Tables[0].Rows[i].ItemArray[0].ToString();
            city = ds.Tables[0].Rows[i].ItemArray[1].ToString();
            state = ds.Tables[0].Rows[i].ItemArray[2].ToString();

            graph.DrawString(pubname, font, XBrushes.Black, new XRect(40, yPoint, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft);

            graph.DrawString(city, font, XBrushes.Black, new XRect(120, yPoint, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft);

            graph.DrawString(state, font, XBrushes.Black, new XRect(400, yPoint, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft);

            yPoint = yPoint + 40;
        }


        string pdfFilename = "dbtopdf.pdf";
        pdf.Save(pdfFilename);

I created a pdf file directly from the database. 我直接从数据库创建了一个pdf文件。 I need to protect the pdf file with the password. 我需要用密码保护pdf文件。

using (MemoryStream ObjememoryStream = new MemoryStream())
        {
            PdfWriter.GetInstance(pdfDoc, ObjememoryStream);
            pdfDoc.Open();
            htmlworker.Parse(sr);
            pdfDoc.Close();
            byte[] Filebytes = ObjememoryStream.ToArray();
            ObjememoryStream.Close();
            using (MemoryStream inputData = new MemoryStream(Filebytes))
            {
                using (MemoryStream outputData = new MemoryStream())
                {
                    string PDFFileword = txtPassword.Text;//you can also generate Dynamic word  
                    PdfReader reader = new PdfReader(inputData);
                    PdfEncryptor.Encrypt(reader, outputData, true, PDFFileword, PDFFileword, PdfWriter.ALLOW_SCREENREADERS);
                    Filebytes = outputData.ToArray();
                    File.WriteAllBytes(destPath, Filebytes);
                    //Response.ContentType = "application/pdf";
                    //Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
                    //Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    //Response.BinaryWrite(Filebytes);
                    //Response.End();
                    GridView1.AllowPaging = true;
                    GridView1.DataBind();
                }
            }
        }

I managed to protect the pdf file with password with the code above, but it only works with the pdf file which is generate from a gridview. 我设法使用上面的代码用密码保护pdf文件,但它只适用于从gridview生成的pdf文件。 Can someone show me how to protect the pdf file with password which generated with first method by something similar to my second code? 有人可以告诉我如何用第一种方法生成的密码来保护pdf文件,类似于我的第二个代码吗?

在SecuritySettings中设置用户密码

    pdf.SecuritySettings.UserPassword = "your password";

In web.config , add key element add paths and I have Date of Birth as a PDF Password . web.configadd key元素添加路径,我将Date of Birth作为PDF Password You can use anything in place of it. 你可以用anything代替它。

<add key="Inputfile" value=”Path of pdf file where it is getting saved…”>
        <add key="Outputfile" value=”Path of pdf file where it has to be saved after getting password protected…”>   


        protected void passwordProtect(DateTime DateofBirth)
                {
                    string yourpdf = ConfigurationManager.AppSettings["Inputfile"];
                    string pdfWithPasswordA = ConfigurationManager.AppSettings["Outputfile"];
                    string InputFileA = yourpdf;
                    string OutputFileA = pdfWithPasswordA;

                    using (Stream input = new FileStream(InputFileA, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        using (Stream output = new FileStream(OutputFileA, FileMode.Create, FileAccess.Write, FileShare.None))
                        {
                            PdfReader reader = new PdfReader(input);
                            PdfEncryptor.Encrypt(reader, output, true, DateofBirth.ToString("yyyyMMdd"), "secret", PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_COPY);
                        }
                    } 



            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM