【问题标题】:@media print { page-break-before; page-break-after} property not working in IONIC (angular)@media print { page-break-before; page-break-after} 属性在 IONIC 中不起作用(角度)
【发布时间】:2021-04-06 03:15:58
【问题描述】:

假设它是一个示例代码????


<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 属性。 我会很感激的。

【问题讨论】:

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


    【解决方案1】:

    问题:

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

    解决方案:

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

    我遇到了同样的问题,并通过使用事件监听器onbeforeprintonafterprint 解决了它。这是一个带有角度的离子示例,但逻辑可以很容易地重构为反应或 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');
          }
        });
      }
    }
    

    【讨论】:

    • 您好先生,我已经尝试过这种方法,但同样的问题。也许我做错了什么。请您告诉我,您如何/在哪里调用 window.print() 。就我而言,我将它放在 init() 的第一行或 init() 的最后一行
    • 嗨 Sounak,只需在 AppModule 中导入 PrintService,将其添加到 app.component.ts 的构造函数中,然后在 app.component 中调用 init()。之后注册 EventListeners,你应该可以在任何其他组件中调用 window.print()。
    【解决方案2】:

    为我添加这项工作。离子 4,角度 8

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-22
      • 2014-11-20
      • 2011-03-16
      • 2013-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多