我正在制作一个应该显示带有密码的 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: }