从Javascript打印图像

Print image from Javascript

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

我有一些图片....每个图像的大小是不同的例如:

img1 = 200 x 1900
img2 = 1800 x 400
img3 = 600 x 800

//HTML

<html>
<body>
    <img src='img1.jpg'>    
    <img src='img2.jpg'>
    <img src='img3.jpg'>
</body>
</html>

//javascript
            var mywindow = window.open('', 'my div');
            mywindow.document.write('<html><head><title>my div</title>');
            mywindow.document.write('</head><body >');
            data = "<img src='img1.jpg'><img src='img2.jpg'><img src='img3.jpg'>";
            mywindow.document.write(data);  // data = all image
            mywindow.document.write('</body></html>');
            mywindow.print();
            mywindow.close();

现在输出的是所有的图像打印,但大小是损坏的如何在A4页打印每个图像并将其打印在A4页

您可以定义打印的CSS规则,并以21cm x 29.7cm为基础。

例如:

<style type="text/css">
@media print {
   img {
      max-width: 18cm;
      max-height: 8cm;
   }
}
</style>

注意,如果你的页面足够简单,你不需要在一个新窗口中建立一个新的布局,因为你可以简单地为@media print@media screen定义不同的规则。

你不能。网站是为屏幕创建的,不是为打印机创建的。

但是,您可以强制web浏览器以与A4相同的像素尺寸显示页面。但是,在渲染时可能会有一些奇怪的地方。

<!DOCTYPE html>
<html>
  <head>
    <style>
    body {
        height: 842px;
        width: 595px;
        /* to centre page on screen*/
        margin-left: auto;
        margin-right: auto;
    }
    </style>
  <head>
  <body>
  </body>
</html>

打印的最佳解决方案是使用pdf,这就是pdf的用途。创建具有相同数据的PDF。在这种情况下,您可以完全控制打印格式。