如何在iPad上使用Javascript打印iFrame的内容

How to print the contents of an iFrame using Javascript on iPad?

本文关键字:iFrame 打印 Javascript iPad      更新时间:2023-09-26

打印iFrame的内容似乎已经成为跨浏览器解决的一个具有挑战性的问题。在测试了很多方法(其中一些也可以在这个网站上找到)之后,我目前的方法似乎可以很好地跨浏览器工作,看起来像这样:

function printUrl( elem, url ) {
    $( '#' + elem ).append( "<iframe style='border: none; width: 0; height: 0; margin: 0; padding: 0;' src='" + url + "' id='printFrame'></iframe>" );
    $( '#printFrame' ).load( function() {
        var w = ( this.contentWindow || this.contentDocument.defaultView );
        w.focus();
        w.print();
    } );
}

在使用iPad时,这段代码只有一个小问题。iPad打印包含iFrame的页面,而不是iFrame的内容。但是,Mac上的Safari可以正确打印iFrame的内容。

有没有人已经解决了这个问题,并能够在iPad上打印iFrame的内容?

好吧,首先。我没有解决问题。我创造了一种变通方法,它实际上可以达到我想要的效果。

因为iPad/iPhone只是打印父页面,所以我将整个主体包装在一个新的div中,然后附加iFrame和一些样式表,以确保打印的文档只包含iFrame:

function printUrl( url ) {
    $newBody = "<div class='do_not_print_this'>"
                + $( 'body' ).html()
                + "</div>"
                + "<iframe style='border: none; 0; width: 100%; margin: 0; padding: 0;' src='" + url + "' class='printFrame'></iframe>"
                + "<style type='text/css' media='all'>.printFrame { position: absolute; top: -9999999px; left: -99999999px; }</style>"
                + "<style type='text/css' media='print'>.do_not_print_this { display: none; } .printFrame { top: 0; left: 0; }</style>";
    $( 'body' ).html( $newBody );
    $( '.printFrame' ).load( function() {
        var w = ( this.contentWindow || this.contentDocument.defaultView );
        w.focus();
        w.print();
    } );
}

在正常视图中为浏览器隐藏iframe使用绝对定位,使用display on none或visibility hidden会在最终打印中引入奇怪的行为。

是的,它很丑。然而,这是目前我能想到的唯一可行的选择。如果你们谁有更好的解决方案,请告诉我。

这是一个可以在常绿浏览器和当前版本的iOS上跨平台工作的函数:

function printElement(divid, title)
{   
  var contents = document.getElementById(divid).innerHTML;
  var frame1 = document.createElement('iframe');
  frame1.name = "frame1";
  frame1.style.position = "absolute";
  frame1.style.top = "-1000000px";
  document.body.appendChild(frame1);
  var frameDoc = frame1.contentWindow ? frame1.contentWindow : frame1.contentDocument.document ? frame1.contentDocument.document : frame1.contentDocument;
  frameDoc.document.open();
  frameDoc.document.write('<html><head><title>' + title + '</title>');
  frameDoc.document.write('</head><body style="font-family: Arial, Helvetica, sans; font-size: 14px; line-height: 20px">');
  frameDoc.document.write('<h1>' + title + '</h1>');
  frameDoc.document.write(contents);
  frameDoc.document.write('</body></html>');
  frameDoc.document.close();
  setTimeout(function () {
    window.frames["frame1"].focus();
    window.frames["frame1"].print();
  }, 500);
  //Remove the iframe after a delay of 1.5 seconds
  //(the delay is required for this to work on iPads)
  setTimeout(function () {
     document.body.removeChild(frame1);
  }, 1500);
  return false;
}

这是基于这个答案进行了轻微修改(重要的是,document.body.removeChild(frame1);行必须删除,以便在iOS上打印)