打印HTML内容 [英] Printing HTML content
问题描述
我一直在环顾四周,我发现很多人都遇到同样的问题,但到目前为止还没有解决的办法.
i have been looking around and i see that there is a lot of people with the same problem but so far no solution.
我正在为学生的电子学习应用程序中处理角度5和角度材料,我需要实现的功能之一是打印文档,但是如果有的话,我还没有找到解决方法任何以角度方式打印div
内容的方法,因为我尝试使用此
i´m working with angular 5 and angular material in a E-learning application for students and one of the function i need to implement is for printing the document, but i have not found a way to do it, if there is any way to print the content of a div
in angular, because i try with this solution
but doesn´t work, because when i get the innerHTML of the DOM Element, return me the html with angular the code:
<!--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"
}-->
而不是容器的内容,请给我一个错误,如果没有,请告诉我一个错误.
and not the content of the container, and give me a error, any idea if there is away to this.
推荐答案
我将使用可以附加到容器元素的指令.该指令将应用适当的样式,以便不打印元素外部的所有内容,而打印其中的所有内容.
I would use a directive that you can attach to a container element. The directive applies the appropriate styles so that everything outside the element is not printed and everything inside is.
@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();
}
此方法的优点是,当不使用该指令且附加了指令时,仍将能够以默认行为打印页面,然后仅打印页面的该部分并适合宽度页面的内容.
The advantages of this method is that the page will still be able to be printed with the default behavior when the directive is not used and when it is attached then only that section of the page will be printed and it will fit the width of the page.
这篇关于打印HTML内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!