2

I am trying to convert a dynamically generated inline style background-image: url("xyz") into an img src="xyx" that will be opened in a new tab/window for print. I can pull in the url inline image into the img src but when clicking on the print button, 2 pages open up; a page with the url text and the image in the parent window. The pages constantly refresh also.

function to convert the url inline style to an image in an external window for print and the div id with the inline style BG and print button:

function printImg() { 
  var printWin = window.open();
  var content = "<html>";  
  printWin.document.write( src = document.getElementById("lbImage").style.backgroundImage );
  src = src.replace('url(','');
  src = src.replace('")','');
  content += document.write('<img src='+src+'" />');
  printWin.document.close();
  printWin.focus();
  printWin.print(content);
  printWin.close();
}
<div style="background-image: url("mysite.com/images/randomImg.png"); display: block;" id="lbImage">
<a href"#" type="button" onClick="printImg()" target="_blank">Print</a>

I have been plugging at this for a day now and seem to have hit a wall... any suggestions would be greatly appreciated.

2 Answers2

0

The complete fix to remove the url text and print correctly in FireFox, IE, and Chrome:

function printImg() {
  var printWin = window.open();
  var src = src;
  printWin.document.write( src = document.getElementById("lbImage").style.backgroundImage );
  src = src.replace('url(','');
  src = src.replace('example.com','');
  src = src.replace('png)','png');
  src = src.replace('jpg)','jpg');
  src = src.replace(')','');
  printWin.document.write( "<body style='color:#fff;font-size:0px;'>");
  printWin.document.write( "<div style='text-align:center;'>");
  printWin.document.write('<img src='+src+' ' + ' style="width:100%;"/>');
  printWin.document.close();
  printWin.focus();
  printWin.print();
  //printWin.close();  
  //enable this line to close window after print/cancel

}

The color:#fff and font-size:0px clears the url of the image from writing to the top of the page (just remove these if you want that). The width:100% allows the image to fill the window. I disabled the printWin.close() just in case the user does not want to print the image, only Save Image As...

0

I found the solution to this pretty simple when I realized it ! Just change this :

printWin.onload = function() { printWin.print();}
hunters30
  • 501
  • 3
  • 21
  • I can get it to work properly now in IE and FireFox although I am still having the issue with image showing up in Chrome. Chrome is putting an extra )" at the end of the img tag which is why it is not showing up: < img src="myImg)"" > – Bobby Etheredge Sep 02 '15 at 16:35
  • Your suggested solution works but also throws a confirm dialog box to prevent the pop ups in FireFox if using multiple images. Great fix BTW! – Bobby Etheredge Sep 02 '15 at 16:48