n8n-nodes-openai-analytics
Version:
n8n node for OpenAI Analytics
139 lines • 6.04 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.convertHtmlToPdf = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const puppeteer = __importStar(require("puppeteer"));
async function convertHtmlToPdf(context) {
var _a, _b;
const { functionThis, i, items } = context;
try {
// 파라미터 가져오기
const htmlSource = functionThis.getNodeParameter('htmlSource', i);
let htmlContent = '';
if (htmlSource === 'binaryData') {
// 바이너리 데이터에서 HTML 읽기
const binaryPropertyName = functionThis.getNodeParameter('htmlBinaryPropertyName', i);
// 이진 속성이 존재하는지 확인
if (!items[i].binary || !((_a = items[i].binary) === null || _a === void 0 ? void 0 : _a[binaryPropertyName])) {
throw new Error(`No binary data found in property "${binaryPropertyName}"`);
}
// 바이너리 데이터를 문자열로 변환
const binaryData = (_b = items[i].binary) === null || _b === void 0 ? void 0 : _b[binaryPropertyName];
if (!binaryData) {
throw new Error(`Binary data in property "${binaryPropertyName}" is undefined`);
}
const binaryBuffer = Buffer.from(binaryData.data, 'base64');
htmlContent = binaryBuffer.toString('utf-8');
}
else {
// 직접 입력한 HTML 사용
htmlContent = functionThis.getNodeParameter('htmlContent', i);
}
// 선택된 파라미터 가져오기
const pageFormat = functionThis.getNodeParameter('pageFormat', i, 'a4');
const pageOrientation = functionThis.getNodeParameter('pageOrientation', i, 'portrait');
const includeBackground = functionThis.getNodeParameter('includeBackground', i, true);
const scale = functionThis.getNodeParameter('scale', i, 1);
const waitTime = functionThis.getNodeParameter('waitTime', i, 1000);
const outputPropertyName = functionThis.getNodeParameter('pdfBinaryPropertyName', i, 'data');
// 임시 HTML 파일 생성
const tempDir = os.tmpdir();
const tempHtmlPath = path.join(tempDir, `temp_${Date.now()}.html`);
const tempPdfPath = path.join(tempDir, `temp_${Date.now()}.pdf`);
fs.writeFileSync(tempHtmlPath, htmlContent, 'utf8');
// Puppeteer를 사용하여 HTML을 PDF로 변환
const browser = await puppeteer.launch({
headless: 'new',
args: ['--no-sandbox', '--disable-setuid-sandbox'],
});
try {
const page = await browser.newPage();
// HTML 파일 로드
await page.goto(`file://${tempHtmlPath}`, { waitUntil: 'networkidle0' });
// 모든 요소가 로드될 때까지 추가 대기 (사용자 설정 시간)
if (waitTime > 0) {
await page.waitForTimeout(waitTime);
}
// PDF 옵션 설정
const pdfOptions = {
path: tempPdfPath,
format: pageFormat,
landscape: pageOrientation === 'landscape',
printBackground: includeBackground,
scale: scale,
margin: {
top: '10mm',
right: '10mm',
bottom: '10mm',
left: '10mm',
},
};
// PDF 생성
await page.pdf(pdfOptions);
// PDF 파일 읽기
const pdfBuffer = fs.readFileSync(tempPdfPath);
// 바이너리 데이터 생성
const binaryData = await functionThis.helpers.prepareBinaryData(pdfBuffer, `report_${new Date().toISOString().replace(/[:\.]/g, '-')}.pdf`, 'application/pdf');
return {
json: {
success: true,
format: pageFormat,
orientation: pageOrientation,
size: pdfBuffer.length,
},
binary: {
[outputPropertyName]: binaryData,
},
};
}
finally {
// 브라우저 종료
await browser.close();
// 임시 파일 삭제
try {
fs.unlinkSync(tempHtmlPath);
fs.unlinkSync(tempPdfPath);
}
catch (error) {
// 임시 파일 삭제 오류는 무시
console.error('Failed to delete temporary files:', error);
}
}
}
catch (error) {
return {
json: {
success: false,
error: error.message,
stack: error.stack,
},
};
}
}
exports.convertHtmlToPdf = convertHtmlToPdf;
//# sourceMappingURL=convertHtmlToPdf.js.map