Pdfkit: Как создать новый PDF для каждой новой страницы? - PullRequest
0 голосов
/ 28 июня 2019

Я использую pdfkit для создания нового PDF-файла и нод-машинописный код для кода, и я хочу, чтобы каждая новая страница была в отдельном PDF-файле (только с 1 страницей). Дело в том, что я не знаю размер содержимого PDF, он исходит со стороны клиента. (если это связано с тем, что я хочу сделать)

Я пытался поместить pdf.end в функцию pageAdded, но все равно получаю этот пустой pdf каждый раз, когда пытаюсь создать pdf. (Я нуб на ноде / машинопись)

Вот мой код:

import { sign } from 'tjam-pdf-utils';
import { GenericErrorException } from 'tjam-node-exceptions';
import { readFile, createWriteStream, unlinkSync } from 'fs';

let Pdf = require('pdfkit');

interface paramsCertificate {
    oficial?: string;
    doc?: string;
    mandado?: string;
    processo?: string;
    descricao?: string;
    latitude?: string;
    longitute?: string;
    precisao?: string;
    classe?: string;
    indiciado?: string;
    docSigner?: string;
    currentDir?: string;
    pathCertificate?: string;
    pathCertificateSigner?: string;
    blob?: any;
    image?:any;
    error?: GenericErrorException;
}



function makeCretificate(c:paramsCertificate): Promise<paramsCertificate> {
    return new Promise((resolve, reject) => {
        try {
            c.oficial = null? '': c.oficial;
            c.mandado = null? '': c.mandado;
            c.processo = null? '': c.processo;
            c.classe = null? '': c.classe;
            c.descricao = null? '': c.descricao;
            c.latitude = null? '': c.latitude;
            c.longitute = null? '': c.longitute;
            c.precisao = null? '': c.precisao;

            let date = new Date().toLocaleString('pt-BR');

            c.pathCertificate = c.currentDir + (c.oficial.replace(/\s/gi, '')) + '_' + (date.replace(/\s/gi, '-'));

            let myDoc = new Pdf({ size: 'a4',  margin: 40,  autoFirstPage: false});

            let  options = { encoding: 'binary' };
            myDoc.pipe(createWriteStream(c.pathCertificate + '.pdf', options));

            let pageNumber = 0;
            myDoc.on('pageAdded', () => {
                pageNumber++;
                let bottom = myDoc.page.margins.bottom;
                myDoc.page.margins.bottom = 0;
                myDoc.font('Times-Roman')
                    .text(`${pageNumber}`,
                        (myDoc.page.width - 50),
                        myDoc.page.height - 50,
                );

                // Reset text writer position
                myDoc.text('', 50, 50);
                myDoc.page.margins.bottom = bottom;
            });

            // espaços entre os textos
            let enter = '\n\n';

            myDoc.addPage();
            // brasão do tribunal
            let  center = Math.round((myDoc.page.width - 70) / 2);
            myDoc.image(c.currentDir + 'TJAM.png', center, 40, {width: 70, height: 85});

            // cabeçalho do tribunal
            let header_01 = `PODER JUDICIÁRIO`;
            myDoc.y = 140
            myDoc.text(header_01, {
                align:'center'
            });

            let header_02 = `TRIBUNAL DE JUSTIÇA DO AMAZONAS`;
            myDoc.text(header_02, {
                align:'center'
            });


            // cabeçalho da certidão
            let mandado = 'Mandado: ' + formatarNumMandado(c.mandado);
            let processo = 'Processo nº: ' + formatarNumProcesso(c.processo);
            let classe = 'Classe: ' + c.classe;
            // let indiciado = 'Indiciado(s): ' + c.indiciado;
            myDoc.text(enter
                + mandado
                + '\n'+ processo
                + '\n' + classe
                , {align: 'justify'});



            // texto
            let certidão = 'CERTIDÃO';
            myDoc.text(enter
                + certidão, {align: 'center'});

            let text = c.descricao + '. Mandado cumprido na posição geográfica <' 
                + c.latitude + ', ' + c.longitute + '> (precisaõ de ' + c.precisao + ' metro(s))';
            myDoc.font('Times-Italic')
                .lineGap(5)
                .text(enter
                    + text, {align: 'justify'});
myDoc.end();
            resolve(c);
        }
        catch (err) {
            c.error = new GenericErrorException(`Ocorreu um erro ao montar a certidão: ${err.toString()}`);
            reject(c);
        }
    });
}

Какую операционную систему вы используете? Arch Linux Manjaro Кто-нибудь знает, как я могу это сделать?

...