在浏览器中打印图像

Printing images in browsers

本文关键字:图像 打印 浏览器      更新时间:2023-09-26

我正在尝试html页面中print图像。 比如说大约 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="https://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="https://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>

为文档指定一个高度,然后将图像设置为填充父元素(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; }
}

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

http://www.richmondau.com/

您得到了解决方案。