I had a problem where input controls were loosing their values when printing so I cooked up this code. This series of functions allows you to print either some static HTML snippet or the contents of a particular node and preserves input values and features hiding selected elements with the class "hideToPrint" and features a callback to modify the HTML just for the print so you can change things in other ways without messing with the original node.
The only downside of this I know of is that the body looks like what you are printing while the print dialog is up.
This has only been tested on Chrome.
CSS:
@media print {
.hideToPrint {
display: none;
}
}
JS:
/**
* Takes the outerHTML of the element referenced by contentId
* and applies the fnModifyHtml(printContents) to the
* outerHTML content if specified, and prints it.
* Any content element that has the class "hideToPrint" will
* be hidden for printing.
* @param {string} contentId host element id
* @param {function=} fnModifyHtml
*/
async function as_printContent(contentId, fnModifyHtml=null) {
const aHideToPrint = Array.from(document.getElementsByClassName('hideToPrint'));
aHideToPrint.forEach((el) => {
hide(el);
});
await as_printRawContent(ge(contentId), fnModifyHtml);
aHideToPrint.forEach((el) => {
show(el);
});
}
/**
* Asynchronously prints the raw content of an element.
*
* @param {Element|string} elContent - The element or HTML string to print.
* @param {function} fnModifyHtml - A function to modify the printed HTML.
* @return {Promise<void>} A promise that resolves when the printing is done.
*/
async function as_printRawContent(elContent, fnModifyHtml = null) {
if (typeof(elContent) == 'string') {
// this is HTML and needs to be placed into a temporary element
const html = elContent;
elContent = document.createElement('div');
elContent.innerHTML = html;
}
const aBodyValues = saveNodeValues(document.body);
const bodyHTML = document.body.innerHTML;
const aPrintContentValues = saveNodeValues(elContent);
let printContents = elContent.outerHTML;
if (fnModifyHtml) {
printContents = fnModifyHtml(printContents);
}
document.body.innerHTML = printContents;
restoreNodeValues(document.body, aPrintContentValues);
await delay(1);
window.print();
document.body.innerHTML = bodyHTML;
restoreNodeValues(document.body, aBodyValues);
addEventHandlers();
}
/**
* Retrieve the values of all input, select, and textarea elements within a given node.
*
* @param {HTMLElement} node - The node to search for input elements.
* @return {Array} An array of objects containing the id, value, and type of each input element.
*/
function saveNodeValues(node) {
return Array.from(node.querySelectorAll('input, select, textarea')).map((el) => {
if (!el.id) {
console.assert(el.id, `Element ${el.outerHTML} has no id`);
}
return {
id: el.id,
value: (el.type == 'checkbox') ? el.checked : el.value,
type: el.type
};
});
}
/**
* Restores the values of the specified DOM elements based on the provided array of values.
*
* @param {Node} node - The root node from which the DOM elements will be searched.
* @param {Array} aValues - An array of objects containing the id, value, and type of each element to be restored.
* @param {string} aValues[].id - The id of the DOM element.
* @param {any} aValues[].value - The value to be restored on the DOM element.
* @param {string} aValues[].type - The type of the DOM element (e.g., 'checkbox', 'text', etc.).
*/
function restoreNodeValues(node, aValues) {
aValues.forEach(({ id, value, type }) => {
const el = ge(id);
if (el) {
if (type === 'checkbox') {
el.checked = value ? 'checked' : '';
} else {
el.value = value;
}
}
});
}
/**
* Delays the execution of subsequent code for a specified amount of time.
* @param {number} time The amount of time to delay in milliseconds.
* @returns {Promise} A promise that resolves after the specified time has passed.
*/
async function delay(time) {
return new Promise((resolve) => {
setTimeout(resolve, time);
});
}