admin管理员组

文章数量:1426072

I want to print only the image in a HTML page.

I used

function printImg(){        
    var URL = "image.png";
    var W = window.open(URL);
    W.window.print();
}

But executing the code, whole page prints rather the image. Are there any method to print only the image? Pls guide me.

Thanks.

I want to print only the image in a HTML page.

I used

function printImg(){        
    var URL = "image.png";
    var W = window.open(URL);
    W.window.print();
}

But executing the code, whole page prints rather the image. Are there any method to print only the image? Pls guide me.

Thanks.

Share Improve this question edited Sep 10, 2012 at 7:58 senps asked Sep 10, 2012 at 7:34 senpssenps 5942 gold badges10 silver badges31 bronze badges 5
  • How did you call this function? – Arthur Halma Commented Sep 10, 2012 at 7:38
  • <input type="submit" value="Print" name="printImg" onClick="printImg()"> – senps Commented Sep 10, 2012 at 7:38
  • Try to add return false; at the end of function in this case. – Arthur Halma Commented Sep 10, 2012 at 7:40
  • @Isuru Senanayake: See my answer below with a demo. – Ahsan Khurshid Commented Sep 10, 2012 at 7:49
  • @IsuruSenanayake, This can't be done. You can't modify browser settings (i.e. printer settings) from JavaScript – Alexander Commented Sep 10, 2012 at 8:51
Add a ment  | 

5 Answers 5

Reset to default 1

create one print.css that hide all other unwanted divs except the image

If you heard about CSS Media types then you can achieve your desired task with this technique.

Example:

Define Media Type Print and then add a css class.noprint with a css rule display:none; in your css file like given below:

@media print {
   .noprint{ display: none }
}

And then apply this class on the elements you don't want to print.

SEE AN EXAMPLE

Hope this will help you a lot.

Use

W.print();

instead of

W.window.print();

W.window makes reference to the parent's window of the pop-up.

Besides this you may consider using an empty page with a window.print triggered on load, instead of your current method which is not waiting for the image to be ready.

== EDIT ==

This can't be done. You can't modify browser settings (i.e. printer settings) from JavaScript

Finally I thought of convert my result to PDF format and print using FPDF Library

You can create an image element then append it to the DOM.

function printImg() {
    var img = document.createElement( "img" );
    img.src = "image.png";
    document.body.appendChild( img );
}

本文标签: phpPrint only Image without whole HTML pageStack Overflow