Ionic4 打印媒体查询可滚动离子内容

vic*_*tcu 5 media-queries ionic4

非常简单的问题。在我的 Ionic4 应用程序中具有可滚动的离子内容。我希望能够通过应用@media only print样式来优雅地打印它。我快到了,但我有一个大问题。我无法让垂直滚动条消失以进行打印。此外,我只打印一页,仅包含打印该页面时看到的内容。我在网上搜索了解决方案,并在 Ionic3 及更早版本的上下文中遇到并尝试了各种建议,但我还没有找到 Ionic4 的灵丹妙药。有没有人遇到过并深入了解过这个问题?

*** 更新 ***

这似乎适用于https://github.com/ionic-team/ionic-framework/issues/19886#issuecomment-1531073496的 Ionic 7 。添加到全局 scss。

@media print {
  .ion-page {
    display: initial !important;
    position: initial !important;
  }
  body {
    position: initial !important;
    max-height: initial !important;
    overflow: auto !important;
  }
  ion-router-outlet {
    overflow: auto !important;
    contain: none !important;
    position: initial !important;
  }
  ion-content {
    --offset-bottom: unset !important;
    display: unset !important;;
    position: unset !important;;
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 2

我已经尝试在 Ionic 4 中打印内容。我遵循打印多页的一些步骤。

  • 删除任何flex-box样式列表。它们只是不会按照您希望的方式页打印,尽管如果内容适合一页,它们对我来说效果很好
  • 对于要按页面分隔的项目,最好是样式项目display: block;,以便在打印样式表中您可以使用其中的分页属性之一
  • 例如,在包含列表的项目上ion-content,请确保max-height从其或其任何祖先元素或子元素中删除任何属性,并overflow: scroll从这些元素中删除 ,以便允许您的内容从一个页面转到另一个页面。例如,在我的打印样式表上(由于保密协议而无法分享),我有很多overflow-y: visibleon 元素只是为了确保它显示。如果您发现某个元素破坏了您的 html,那么它应该是实验的主要目标。
  • 您可以在开发工具中模拟打印,我发现它很有用,这对于迭代很有用,这是一个链接

其他一些可能有帮助的事情,但我不确定,因为我在浏览器上做了很多测试,并且只模糊地记得 css 属性的影响是使主体具有静态位置,以及对主体contain: none说浏览器应该正常呈现,这里没有更多解释

我不知道您的用例的具体情况,但如果您不介意放弃本机打印按钮,而只是为用户提供一个按钮来单击以触发打印,那么这将更易于管理,因为您不必考虑要打印的特定元素周围的所有脚手架(离子路由器、离子页面和所有祖先)

如果你这样做了,那么你可以将你想要打印的所有项目放入一个div带有 idprintSection或你喜欢的项目中,然后负责该页面的 javascript 可以创建你自己的打印函数。在我的示例中,我将使用 Angular,如果您不使用它,则执行您需要的任何 DOM 选择,以从模板中获取本机 html。

@Component({ ... })
export class Page {
  // select the item holding your print content by `#property` you gave it
  @ViewChild('printSection', { read: ElementRef }) printSection: ElementRef;

  ...

  customPrint() {
    const printContent = this.printSection.nativeElement;
    const WindowPrt = window.open('', '', 'left=0,top=0,width=900,height=900,toolbar=0,scrollbars=0,status=0');
    WindowPrt.document.write(printContent.innerHTML); // pass in the native html you got
    /**
     * you should probably use an observable instead of an interval for this, 
     * but this is just to illustrate a bug where the print would be fired before
     * all the content was written
     */
    const interval = setInterval(
      () => {
        if (document.readyState === 'complete') {
          WindowPrt.document.close();
          WindowPrt.focus();
          WindowPrt.print();
          clearInterval(interval);
        }
      },
      200);
  }
} 
Run Code Online (Sandbox Code Playgroud)