본문 바로가기

Nodejs

[Nodejs] phantomjs 사용하여 pdf 파일 추출하기

반응형

소스코드

const phantom = require('phantom');
const fs = require('fs');

const fileUtils = new FileUtils();
    const uploadFolder = `${process.env.UPLOAD_FOLDER_SMTP_ATTACH}${orderInfo.orderNo}`;
    const flag = await fileUtils.mkdir(uploadFolder);

    const attachFile = orderInfo.orderNo + '.pdf';
    const instance = await phantom.create();
    const page = await instance.createPage();
    const file = 'invoicePaid.html';
    let isInvocie = false;
    // await fs.statSync(path.join(__dirname, `../utils/config/form`, file));
    const data = await fs.readFileSync(path.join(__dirname, `../utils/config/form`, file), 'utf-8');
    let html = data.toString();
    html = html.replace(/ORDER_NO/g, orderInfo.orderNo);
    html = html.replace(/COMPANY_NAME/g, orderInfo.companyName);
    html = html.replace(/COMPANY_NO/g, orderInfo.companyNo);
    html = html.replace(/QUANTITY/g, orderInfo.quantity.toLocaleString('en-US'));
    html = html.replace(/VAT_AMOUNT/g, (orderInfo.amount * 0.1).toLocaleString('en-US'));
    html = html.replace(/TOTAL_AMOUNT/g, (orderInfo.amount + orderInfo.amount * 0.1).toLocaleString('en-US'));
    html = html.replace(/DEPOSIT_AMOUNT/g, (orderInfo.amount + orderInfo.amount * 0.1).toLocaleString('en-US'));
    html = html.replace(/AMOUNT/g, orderInfo.amount.toLocaleString('en-US'));
    html = html.replace(/ORDER_DATE/g, moment(orderInfo.createdAt).format('YYYY-MM-DD HH:mm:ss'));
    html = html.replace(/DEPOSIT_DATE/g, moment(orderInfo.depositAt).format('YYYY-MM-DD HH:mm:ss'));
    html = html.replace(/APPROVAL_DATE/g, moment(orderInfo.approvalAt).format('YYYY-MM-DD HH:mm:ss'));

    html = html.replace(/USER_ID/g, orderInfo.userid);
    html = html.replace(/USER_NAME/g, orderInfo.username);
    html = html.replace(/CELL_PHONE_NUMBER/g, orderInfo.cellPhoneNumber);
    html = html.replace(/E_MAIL/g, orderInfo.eMail);

    page.property('paperSize', {
      format: 'A4',
      orientation: 'portrait',
      margin: '0px'
    });
    await page
      .setContent(html, 'http://pgm.dohwa.co.kr/')
      .then(async function (status) {
        if (status == 'fail') {
          throw new Error('Invoice 생성 실패');
        }
        await page
          .render(path.join(__dirname, `../smtpAttachFiles/${orderInfo.orderNo}`, attachFile))
          .then(async function () {
            await instance.exit();
            isInvocie = true;
            console.log(`${attachFile} Invoice render. `);
          })
          .catch((e) => {
            console.log(e);
          });
        console.log(`${attachFile} Invoice 완료. `);
      })
      .catch((e) => {
        console.log(e);
      });

 

우분투 기반에서 작업하는 경우 한글이 안나올 때

한글이 아예 안나오거나 깨져서 나오는 경우 OS에 폰트가 없는 경우.

윈도우에서 작업 후 우분투 환경으로 배포하는 경우

C:\Windows\Fonts 폴더를 복사하여 windowFonts 폴더를 생성하여 /usr/share/fonts/windowFonts 로 복사한다.

 docker cp windowFonts/ server_pgmlog:/usr/share/fonts/windowFonts

 

읽어오려는 html 소스 상에서 에러가 나는 경우 render 실행 시 에러도 발생시키지 않음.

해당 페이지가 문제가 없는지 체크할 것

반응형