summaryrefslogtreecommitdiff
path: root/lib/pdftron/serverSDK/createBasicContractPdf.ts
blob: 706508e645aaafb891c9f72d5d32a8439dd9dabc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
const { PDFNet } = require("@pdftron/pdfnet-node");
const fs = require('fs').promises;
const path = require('path');
import { file as tmpFile } from "tmp-promise";

type CreateBasicContractPdf = (
  templateBuffer: Buffer,
  templateData: {
    [key: string]: any;
  }
) => Promise<{
  result: boolean;
  buffer?: ArrayBuffer;
  error?: any;
}>;

export const createBasicContractPdf: CreateBasicContractPdf = async (
  templateBuffer,
  templateData
) => {

  const result = await PDFNet.runWithCleanup(async () => {
    console.log("πŸ”„ PDFTron κΈ°λ³Έκ³„μ•½μ„œ PDF λ³€ν™˜ μ‹œμž‘");
    console.log("πŸ“ ν…œν”Œλ¦Ώ 데이터:", JSON.stringify(templateData, null, 2));

    // μž„μ‹œ 파일 생성
    const { path: tempDocxPath, cleanup } = await tmpFile({
      postfix: ".docx",
    });

    try {
      // ν…œν”Œλ¦Ώ 버퍼λ₯Ό μž„μ‹œ 파일둜 μ €μž₯
      await fs.writeFile(tempDocxPath, templateBuffer);

      let resultDoc;

      // ν…œν”Œλ¦Ώ 데이터가 μžˆλŠ” 경우 λ³€μˆ˜ μΉ˜ν™˜, μ—†μœΌλ©΄ λ‹¨μˆœ λ³€ν™˜
      if (templateData && Object.keys(templateData).length > 0) {
        console.log("πŸ”„ ν…œν”Œλ¦Ώ λ³€μˆ˜ μΉ˜ν™˜ μ‹œμž‘");
        
        const template = await PDFNet.Convert.createOfficeTemplateWithPath(
          tempDocxPath
        );
        resultDoc = await template.fillTemplateJson(
          JSON.stringify(templateData)
        );
        
        console.log("βœ… ν…œν”Œλ¦Ώ λ³€μˆ˜ μΉ˜ν™˜ 및 PDF λ³€ν™˜ μ™„λ£Œ");
      } else {
        console.log("πŸ“„ λ‹¨μˆœ PDF λ³€ν™˜ μˆ˜ν–‰");
        
        resultDoc = await PDFNet.Convert.office2PDF(tempDocxPath);
        
        console.log("βœ… λ‹¨μˆœ PDF λ³€ν™˜ μ™„λ£Œ");
      }

      const buffer = await resultDoc.saveMemoryBuffer(
        PDFNet.SDFDoc.SaveOptions.e_linearized
      );

      return {
        result: true,
        buffer,
      };
      
    } finally {
      // μž„μ‹œ 파일 정리
      await cleanup();
    }
  },
    process.env.NEXT_PUBLIC_PDFTRON_SERVER_KEY
  );
  return result;
};