Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

c# - Stream PDF to browser?

Could anyone please tell me how could I stream a pdf to a new tab browser? I just have the pdf stream on memory and I want when I click over the link to show the PDF in a new tab or window browser. How could I do that? Thank!!!

I have this link:

<a id="hrefPdf" runat="server" href="#" target="_blank"><asp:Literal ID="PdfName" runat="server"></asp:Literal></a>

In my code behind I have this on the onload event:

                Stream pdf= getPdf
                if (pdf != null)
                {
                    SetLinkPDF(pdf);
                }

    private void SetLinkPDF(IFile pdf)
    {
        hrefPdf.href = "MyPDF to the Browser"
        PdfName.Text = pdf.PdfName;      
    }

Someway I have to process the stream pdf (IFile contains Name, Stream,Metadata, etc of the PDF)

What can I do to proccess this and whe I click show the stream at a new browser?

I have another probelm, is not working the OnClientClick="aspnetForm.target='_blank';" timbck2 suggested me. I have to open the file (image or pdf ) in a new window, what could I do? Is not working this. Thank!

Timbbck2 my asp code is:

<asp:LinkButton runat="server" ID="LinkButtonFile" OnClick="LinkButtonFile_Click" OnClientClick="aspnetForm.target = '_blank';"></asp:LinkButton>

Thanks!!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I've done this from a file on disk - sending the data from a memory stream shouldn't be that much different. You need to supply two pieces of metadata to the browser, in addition to the data itself. First you need to supply the MIME type of the data (in your case it would be application/pdf), then the size of the data in bytes (integer) in a Content-Length header, then send the data itself.

So in summary (taking into account the comments and what I think you're asking, your markup would look like this:

<asp:LinkButton ID="whatever" runat="server" OnClick="lnkButton_Click" 
  OnClientClick="aspnetForm.target='_blank';">your link text</aspnet:LinkButton>

These few lines of C# code in your code behind should do the trick (more or less):

protected void lnkButton_Click(object sender, EventArgs e)
{
    Response.ClearContent();
    Response.ContentType = "application/pdf";
    Response.AddHeader("Content-Disposition", "inline; filename=" + docName);
    Response.AddHeader("Content-Length", docSize.ToString());
    Response.BinaryWrite((byte[])docStream);
    Response.End();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...