Display PDF in iframe

泄露秘密 提交于 2019-12-28 06:53:11

问题


I have a solution in place for my site that renders a requested PDF document in a full page using the code below. Now my client wants the document rendered within an iframe. I can't seem to get it to work readily, maybe I am missing something obvious. The first code will properly display the PDF in a new window.

        if (File.Exists(filename))
        {            
            //Set the appropriate ContentType.
            Response.ContentType = "Application/pdf";
            Response.WriteFile(filename);
            Response.End();
        }
        else Response.Write("Error - can not find report");

The iframe code looks like this:

<iframe runat="server" id="iframepdf" height="600" width="800" > </iframe>

I know I am supposed to use the src attribute for the filename, but the problem seems to be that the iframe loads before the Page_Load event fires, so the PDF is not created. Is there something obvious I am missing?


回答1:


Use an ASHX handler. The source code to your getmypdf.ashx.cs handler should look something like this:

using System;
using System.Web;

public class getmypdf : IHttpHandler 
{
  public void ProcessRequest(HttpContext context)
  {
        Response.ContentType = "Application/pdf";
        Response.WriteFile("myfile.pdf");
        Response.End();
  }

  public bool IsReusable 
  {
    get 
    {
      return false;
    }
  }
}

getmypdf.ashx would contain something like this:

<% @ webhandler language="C#" class="getmypdf" %>

And your iframe would look like this:

<iframe runat="server" id="iframepdf" height="600" width="800" src="..../getmypdf.ashx"> </iframe>



回答2:


I actually solved this! The solution was to generate another aspx page (showpdf.aspx) with the code that renders the PDF (the meat of it being the Response... code), then call that code in the iframe. I pass the necessary variable from the source page. Thanks all!

<iframe runat="server" id="iframepdf" height="600" width="800"  >  
</iframe>

        protected void Page_Load(object sender, EventArgs e)
        {
            String encounterID = Request.QueryString["EncounterID"];
            iframepdf.Attributes.Add("src", "showpdf.aspx?EncounterID=" + Request.QueryString["EncounterID"]);
        }



回答3:


You need to set the src="" to a different URL that serves a PDF.




回答4:


Did you try:

window.onload = function() {
     document.getElementById("iframepdf").src = "the URL that loads the PDF"
}


来源:https://stackoverflow.com/questions/11603277/display-pdf-in-iframe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!