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);
我直接从数据库创建了一个pdf文件。我需要用密码保护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();
}
}
}
我设法用上面的代码用密码保护PDF文件,但它只适用于从网格视图生成的PDF文件。有人能告诉我如何用类似于我的第二个代码用第一种方法生成的密码保护PDF文件吗?
2条答案
按热度按时间o2g1uqev1#
在
SecuritySettings
中设置用户密码hmmo2u0o2#
在
web.config
中,add key
元素添加路径,并且我有Date of Birth
作为PDF Password
。您可以使用anything
来代替它。