@Media打印样式未应用

时间:2018-07-03 07:38:12

标签: javascript html css sass

Stackblitz:https://stackblitz.com/edit/angular-xvdy1q
我要打印特定的div

<div id="forPrint" (click)="onPrint('23')">
  <div id="printable">
    <div class="box">

    </div>
  </div>
</div>

JavaScript代码:

onPrint(url) {
  this.mode = 'print';
  const mywindow = window.open('', 'PRINT', 'height=400,width=600');

  mywindow.document.write(`<html><head><title>${document.title}</title>`);
  mywindow.document.write('</head><body >');
  mywindow.document.write(`<h1> www.${url}</h1>`);
  mywindow.document.write(document.getElementById('forPrint').innerHTML);
  mywindow.document.write('</body></html>');
  mywindow.document.close(); // necessary for IE >= 10
  mywindow.focus(); // necessary for IE >= 10*/

  mywindow.print();
  mywindow.close();

  return true;
}

样式:

@media print {
  html,
  body {
    height: 100% !important;
    width: 100%!important;
    h1 {
      color: #1c7430;
    }
  }
  #printable {
    display: flex!important;
    justify-content: center!important;
    align-items: center!important;
    height: 100% !important;
    width: 700px!important;
  }
  .box {
    width: 100px!important;
    height: 100px!important;
    background: green!important;
  }
}

但是在打开打印对话框后,该框未显示。因此,没有应用任何样式,例如h1.box。有什么问题预先感谢。

2 个答案:

答案 0 :(得分:3)

您需要以某种方式将CSS注入新页面。

在这里,我创建一个style标签并直接添加CSS。您也可以链接到样式表:

function onPrint(url) {
  this.mode = 'print';
  const mywindow = window.open('', 'PRINT', 'height=400,width=600');

  const styles = `html,
      body {
        height: 100% !important;
        width: 100%!important;
      }
      h1 {
          color: #1c7430;
      }
      #printable {
        display: flex!important;
        justify-content: center!important;
        align-items: center!important;
        height: 100% !important;
        width: 700px!important;
      }
      .box {
        width: 100px!important;
        height: 100px!important;
        background: green!important;
      }`

  mywindow.document.write(`<html><head><title>${document.title}</title>`);
  mywindow.document.write(`<style>${styles}</style>`)
  mywindow.document.write('</head><body >');
  mywindow.document.write(`<h1> www.${url}</h1>`);
  mywindow.document.write(document.getElementById('forPrint').innerHTML);
  mywindow.document.write('</body></html>');
  mywindow.document.close(); // necessary for IE >= 10
  mywindow.focus(); // necessary for IE >= 10*/

  mywindow.print();
  mywindow.close();

  return true;
}

JSFiddle Demo

答案 1 :(得分:1)

打印时需要启用背景色和图像。您可以在Chrome的高级设置下的打印对话框中执行此操作。

您还可以应用-webkit-print-color-adjust: exact;属性来更改背景打印行为。

相关问题