打印HTML内容

时间:2018-05-15 12:27:10

标签: javascript angular

我一直在四处寻找,我发现有很多人有同样的问题,但到目前为止还没有解决方案。

我在学生的电子学习应用程序中使用角度5和角度材料,我需要实现的功能之一是打印文档,但我还没有找到方法,如果有的话以角度方式打印div内容的任何方式,因为我尝试使用此solution 但是不起作用,因为当我得到DOM元素的innerHTML时,返回带有角度代码的html:

                      <!--bindings={
  "ng-reflect-ng-for-of": "[object Object],[object Object"
}--><article _ngcontent-c18="" class="ng-tns-c18-3 ng-star-inserted" style="">

                        <!--bindings={
  "ng-reflect-ng-if": "false"
}-->


                        <!--bindings={
  "ng-reflect-ng-if": "false"
}-->


                        <!--bindings={
  "ng-reflect-ng-if": "true"
}--><p _ngcontent-c18="" autocorrect="off" draggable="return false;" oncut="return false" ondragover="return false;" ondrop="return false;" onkeypress="return false" onpaste="false" spellcheck="false" class="ng-tns-c18-3 ng-star-inserted" ng-reflect-ng-class="[object Object]" data-block-id="8f5b8d8f-9027-4c40-b7fe-d5ec90334fd9" contenteditable="true">Hallo Zusammen,</p>


                        <!--bindings={
  "ng-reflect-ng-if": "false"
}-->

而不是容器的内容,并给我一个错误,任何想法,如果有这个。

1 个答案:

答案 0 :(得分:3)

我会使用一个可以附加到容器元素的指令。该指令应用适当的样式,以便元素外部的所有内容都不会被打印,内部的所有内容都是。

指令

@Directive({
  selector: '[print-section]',
})
export class PrintSectionDirective implements AfterViewInit, OnDestroy {
  @HostBinding('class.print-section') private printSection = true;
  private style: HTMLStyleElement;

  public ngAfterViewInit() {
    this.style = document.createElement('style');
    this.style.type = 'text/css';
    this.style.innerText = `
    @media print {
      body * {
        visibility: hidden;
      }
      .print-section, .print-section * {
        visibility: visible;
      }
      .print-section {
        width: 100%;
      }
    }`;

    document.head.appendChild(this.style);
  }

  public ngOnDestroy() {
    document.head.removeChild(this.style);
  }
}

用法

模板

<div print-section>Print only this content</div>
<button (click)="printThePage()">Print Content</button>

成分<​​/ P>

public printThePage() {
  window.print();
}

这种方法的优点是,当不使用该指令时,页面仍然可以使用默认行为进行打印,当它被附加时,只打印页面的那一部分,它将适合宽度页面。