Using javascript to print images

前端 未结 9 865
清歌不尽
清歌不尽 2020-12-02 17:40

I would like to know if it\'s possible to use javascript to open a popup window containing an image, and at the same time have the print dialog show. Once someone clicks on

相关标签:
9条回答
  • 2020-12-02 18:11

    I wrote a coffee script function that does that (but without opening a new window):

    @print_img = (url) ->
    $children = $('body').children().hide()
    $img = $('<img>', src: url)
    $img.appendTo('body')
    
    $img.on 'load', ->
      window.print()
      $(this).remove()
      $children.show()
    

    Or if you prefer in javascript:

    this.print_img = function(url) {
      var $children, $img;
      $children = $('body').children().hide();
      $img = $('<img>', {
        src: url
      });
      $img.appendTo('body');
    
      $img.on('load', function() {
        window.print();
        $(this).remove();
        $children.show();
      });
    };
    

    This function makes sure that the elements on the body are hidden and not redrawn into the DOM. It also makes sure that the image is loaded before calling print (if the image is too large and the internet connection is slow, it may take a while to load the img, if you call print too soon, it will print an empty page)

    0 讨论(0)
  • 2020-12-02 18:15
    popup = window.open();
    popup.document.write("imagehtml");
    popup.focus(); //required for IE
    popup.print();
    
    0 讨论(0)
  • 2020-12-02 18:25

    This code will open YOUR_IMAGE_URL in a popup window, show print dialog and close popup window after print.

    var popup;
    
    function closePrint () {
        if ( popup ) {
            popup.close();
        }
    }
    
    popup = window.open( YOUR_IMAGE_URL );
    popup.onbeforeunload = closePrint;
    popup.onafterprint = closePrint;
    popup.focus(); // Required for IE
    popup.print();
    

    MDN Reference code

    0 讨论(0)
提交回复
热议问题