【发布时间】:2023-11-29 14:29:01
【问题描述】:
我正在制作一个应显示带有密码的 PDF 的应用程序。这是我的代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
string filePath = Request.QueryString["filePath"];
if (filePath.ToUpper().EndsWith("PDF"))
{
copyPDF(filePath);
}
}
catch
{
string message = "<script language='Javascript'>alert('File Not Found! Call Records Department for verification. ')</script>";
ScriptManager.RegisterStartupScript(Page, this.GetType(), message, message, false);
}
}
}
public void copyPDF(string filePath)
{
iTextSharp.text.pdf.RandomAccessFileOrArray ra = new iTextSharp.text.pdf.RandomAccessFileOrArray(Server.MapPath(ResolveUrl(filePath)));
if (ra != null)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
byte[] password = System.Text.ASCIIEncoding.ASCII.GetBytes("Secretinfo");
iTextSharp.text.pdf.PdfReader thepdfReader = new iTextSharp.text.pdf.PdfReader(ra, password);
int pages = thepdfReader.NumberOfPages;
iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document();
iTextSharp.text.pdf.PdfCopy pdfCopy = new iTextSharp.text.pdf.PdfCopy(pdfDoc, ms);
pdfDoc.Open();
int i = 0;
while (i < pages)
{
pdfCopy.AddPage(pdfCopy.GetImportedPage(thepdfReader, i + 1));
i += 1;
}
pdfDoc.Close();
Byte[] byteInfo = ms.ToArray();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", byteInfo.Length.ToString());
Response.BinaryWrite(byteInfo);
Response.Flush();
Response.End();
}
}
我的代码在没有密码的情况下打开 pdf 文件没有问题,但即使提供了密码,它也无法使用密码打开 pdf。应用程序改为执行 catch。我的代码似乎有什么问题?
编辑: 我删除了 Catch 以查看抛出的异常。
异常详情:System.ArgumentException:PdfReader 未使用所有者密码打开
它说错误的来源是第 51 行。
Line 49: while (i < pages)
Line 50: {
Line 51: pdfCopy.AddPage(pdfCopy.GetImportedPage(thepdfReader, i + 1));
Line 52: i += 1;
Line 53: }
【问题讨论】:
-
抛出了哪个异常?
-
它不会抛出异常。它执行 catch 语句,在这种情况下是一个弹出窗口,显示“未找到文件!致电记录部门进行验证。'
-
嘿@mkl 我删除了 Catch 以找出引发了什么样的异常它说 System.ArgumentException: PdfReader not opens with owner password。
-
您似乎没有提供正确的密码。
-
可能 PDF 既有用户密码又有所有者密码,而您只提供了用户密码。
标签: c# asp.net pdf passwords itextsharp