c:\ windows \ system32 \ inetsrv \ Test.pdf被拒绝

时间:2011-10-13 19:24:16

标签: asp.net sharepoint pdf-generation itextsharp

我需要使用visual web part-sharepoint 2010在按钮上单击生成pdf文档。 我正在使用开源库http://www.itextpdf.com/。我可以使用项目类型作为Windowns应用程序执行以下代码。但是,当我想按下按钮时,我收到c:\ windows \ system32 \ inetsrv \ Test.pdf'被拒绝。错误。

以下是我正在使用的代码

 public static void Main(string[] args)  --Console Application
    {
        Console.WriteLine("PDF demo");
        Document myDoc = new Document(PageSize.A4.Rotate());
        try
        {
            PdfWriter.GetInstance(myDoc, new FileStream("Salman.pdf", FileMode.Create));
            myDoc.Open();
            myDoc.Add(new Paragraph("First pdf File made by Salman using Itext"));
        }
        catch (DocumentException ex)
        {
            Console.Error.WriteLine(ex.Message);
        }
        myDoc.Close();
    }
}

但我希望在按钮点击事件上也这样做。

    protected void pdfGenerator_OnClick(object sender, EventArgs e)
    {
        Document myDoc = new Document(PageSize.A4.Rotate());
        try
        {
            PdfWriter.GetInstance(myDoc, new FileStream("Salman.pdf", FileMode.Create));---I get an error here
            myDoc.Open();
            myDoc.Add(new Paragraph("First pdf File made by Salman using Itext"));
        }
        catch (DocumentException ex)
        {
            Console.Error.WriteLine(ex.Message);
        }
        myDoc.Close();
    }
}

请帮帮我,我不明白错误的原因。我是第一次打它。

2 个答案:

答案 0 :(得分:3)

问题是您尝试在无权访问的目录中创建PDF。这是因为您没有指定保存路径的目录;这导致它默认与当前工作目录在同一位置。在许多情况下,例如ASP.NET;默认值与进程的位置相同。对于ASP.NET,进程为w3wp.exe并位于c:\ windows \ system32 \ inetsrv中。 w3wp将作为(网络服务或AppPoolIdentity)运行的大多数身份都无权访问该目录。实际上,只有系统管理员才能这样做。

您需要将其保存在该进程具有写入权限的其他位置:

PdfWriter.GetInstance(myDoc, new FileStream("Janaki.pdf", FileMode.Create))

应该是这样的:

PdfWriter.GetInstance(myDoc, new FileStream(@"C:\directoryIcanWriteTo\Janaki.pdf", FileMode.Create))

如果您想将其保存在与网站相同的位置,您可以使用HttpContext.Current.Server.MapPath

    PdfWriter.GetInstance(myDoc, new FileStream(HttpContext.Current.Server.MapPath("~/Janaki.pdf", FileMode.Create))

无论如何,如果没有它们,身份仍然需要对目录的写权限。但你绝对不应该把它们放在inetsrv中。

答案 1 :(得分:0)

只是不要使用需要服务器写权限的“FileStream”。将其替换为MemoryStream,然后在用户的浏览器上刷新其内容。