Hi Guys,
Can you please suggest how can we print pdf from lwc component?
I tried window.print() which gives whole page, we only want contents from our lwc component.
Hello community!
I had similar task and was able to complete it using just lwc!
For that I had to create the following js method:
handlePrintClick () {
let printableElement = this.template.querySelector('.print-section');
if (printableElement) {
let clone = printableElement.cloneNode(true);
let printWindow = window.open('', '_blank');
if (printWindow) {
printWindow.document.body.appendChild(clone);
let style = printWindow.document.createElement('style');
style.textContent = `
@page {
size: auto; /* auto is the initial value */
margin: 0mm; /* this affects the margin in the printer settings */
}
@media print {
body {
margin: 0;
padding: 0;
}
.no-print {
display: none;
}
}
`;
printWindow.document.head.appendChild(style);
printWindow.focus();
printWindow.print();
printWindow.close();
} else {
console.error('Failed to open print window');
}
} else {
console.error('Printable element not found');
}
}
and you need to update the content of html with css class to the place which you wanted to print (I had lots of inner data, parent and childs)
<div class="print-section">
Data which should be printed
</div>
Note: In my case I had all css values in the same html file (not a separate css, I used style tag)