我正在制作一个应用程序,该应用程序应该显示带有密码的PDF。这是我的代码:用iTextSharp打开受密码保护的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。我的代码似乎有什么问题?
编辑: 我删除了抓住看到抛出的异常。
异常详细信息信息: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: }
哪个异常被抛出? – mkl
它不会抛出异常。它执行catch语句,在这种情况下是一个弹出窗口,说'文件未找到!呼叫记录部门进行验证。' – Artemis
嘿@mkl我删除了Catch,以找出抛出什么样的异常它说** System.ArgumentException:PdfReader未打开所有者密码**。 – Artemis