在浏览器中打印图像

时间:2016-03-03 06:53:18

标签: javascript jquery html css printing

我正在print页面中尝试html张图片。说100张图片,每页一张。 我在html内容中添加了图像,并将其添加到iframe标记中并尝试打印。图像在底部被截断,其余部分移动到下一页。我该如何克服这个问题?

我附上了一个简单的代码段来打印简单的图像。请尝试运行代码段并建议我在所有浏览器的单个页面中打印图像的解决方案(即ff和chrome)

<!DOCTYPE html>
<html moznomarginboxes mozdisallowselectionprint>

<head>
 
</head>

<body>

  <button id="btn1" type="button" onclick="myFunction()">Print</button>
  <br/>
  <img src="http://i.stack.imgur.com/bFvfE.jpg" style="border:1px solid" />

</body>

<script>
  function myFunction() {
    //window.print();
    var iframe = document.createElement('iframe');
    iframe.name = "printFrame";
    iframe.style.position = "absolute";
    iframe.style.top = "-100000000px";
    document.body.appendChild(iframe);
    var frameDoc = iframe.contentWindow ? iframe.contentWindow : iframe.contentDocument.document ? iframe.contentDocument.document : iframe.contentDocument;
    frameDoc.document.open();
    frameDoc.document.write('<html moznomarginboxes mozdisallowselectionprint><head><style>@media print {div { page-break-inside: avoid;} @page{margin:0;} body{margin:0;}}</style></head><body><center>');
    frameDoc.document.write('<div><img src="http://i.stack.imgur.com/bFvfE.jpg" style="border:1px solid;margin:0px;display:block"/></div><br/>');
    frameDoc.document.write('</center></body></html>');
    frameDoc.document.close();
    setTimeout(function() {
      window.frames["printFrame"].focus();
      window.frames["printFrame"].print();
      document.body.removeChild(iframe);
    }, 500);
  }
</script>

</html>

2 个答案:

答案 0 :(得分:1)

为文档指定一个高度,然后将图像设置为填充父元素(html,body)允许的空间:

<强> CSS

html, body { height: 100%; }
img { height: 100%; width: auto; }

这似乎可以解决所有问题:

html, body { height: 100%; }
img { height: 100%; width: auto; display: block; }
@media print { 
    body { margin: 0; }
    img { box-sizing: border-box; }
    br, button { display: none; }
}

答案 1 :(得分:-1)

您必须编写@media查询来打印您的html或网页。我正在使用@media查询打印网页。见下面的链接。

http://www.richmondau.com/

你得到了解决方案。