我环顾四周,发现有很多人有同样的问题,但到目前为止还没有解决方案。
我正在为学生提供的电子学习应用程序中使用 Angular 5 和 Angular Material ,我需要实现的功能之一是打印文档,但我还没有找到一种方法来做到这一点(如果有的话)任何方式打印 div
的内容有 Angular ,因为我尝试使用这个 solution
但不起作用,因为当我获得 DOM 元素的innerHTML时,返回带有 Angular 代码的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"
}-->
而不是容器的内容,并给我一个错误,知道是否有这个问题。
最佳答案
我将使用一个可以附加到容器元素的指令。该指令应用适当的样式,以便不打印元素外部的所有内容,而打印内部的所有内容。
指令
@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>
组件
public printThePage() {
window.print();
}
此方法的优点是,当未使用该指令时,页面仍然能够以默认行为打印,并且当附加该指令时,仅打印页面的该部分,并且它将适合宽度页面的。
关于javascript - 打印 HTML 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50350212/