simonbengtsson / jsPDF-AutoTable

jsPDF plugin for generating PDF tables with javascript
https://simonbengtsson.github.io/jsPDF-AutoTable/
MIT License
2.33k stars 624 forks source link

Node.js PDF Rendering Issue with HTML Table String from MongoDB #1066

Closed Brunapupo closed 2 months ago

Brunapupo commented 2 months ago

I am currently retrieving a string containing an HTML table tag from the frontend browser and sending it to the backend. Upon retrieval from MongoDB, it appears as "Type of htmlData: object". However, when passing this string to the autotable library, nothing is rendered in the PDF.

module.exports.recuperarHtmlPorId = async (id) => {
    try {
        const htmlData = await HtmlTable.findOne({ _id: id }, { _id: 1, htmlTableString: 1, dataCriacao: 1 });

        if (!htmlData) {
            throw new Error('HTML não encontrado');
        }

        const htmlTableString = [htmlData.htmlTableString];

        const doc = new JsPDF({
            orientation: 'portrait',
            unit: 'pt',
            format: 'a4',
        });
        const totalPagesExp = '{total_pages_count_string}';
        doc.setFont('helvetica');
        doc.setFontSize(9);
        doc.setDrawColor(50, 54, 57);

        const larguraPagina = doc.internal.pageSize.getWidth();
        const alturaPagina = doc.internal.pageSize.getHeight();
        const margem = 20;

        // Header e logos
        const larguraTotalLogos = 260;
        const xInicioLogos = (larguraPagina - larguraTotalLogos) / 2;
        const yPositionLogos = 20;

        const logoWidthSus = 100;
        const logoHeightSus = 40;
        const logoWidthSecretariaSaude = 100;
        const logoHeightSecretariaSaude = 30.77;

        const tituloHeader =
            'ESTADO DE SANTA CATARINA\nSECRETARIA DE ESTADO DA SAÚDE\nSUPERINTENDÊNCIA DE SERVIÇOS ESPECIALIZADOS E REGULAÇÃO\nCENTRAL ESTADUAL DE TELEMEDICINA\n';
        const dataEmissao = new Date().toLocaleString();

        doc.autoTable({
            html: htmlTableString,
            useCss: true,
            margin: { top: 160, right: margem, bottom: 40, left: margem },
            horizontalPageBreak: true,
            horizontalPageBreakRepeat: 0,
            didDrawPage: (data) => {
                const xCentro = larguraPagina / 2;

                // Header
                doc.setFontSize(9);
                doc.setFont('helvetica');

                // logos
                if (logoSus) {
                    const logoXPosition = margem;
                    const logoYPosition = 20;
                    doc.addImage(logoSus, 'PNG', logoXPosition, logoYPosition, logoWidthSus, logoHeightSus);
                }

                if (logoSecretariaSaude) {
                    const logoXPosition = larguraPagina - margem - logoWidthSecretariaSaude;
                    const logoYPosition = 20;
                    doc.addImage(logoSecretariaSaude, 'PNG', logoXPosition, logoYPosition, logoWidthSecretariaSaude, logoHeightSecretariaSaude);
                }

                const linhasTitulo = tituloHeader.split('\n');
                const linhaAltura = 12;
                linhasTitulo.forEach((linha, index) => {
                    const tituloXPosition = xCentro - doc.getTextWidth(linha) / 2;
                    doc.text(linha, tituloXPosition, yPositionLogos + 10 + index * linhaAltura);
                });

                doc.setFontSize(24);
                const tituloTabela = formatarStringCubo('cubo_exemplo');
                const tituloTabelaXPosicao = xCentro - doc.getTextWidth(tituloTabela) / 2;
                doc.text(tituloTabela, tituloTabelaXPosicao, yPositionLogos + linhasTitulo.length * linhaAltura + 30);

                doc.setFontSize(10);
                const dataInicialFinal = `Data Inicial: ${new Date().toLocaleDateString()}`;
                const dataFinalText = `Data Final: ${new Date().toLocaleDateString()}`;
                const dataEmissaoText = `Data de Emissão: ${dataEmissao}`;

                const PosicaoYData = yPositionLogos + 10 + linhasTitulo.length * linhaAltura + 60;

                doc.text(dataInicialFinal, margem, PosicaoYData); // Alinhado à esquerda
                doc.text(dataFinalText, xCentro - doc.getTextWidth(dataFinalText) / 2, PosicaoYData); // Centralizado
                doc.text(dataEmissaoText, larguraPagina - margem - doc.getTextWidth(dataEmissaoText), PosicaoYData); // Alinhado à direita

                // Paginação
                let textoRodape = 'Página ' + data.pageNumber;
                if (typeof doc.putTotalPages === 'function') {
                    textoRodape = textoRodape + ' de ' + totalPagesExp;
                }
                doc.text(textoRodape, larguraPagina - margem - 100, alturaPagina - 10);
            },
        });

        if (typeof doc.putTotalPages === 'function') {
            doc.putTotalPages(totalPagesExp);
        }

        const pdfBuffer = doc.output('arraybuffer');
        return Buffer.from(pdfBuffer);
    } catch (error) {
        console.error('Erro ao gerar PDF no backend: ', error);
        throw error;
    }
};

image

github-actions[bot] commented 2 months ago

This issue will soon be closed since issues in this project are mainly meant to be bugs or feature requests. Questions are directed to stackoverflow.