繁体   English   中英

如何将PDF写入asp.net页面?

[英]how can I do write a PDF to a asp.net page?

我正在尝试获取网站上下文中的PDF页面,以在用户指定时显示。 我有以下代码:

    if (context.User.Identity.IsAuthenticated)
    {
        string SampleURL = context.Request.CurrentExecutionFilePath; //CurrentExecutionFilePath;

        context.Response.Buffer = true;
        context.Response.Clear();
        using (FileStream fs = new FileStream(SampleURL,FileMode.Open)) //System.IO.File.OpenRead(path))
        {
            int length = (int)fs.Length;
            byte[] buffer;

            using (BinaryReader br = new BinaryReader(fs))
            {
                buffer = br.ReadBytes(length);
            }

            context.Response.Clear();
            context.Response.Buffer = true;
            context.Response.ContentType = "application/pdf";
            context.Response.BinaryWrite(buffer);
            context.Response.End();
        }
    }
    else
    {
        context.Response.Redirect(
           "~/Error/invalid_access.aspx");
    }

唯一的问题是我无法使PATH正常工作。 如果要直接通过URL调用PDF,它将为http://www.abc.com/reports/sample.pdf,但我无法回到该位置。 我实现了一个HTTPHandler来防止某人访问URL,但是现在我需要将该文件流回浏览器并编写。

有想法,意见或建议吗?

编辑:这是我无法获得相对URL指向正确位置的PATH。 context.Request.CurrentExecutionFilePath给了我“ /www.abc.com/sample_reports/sample.pdf”,但我似乎无法将其打开或读取

路径是什么意思? 文件名? 您可以使用Content-Disposition标头执行此操作。

Response.Addheader "Content-Disposition", "attachment;Filename=WhateverName.pdf"

您必须从本地服务器打开它。 如果它位于您的服务器上,则可以执行

FileStream fs = new FileStream(Server.MapPath("/example.pdf"),FileMode.Open)

如果要从URL加载,则必须先下载PDF。

   WebClient client = new WebClient ();

    // Add a user agent header in case the 
    // requested URI contains a query.

    client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

    Stream data = client.OpenRead (args[0]);
    StreamReader reader = new StreamReader (data);
    string s = reader.ReadToEnd ();` 

我会改变几件事

首先,如果磁盘上有文件,我可能会考虑将文件读取切换为更简单的内容

byte[] buffer = File.ReadAllBytes( path );

现在就上下文

context.Response.Clear();
context.Response.ClearHeaders();
context.Response.Buffer = true;
context.Response.ContentType = "application/pdf";
context.Response.AddHeader( "content-disposition","attachment; filename=file.pdf" );
context.Response.AddHeader("Content-Length", buffer .Length.ToString() );
context.Response.BinaryWrite(buffer);
context.Response.Close();
context.Response.End();
context.Response.Flush();

上面的代码过度杀伤力吗? 可能,但我发现围绕过大杀伤力运行的所有不同浏览器都是值得的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM