0

I am trying to print a pdf file on the client side using javascript. My javascript code is as below

function doit() {
    var win = document.getElementById("pdf");
    var frm = document.getElementById("pdf").contentWindow;
    frm.print();
    win.print();
}          

The problem is that frm is always null and win does not have a function of print

My pdf element is as below

<iframe id="pdf" name="pdf" src="C:\My_P.pdf"></iframe>

I am calling the function from c# as below

ClientScript.RegisterStartupScript(this.GetType(), "Print", "doit();", true);

Really struggling. Please help

user2837961
  • 1,505
  • 3
  • 27
  • 67
  • I frame is loaded from client and function doit is getting called before it loads the pdf. Are you able to see pdf content in iframe? – Anil Apr 03 '17 at 10:50
  • No. the error is Not allowed to load local resource: file:///C:/_temp/My_P.pdf. I changed the directory thinking I should not load from C: – user2837961 Apr 03 '17 at 11:03

2 Answers2

1

Are you being hampered by same origin policy?

In the past I've used:

window.frames["pdf"].focus();
window.frames["pdf"].print();
Mark Ball
  • 366
  • 2
  • 10
1

The solution to your problem is to call print function after Iframe has been loaded, you may not need to call it from server using RegisterStartupScript

<iframe id="pdf" name="pdf" src="C:\My_P.pdf"
     onload="doit();"></iframe>

Another problem seems to be src path C:\My_P.pdf, I frame is expecting a url to display content. refer Iframe

To mitigate this, create a directory e.g. MyResource within your asp.net project and copy your pdf to this directory and change src="/MyResource/My_P.pdf". Your pdf should be a accessible to browser then only Iframe can load it.

Community
  • 1
  • 1
Anil
  • 3,722
  • 2
  • 24
  • 49
  • Does it mean the file has to be on server side? – user2837961 Apr 03 '17 at 11:34
  • Yes, it can be on any server accessible to your iframe through a URL. – Anil Apr 03 '17 at 11:36
  • The problem is of loading into iframe. I cannot see the pdf. I created a directory in my web application \\WebApplication\bin\Temp and placed the pdf into Temp directory. It does not load it. The print dialog comes up and its displaying blank with my aspx link at the bottom – user2837961 Apr 03 '17 at 11:40
  • Create it under \WebApplication\Temp and not under bin as this is static resource. This should be available to browser like other static resources imgae, js and CSS etc. Try to access it directly on browser like http://localhost/Temp/Mypdf.pdf. Browser will ask to download it. Once you are able to access it via browser then add that path to src attribue of your iframe. – Anil Apr 03 '17 at 12:28