문제

iframe 컨텐츠를 인쇄하려고합니다.

contentWindow.focus();
contentWindow.print();

이 코드는 IE, Firefox 및 Safari에서 작동합니다. 그러나 크롬과 오페라에서는 작동하지 않습니다. 이 브라우저는 전체 페이지를 인쇄합니다.

이 주제를 사용하려고했습니다 Safari/Chrome의 JavaScript에서 iframe을 어떻게 인쇄합니까?. 그러나 그것은 나를 도와주지 않았다.

누군가 나를 도울 수 있습니까?

도움이 되었습니까?

해결책

이것은 오페라에서 알려진 버그입니다. 해결 방법에 대한 위의 아이디어 외에도 다음과 같은 것을 가지고 놀 수 있습니다.

    var clone=document.documentElement.cloneNode(true)
    var win=window.open('about:blank');
    win.document.replaceChild(clone, win.document.documentElement);
    win.print();

이것을 테스트하지는 않았지만 서버에서 두 번째로 컨텐츠를로드하거나 인쇄하려는 DOM 수정을 잃지 않고도 팝업 창에 페이지 사본을 작성하고 인쇄해야합니다.

다른 팁

내가 이해했듯이 새 창을 열지 않고 iframe 인쇄를 구현하는 것은 불가능합니다.

내 인쇄 기능 :

if ($.browser.opera || (/chrome/.test(navigator.userAgent.toLowerCase()))) {
  var href = contentWindow.location.href;
  href = href.indexOf("?") > -1 ? href + "&print=1" : href + "?print=1";
  var printWindow = window.open(href, "printWindow", "scrollbars=yes");
  printWindow.focus();
}
else {
  contentWindow.focus();
  contentWindow.print();
}

또한 신체 끝에 다음 코드를 추가했습니다 (print == 1) :

<script type='text/javascript'>
  function invokePrint() {
    if (document.readyState && document.readyState!='complete')
      setTimeout(function() { invokePrint(); }, 50);
    else if (document.body && document.body.innerHTML=='false')
      setTimeout(function() { invokePrint(); }, 50);
    else {
      focus();
      print();
    }
  }
  invokePrint();
</script>

Chrome의 문제를 재현 할 수 없습니다. 그러나 오페라는 실제로 iframe 만 인쇄하려고 할 때 여전히 전체 외부 페이지를 인쇄합니다.

나는 해결 방법을 고안했지만 대부분 작동하지만 100% 실패하지는 않습니다 (오페라는 인쇄를 위해 선을 감싸기 때문에 다른 경우에는 올바른 높이를 계산하는 방법을 모르겠습니다). 즉, 다음 코드는 적어도 합리적으로 작동합니다 (편의를 위해 jQuery 사용) :

if ($.browser.opera) {
    var ifr     = $('#youriframe');
    var ifrbody = ifr.get(0).contentDocument.body;
    var sheet   = $([
        '<style type="text/css" media="print">',
        'body * {',
        ' display: none;',
        '}',
        '#youriframe {',
        ' border: none;',
        ' display: block;',
        ' height: ', ifrbody.scrollHeight, 'px;',
        ' margin: 0px;',
        ' padding: 0px;',
        ' width: ', ifrbody.scrollWidth, 'px;',
        '}',
        '<\/style>'
    ].join(''));
    $('head').append(sheet);
    window.print();
    sheet.remove();
}

도움이 되었기를 바랍니다.

위의 코드를 시도했고 위의 코드를 변경 한 후 다음과 같이 결정적인 코드와 함께 제공되었습니다.

var win=window.open('about:blank');
win.document.write('<html><head></head><body>'); 
win.document.write('<iframe frameBorder="0" align="center" src="'+window.location.href+'" onload="test()" style="width: 619px; height: 482px;"></iframe>'); 
win.document.write('<scr'+'ipt>function test(){window.focus();window.print()}</sc'+'ript></body></html>'); 
win.document.close(); 
if (window.focus) {win.focus()}

이거 한번 해봐

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top