Reputation: 15
Suppose it's a sample code 👇
<div id="print-div">
<p>Lorem ipsum dolor sit amet page 1.</p>
<ion-label>page break here</ion-label>
<p>Lorem ipsum dolor sit amet page 2.</p>
</div>
I want to print this section, where first paragraph will be in 1st page and 2nd paragraph will be in next page.
printThis(){
let backup = document.body.innerHTML;
let divcontent = document.getElementById('print-div').innerHTML;
document.body.innerHTML = divcontent;
window.print();
document.body.innerHTML = backup;
}
@media print {
ion-label{
page-break-before: always !important;
}
}
But this does not breaking the page while printing. All the data are printing in one page & if the content is larger than one page, it still printing ony one page's data.
I have tried with
page-break-before: always;
page-break-after: always;
break-after: always;
But nothing happening.
If anyone helps me a little bit that how to use the page-break property in ionic. I'll be very thankful.
Upvotes: 1
Views: 930
Reputation: 462
For me adding this work. Ionic 4, Angular 8
@media print {
body {
position: relative !important;
}
}
https://medium.com/@Idan_Co/angular-print-service-290651c721f9
Upvotes: 0
Reputation: 796
Problem:
The ion-content component has an inner div with absolute positioning. As ionic is using web-components with shadow-root and the positioning is not exposed as a css-variable, this style property cannot be set with the css stylesheet. But: Page-breaks don't work on absolute positioned elements w3schools
Solution:
Use JS to manipulate the shadow-root and set the positioning to relative. github: ionic-print-test
I had the same problem and solved it by using the event-listeners onbeforeprint
and onafterprint
. Here is an example for ionic with angular but the logic can easily be refactored to react or vue. ionic-print-test:issue
print.service.ts
import { DOCUMENT } from '@angular/common';
import { Inject, Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class PrintService {
constructor(@Inject(DOCUMENT) private document: HTMLDocument) {}
init() {
window.onbeforeprint = () => this.setPrintStyles(true);
window.onafterprint = () => this.setPrintStyles(false);
}
private setPrintStyles(add: boolean) {
this.document.querySelectorAll('ion-content').forEach((element) => {
const scroll = element.shadowRoot.querySelector('.inner-scroll') as HTMLElement;
if (add) {
scroll.style.position = 'relative';
} else {
scroll.style.removeProperty('position');
}
});
}
}
Upvotes: 2