【问题标题】:How to properly set print orientation in Angular application?如何在 Angular 应用程序中正确设置打印方向?
【发布时间】:2019-10-24 19:45:14
【问题描述】:

我需要创建一个打印服务,它可以从整个应用程序的不同组件中调用。 service方法接受两个参数,需要编译打印的组件,打印方向(Portrait or Landscape)。

一切正常,除了方向。要么未设置,要么坚持第二次应用的方向。我所说的第二个应用方向的意思是,我有两个按钮用于测试目的。每个按钮调用不同的组件并设置不同的方向。如果我按以下顺序单击按钮:纵向,然后是横向,然后无论我按什么,页面都会以横向打印,反之亦然。

到目前为止,我已经尝试了以下方法:

  • 定义了两个有条件生成的不同 div 元素(使用 ngIf 指令)。每个 div 包含具有适当页面方向的 <style></style> 元素。 style 元素未呈现,因此方向未更改

  • 页面方向在组件的 style/stuleUrls 元数据中定义。这会产生上述第二次应用方向的问题

  • 使用ComponentFactoryResolver 为动态创建的组件添加样式。未应用页面样式

组件是使用ComponentFactoryResolver 动态生成的。为简单起见,我不会发布该代码。如果需要,我会发布。

这个html被添加到app.component.html:

<div class="print-section">
    <div *ngIf="printOrientation === orientationEnum.Landscape">
        <style>
            @media print {
                @page {
                    orientation: landscape !important;
                }
            }
        </style>
    </div>
    <div *ngIf="printOrientation === orientationEnum.Portrait">
        <style>
            @media print {
                @page {
                    orientation: portrait !important;
                }
            }
        </style>
    </div>
</div>

在组件样式/styleUrls 元数据中添加了相同的代码。

我也尝试过在组件创建后动态地向生成的组件添加类:

let element: HTMLElement = <HTMLElement>componentRef.location.nativeElement;
this.printTemp.layout === PrintLayoutEnum.Landscape ? element.classList.add('landscape-print') : element.classList.add('portrait-print');

这根本不影响方向。

预期的结果是适当地改变方向。通过在app.component.html 中设置style,或者通过在使用ComponentFactoryResolver 呈现组件时动态应用。我更喜欢第二种选择,但任何一种都可以。

【问题讨论】:

    标签: html css angular printing orientation


    【解决方案1】:

    我有隧道视野,我试图使解决方案过于复杂。我创建了一个带有 id 的 style 元素。在使用ComponentFactoryResolver 创建组件期间,我只是附加了所需的样式:

    let styleElement = document.getElementById('print-style');
    styleElement.append('@media print { @page { size: A4 landscape; } }')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-08
      • 1970-01-01
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-03
      相关资源
      最近更新 更多