CristalT
8/31/2019 - 12:17 AM

Exportar Datatable a PDF

/**
 * Librería requerida: npm install pdfmake
 * */
 
import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
pdfMake.vfs = pdfFonts.pdfMake.vfs;

/**
 * @param data Object[] Ej. [{ nombre: 'Marcelo', apellido: 'Forclaz' }]
 * @param columns Object[] Ej. [{ label: 'Nombre', key: 'nombre' }]
 **/
 
export const pdf = (data, columns) => {
  const cols = [
    columns.map(item => ({
      text: item.label,
      style: 'tableHeader'
    }))
  ];
  const rows = data.reduce((acc, item) => {
    const row = [];
    columns.forEach(col => {
      row.push({ text: item[col.key], fontSize: 8 });
    });
    acc.push(row);
    return acc;
  }, []);
  const dd = {
    content: [
      {
        table: {
          fontSize: 8,
          body: cols.concat(rows)
        }
      }
    ],
    styles: {
        tableHeader: {
            fillColor: '#212121',
            fontSize: 8,
            color: '#ffffff'
        }
    }
  };
  pdfMake.createPdf(dd).open();
};