JAVASCRIPT   72

html.js

Guest on 30th July 2021 02:48:45 PM

  1. import { collectStyles, loopNodesCollectStyles, addWrapper, addHeader } from './functions'
  2. import Print from './print'
  3.  
  4. export default {
  5.   print: (params, printFrame) => {
  6.     // Get HTML printable element
  7.     let printElement = document.getElementById(params.printable)
  8.  
  9.     // Check if element exists
  10.     if (!printElement) {
  11.       window.console.error('Invalid HTML element id: ' + params.printable)
  12.  
  13.       return false
  14.     }
  15.  
  16.     // Make a copy of the printElement to prevent DOM changes
  17.     let printableElement = document.createElement('div')
  18.     printableElement.appendChild(printElement.cloneNode(true))
  19.  
  20.     // Add cloned element to DOM, to have DOM element methods available. It will also be easier to colect styles
  21.     printableElement.setAttribute('style', 'display:none;')
  22.     printableElement.setAttribute('id', 'printJS-html')
  23.     printElement.parentNode.appendChild(printableElement)
  24.  
  25.     // Update printableElement variable with newly created DOM element
  26.     printableElement = document.getElementById('printJS-html')
  27.  
  28.     // Get main element styling
  29.     printableElement.setAttribute('style', collectStyles(printableElement, params) + 'margin:0 !important;')
  30.  
  31.     // Get all children elements
  32.     let elements = printableElement.children
  33.  
  34.     // Get styles for all children elements
  35.     loopNodesCollectStyles(elements, params)
  36.  
  37.     // Add header if any
  38.     if (params.header) {
  39.       addHeader(printableElement, params.header, params.headerStyle)
  40.     }
  41.  
  42.     // Remove DOM printableElement
  43.     printableElement.parentNode.removeChild(printableElement)
  44.  
  45.     // Store html data
  46.     params.htmlData = addWrapper(printableElement.innerHTML, params)
  47.  
  48.     // Print html element contents
  49.     Print.send(params, printFrame)
  50.   }
  51. }

Raw Paste


Login or Register to edit or fork this paste. It's free.