Skip to content

Instantly share code, notes, and snippets.

@MarcosSantosDev
Created December 22, 2022 15:49
Show Gist options
  • Save MarcosSantosDev/483834c388dbc0cb37b5a5537833c735 to your computer and use it in GitHub Desktop.
Save MarcosSantosDev/483834c388dbc0cb37b5a5537833c735 to your computer and use it in GitHub Desktop.
Print Html
type PrintHtmlParams = {
/**
* `containerId`:
* - Index of the element where the content to be printed will be assembled
*/
containerId: string;
/**
* `elementHtml`:
* - Content to be printed
*/
elementHtml: string;
};
export const printHtml = ({ containerId, elementHtml }: PrintHtmlParams) => {
const containerIFrame = document.getElementById(containerId);
if (containerIFrame) {
const tagIframe = document.createElement('iframe');
tagIframe.style.position = 'fixed';
tagIframe.style.right = '0';
tagIframe.style.bottom = '0';
tagIframe.style.width = '0';
tagIframe.style.height = '0';
tagIframe.style.border = '0';
containerIFrame.appendChild(tagIframe);
if (tagIframe.contentWindow) {
const removeChildElements = () => {
containerIFrame.removeChild(tagIframe);
};
tagIframe.contentWindow.onbeforeunload = removeChildElements;
tagIframe.contentWindow.onafterprint = removeChildElements;
tagIframe.contentWindow.document.write(
`
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<style type="text/css" media="print">
@page {
size: auto; /* auto is the initial value */
margin: 0; /* this affects the margin in the printer settings */
}
body
{
border: none;
margin: 8mm;
}
</style>
</head>
<body>${elementHtml}</body>
</html>
`,
);
tagIframe.contentWindow.focus();
tagIframe.contentWindow.print();
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment