[英]How to render 1k pdf files using jsreport and jsreport Chrome Pdf?
我試圖使用Express.js生成端點報告,並使用Express.js生成端點,我在JSON中傳遞數組,API遍歷它並在forEach循環中使用,然后將每個對象用於抓取門戶,獲取響應,然后創建一個PDF文件...
這種方法是偽工作,但是我可以肯定存在一些並發問題...因為,如果我在JSON數組中傳遞2個項目,那么API可以毫無問題地創建2個PDF文件,但是如果我傳遞300個API,隨機創建50 ...或60或120。
這是我的jsreport配置
const jsReportConfig = {
extensions: {
"chrome-pdf": {
launchOptions: {
timeout: 10000,
args: ['--no-sandbox', '--disable-setuid-sandbox'],
},
},
},
tempDirectory: path.resolve(__dirname, './../../temporal/pdfs'),
templatingEngines: {
numberOfWorkers: 4,
timeout: 180000,
strategy: 'http-server',
},
};
我像這樣設置jsreport實例
jsreport.use(jsReportChrome());
jsreport.use(jsReportHandlebars());
jsreport.init()
而且,這就是我呈現報告的方式, checkInvoiceStatus
函數用作HTTP調用,該HTTP返回返回注入到Handlebars模板中的HTML響應。
const renderReports = (reporter, invoices) => new Promise(async (resolve, reject) => {
try {
const templateContent = await readFile(
path.resolve(__dirname, './../templates/hello-world.hbs'),
'utf-8',
);
invoices.forEach(async (invoice) => {
try {
const response = await checkInvoiceStatus(invoice.re, invoice.rr, invoice.id)
const $ = await cheerio.load(response);
const reporterResponse = await reporter.render({
template: {
content: templateContent,
engine: 'handlebars',
recipe: 'chrome-pdf',
name: 'PDF Validation',
chrome: {
displayHeaderFooter: true,
footerTemplate: '<table width=\'100%\' style="font-size: 12px;"><tr><td width=\'33.33%\'>{#pageNum} de {#numPages}</td><td width=\'33.33%\' align=\'center\'></td><td width=\'33.33%\' align=\'right\'></td></tr></table>',
},
},
data: {
taxpayerId: 'CAC070508MY2',
captcha: $('#ctl00_MainContent_ImgCaptcha').attr('src'),
bodyContent: $('#ctl00_MainContent_PnlResultados').html(),
},
});
reporterResponse.result.pipe(fs.createWriteStream(`./temporal/validatedPdfs/${invoice.id}.pdf`));
} catch (err) {
console.error(err);
reject(new Error(JSON.stringify({
code: 'PORTAL-PDFx001',
message: 'The server could not retrieve the PDF from the portal',
})));
}
});
resolve();
} catch (err) {
console.error(err);
reject(new Error(JSON.stringify({
code: 'PORTAL-PDFx001',
message: 'The server could not retrieve the PDF from the portal',
})));
}
});
我不知道為什么,但是此功能在500毫秒后終止,但是文件是在1分鍾后創建的...
app.post('/pdf-report', async (req, res, next) => {
const { invoices } = req.body;
repository.renderReports(reporter, invoices)
.then(() => res.status(200).send('Ok'))
.catch((err) => {
res.status(500).send(err);
});
});
UPDATE
除了@hurricane提供的代碼外,我還必須將jsReport配置更改為此
const jsReportConfig = {
chrome: {
timeout: 180000,
strategy: 'chrome-pool',
numberOfWorkers: 4
},
extensions: {
'chrome-pdf': {
launchOptions: {
timeout: 180000,
args: ['--no-sandbox', '--disable-setuid-sandbox'],
ignoreDefaultArgs: ['--disable-extensions'],
},
},
},
tempDirectory: path.resolve(__dirname, './../../temporal/pdfs'),
templatingEngines: {
numberOfWorkers: 4,
timeout: 180000,
strategy: 'http-server',
},
};
我認為在您的結構中,使用writeFileSync
函數而不是使用writeStream可以輕松解決問題。 但這並不意味着這是最好的方法。 因為您必須等待每個渲染和每個寫入文件進程開始另一個進程。 因此,我建議使用Promise.all
,以便您可以同時運行較長的流程。 這意味着您將只等待最長的過程。
快速獲勝-流程緩慢
reporterResponse.result.pipe
更改此行
fs.createFileSync(`./temporal/validatedPdfs/${invoice.id}.pdf`);
更好的方法-快速的過程
const renderReports = (reporter, invoices) => new Promise(async (resolve, reject) => {
try {
const templateContent = await readFile(
path.resolve(__dirname, './../templates/hello-world.hbs'),
'utf-8',
);
const renderPromises = invoices.map((invoice) => {
const response = await checkInvoiceStatus(invoice.re, invoice.rr, invoice.id)
const $ = await cheerio.load(response);
return await reporter.render({
template: {
content: templateContent,
engine: 'handlebars',
recipe: 'chrome-pdf',
name: 'PDF Validation',
chrome: {
displayHeaderFooter: true,
footerTemplate: '<table width=\'100%\' style="font-size: 12px;"><tr><td width=\'33.33%\'>{#pageNum} de {#numPages}</td><td width=\'33.33%\' align=\'center\'></td><td width=\'33.33%\' align=\'right\'></td></tr></table>',
},
},
data: {
taxpayerId: 'CAC070508MY2',
captcha: $('#ctl00_MainContent_ImgCaptcha').attr('src'),
bodyContent: $('#ctl00_MainContent_PnlResultados').html(),
},
});
});
const renderResults = await Promise.all(renderPromises);
const filewritePromises = results.map(renderedResult => await fs.writeFile(`./temporal/validatedPdfs/${invoice.id}.pdf`, renderedResult.content));
const writeResults = await Promise.all(filewritePromises);
resolve(writeResults);
} catch (err) {
console.error(err);
reject(new Error(JSON.stringify({
code: 'PORTAL-PDFx001',
message: 'The server could not retrieve the PDF from the portal',
})));
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.