Using javascript to print images

前端 未结 9 938
清歌不尽
清歌不尽 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 = $('', 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 = $('', {
        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)

提交回复
热议问题