JAVASCRIPT   75

json.js

Guest on 30th July 2021 02:52:22 PM

  1. import { addWrapper, capitalizePrint } from './functions'
  2. import Print from './print'
  3.  
  4. export default {
  5.   print: (params, printFrame) => {
  6.     // Check if we received proper data
  7.     if (typeof params.printable !== 'object') {
  8.       throw new Error('Invalid javascript data object (JSON).')
  9.     }
  10.  
  11.     // Check if properties were provided
  12.     if (!params.properties || typeof params.properties !== 'object') {
  13.       throw new Error('Invalid properties array for your JSON data.')
  14.     }
  15.  
  16.     // Variable to hold html string
  17.     let htmlData = ''
  18.  
  19.     // Check print has header
  20.     if (params.header) {
  21.       htmlData += '<h1 style="' + params.headerStyle + '">' + params.header + '</h1>'
  22.     }
  23.  
  24.     // Build html data
  25.     htmlData += jsonToHTML(params)
  26.  
  27.     // Store html data
  28.     params.htmlData = addWrapper(htmlData, params)
  29.  
  30.     // Print json data
  31.     Print.send(params, printFrame)
  32.   }
  33. }
  34.  
  35. function jsonToHTML (params) {
  36.   let data = params.printable
  37.   let properties = params.properties
  38.  
  39.   let htmlData = '<div style="display:flex; flex-direction: column;">'
  40.  
  41.   // Header
  42.   htmlData += '<div style="flex:1 1 auto; display:flex;">'
  43.  
  44.   for (let a = 0; a < properties.length; a++) {
  45.     htmlData += '<div style="flex:1; padding:5px;' + params.gridHeaderStyle + '">' + capitalizePrint(properties[a]['displayName'] || properties[a]) + '</div>'
  46.   }
  47.  
  48.   htmlData += '</div>'
  49.  
  50.   // Create html data
  51.   for (let i = 0; i < data.length; i++) {
  52.     htmlData += '<div style="flex:1 1 auto; display:flex;">'
  53.  
  54.     for (let n = 0; n < properties.length; n++) {
  55.       htmlData += '<div style="flex:1; padding:5px;' + params.gridStyle + '">' + data[i][properties[n]['field'] || properties[n]] + '</div>'
  56.     }
  57.  
  58.     htmlData += '</div>'
  59.   }
  60.  
  61.   htmlData += '</div>'
  62.  
  63.   return htmlData
  64. }

Raw Paste


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