DEV Community

Discussion on: Criando documentos PDF com ReactJS

Collapse
 
taikio profile image
Welker Arantes Ferreira

essa lib não se comunica diretamente com o state do react, você precisa montar um objeto com todas as informações que precisa e passar no construtor da classe de impressão. Ex.:

const dados = {
valorTotal: valorTotalState,
};
const classeImpressao = new Impressao(dados);

Collapse
 
luccanjm profile image
Lucca Nunes de Jesus Martinelli • Edited

Está assim o código, quero exibir o valorTotal depois da tabela que está no body
Poderia me ajudar?

export class Impressao {

constructor(dadosParaImpressao) {
this.dadosParaImpressao = dadosParaImpressao;

let valorTotal = 0;
for (let i = 0; i < dadosParaImpressao.length; i++) {
    valorTotal += parseFloat(dadosParaImpressao[i].valorBoleto);
}
Enter fullscreen mode Exit fullscreen mode

}

async PreparaDocumento() {
const corpoDocumento = this.CriaCorpoDocumento();
const documento = this.GerarDocumento(corpoDocumento);
return documento;
}

CriaCorpoDocumento() {
const header = [
{ text: 'Mês Chamado', bold: true, fontSize: 12, margin: [0, 4, 0, 0] },
{ text: 'Número Chamado', bold: true, fontSize: 12, margin: [0, 4, 0, 0] },
{ text: 'Valor Boleto', bold: true, fontSize: 12, margin: [0, 4, 0, 0] },
{ text: 'Técnico Chamado', bold: true, fontSize: 12, margin: [0, 4, 0, 0] },
{ text: 'Sistema', bold: true, fontSize: 12, margin: [0, 4, 0, 0] },

];
const body = this.dadosParaImpressao.map((item) => {
  return [
    { text: item.mesChamado, fontSize: 12 },
    { text: item.numeroChamado, fontSize: 12 },
    { text: item.valorBoleto, fontSize: 12 },
    { text: item.tecnicoChamado, fontSize: 12 },
    { text: item.sistema, fontSize: 12 },


  ];
});


const lineHeader = [
  {
    text:
      '__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________',
    alignment: 'center',
    fontSize: 5,
    colSpan: 5,

  },
  {},
  {},
];

let content = [header, lineHeader];
content = [...content, ...body];
return content;
Enter fullscreen mode Exit fullscreen mode

}

GerarDocumento(corpoDocumento) {
  const documento = {
    pageSize: 'A4',
    pageMargins: [14, 53, 14, 48],
    header: function () {
      return {
          margin: [14, 12, 14, 0],
          layout: 'noBorders',
          table: {
            widths: ['*'],
            body: [                             
              [
                { text: `RELATÓRIO DE CHAMADOS`, style: 'reportName' }


              ]              
            ],
          },
        };
    },
  content: [
    {
          layout: 'noBorders',
          table: {              
            headerRows: 1,
            widths: [ '*',100,100,100,100],

            body: corpoDocumento
          }
        },
  ],
  footer(currentPage, pageCount) {
        return {
          layout: 'noBorders',
          margin: [14, 0, 14, 22],
          table: {
            widths: ['auto'],
            body: [
              [
                {
                  text:
                    '_________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________',
                  alignment: 'center',
                  fontSize: 5,
                },
              ],
              [
                [
                  {
                    text: `Página ${currentPage.toString()} de ${pageCount}`,
                    fontSize: 7,
                    alignment: 'right',
                    /* horizontal, vertical */
                    margin: [3, 0],
                  },
                  {
                    text: '© TI | 2021 ',
                    fontSize: 7,
                    alignment: 'center',
                  }
                ],
              ],
            ],
          },
        };
      },
  styles: {
    reportName: {
      fontSize: 20,
      bold: true,
      alignment: 'center',
      margin: [0, 4, 0, 0],
      color:'#145E7D',
    }
  },

};
  return documento;
}
Enter fullscreen mode Exit fullscreen mode

}

Thread Thread
 
taikio profile image
Welker Arantes Ferreira

Substitua seu método CriaCorpoDocumento pelo exemplo que vou deixar abaixo, aí você vai conseguir adicionar outros elementos como texto, imagem, etc... Basta fazer page.push(elemento_que_deseja_adicionar)

CriaCorpoDocumento () {
    let page = []

    page.push({
      text: 'Tabela de Itens',
      fontSize: 14,
      bold: true,
      alignment: 'center'
    })

    const header = [
      { text: 'Codigo', bold: true, fontSize: 9, margin: [0, 4, 0, 0] },
      { text: 'Titulo', bold: true, fontSize: 9, margin: [0, 4, 0, 0] },
      { text: 'Descrição', bold: true, fontSize: 9, margin: [0, 4, 0, 0] },
      { text: 'Link', bold: true, fontSize: 9, margin: [0, 4, 0, 0] },
    ];

    const lineHeader = [
      {
        text:
          '__________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________',
        alignment: 'center',
        fontSize: 5,
        colSpan: 4,
      },
      {},
      {},
      {}
    ];

    const tableContent = []

    tableContent.push(header)
    tableContent.push(lineHeader)

    for (const item of this.dadosParaImpressao) {
      tableContent.push([
        { text: item.id, fontSize: 10 },
        { text: item.title, fontSize: 10 },
        { text: item.description, fontSize: 10 },
        { text: 'Google.com', link: 'https://www.google.com/', fontSize: 10 }
      ])
    }

    page.push({
      layout: 'noBorders',
      table: {              
        headerRows: 1,
        widths: [ 40, 55, '*', 55 ],
        body: tableContent
      }
    })

    return page;
  }
Enter fullscreen mode Exit fullscreen mode


`

Outra coisa, no método GerarDocumento substitua a linha da propriedade content pra ficar assim:

content: corpoDocumento