簡體   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