@media 打印 { 分页前; page-break-after} 属性在 IONIC(角度)中不起作用

时间:2020-12-29 13:37:37

标签: angular ionic-framework printing page-break page-break-inside

假设它是一个示例代码?


<div id="print-div">
   <p>Lorem ipsum dolor sit amet page 1.</p>
     <ion-label>page break here</ion-label>
   <p>Lorem ipsum dolor sit amet page 2.</p>
</div>

我想打印这部分,第一段在第一页,第二段在下一页。

在 .ts 文件中

printThis(){
   let backup = document.body.innerHTML;
   let divcontent = document.getElementById('print-div').innerHTML;
   document.body.innerHTML = divcontent;
   window.print();
   document.body.innerHTML = backup;
}

在 css 中

@media print {
    ion-label{
        page-break-before: always !important;
    }
}

但这不会在打印时破坏页面。 所有数据都打印在一页中,如果内容大于一页,它仍然打印任何一页的数据。

我试过

page-break-before: always;
page-break-after: always;
break-after: always;

但是什么都没发生。

如果有人帮助我了解如何在 ionic 中使用 page-break 属性。 我会很感激的。

2 个答案:

答案 0 :(得分:2)

问题:

ion-content 组件有一个绝对定位的内部 div。由于 ionic 使用带有 shadow-root 的 web-components 并且定位未公开为 css 变量,因此无法使用 css 样式表设置此样式属性。但是:分页符不适用于绝对定位的元素 w3schools

解决方案:

使用JS操作shadow-root并将定位设置为relative。 github: ionic-print-test

我遇到了同样的问题,并通过使用事件侦听器 onbeforeprintonafterprint 解决了它。这是一个带有 angular 的 ionic 示例,但逻辑可以很容易地重构为 react 或 vue。 ionic-print-test:issue

print.service.ts

import { DOCUMENT } from '@angular/common';
import { Inject, Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class PrintService {
  constructor(@Inject(DOCUMENT) private document: HTMLDocument) {}

  init() {
    window.onbeforeprint = () => this.setPrintStyles(true);
    window.onafterprint = () => this.setPrintStyles(false);
  }

  private setPrintStyles(add: boolean) {
    this.document.querySelectorAll('ion-content').forEach((element) => {
      const scroll = element.shadowRoot.querySelector('.inner-scroll') as HTMLElement;
      if (add) {
        scroll.style.position = 'relative';
      } else {
        scroll.style.removeProperty('position');
      }
    });
  }
}

答案 1 :(得分:0)

对于我添加这项工作。离子 4,角 8

@media print {
    body {
      position: relative !important;
    }
}

https://medium.com/@Idan_Co/angular-print-service-290651c721f9

相关问题