print-html-element
print-html-element copied to clipboard
Printing multiple divs?
Hello, I'm currently using print-html-element to print off certain "tickets" for my current React application. It works fine if I select single tickets, but my superiors want the function to print off multiple tickets. All these tickets are stored in their own div elements.
I know it's posted that it will be a feature implemented later, but is there a workaround you suggest?
Hi @AndehWong. Sorry, I've been super busy.
Since you've asked about it, I'm actually intending to cut a new release soon to support multiple elements. I should be doing that shortly and will update this issue at that time.
In the mean time, a work around would be to take all of your "ticket divs" and wrap them in one single <div>
or other element. Alternatively, you could get and concatenate their outerHTML
together.
Something like...
// Query for your tickets and spread the `NodeList` into an `Array`
const tickets = [...document.querySelectorAll('.ticket')];
// Create an empty wrapper div
const ticketWrapper = document.createElement("div");
// Deep clone each ticket node and append to the wrapper `<div>`
tickets.forEach(ticket => {
ticketWrapper.appendChild(ticket.cloneNode(true));
});
// Print the wrapper `<div>`
printHtmlElement.printElement(ticketWrapper);
Or...
// Map over each ticket and return its `outerHTML`, then concatenate the strings
ticketMarkup = tickets.map(ticket => ticket.outerHTML).join('\n');
// Print the markup
printHtmlElement.printHtml(ticketMarkup);
I'll leave this issue open to track the feature request
I managed to use your second method of mapping each ticket to a variable string. It retains the CSS from the original page and it prints each ticket on it's own page.
var htmlString = "";
for (var i = 0; i < this.state.rowsToPrint.length; i++){
htmlString = htmlString.concat('<div style="page-break-after:always;">');
const element = document.getElementById('ticketPrint-' + this.state.rowsToPrint[i]);
htmlString = htmlString.concat(element.innerHTML);
htmlString = htmlString.concat('</div>');
}
Printer.printHtml(htmlString);