当我尝试在 Puppeteer 和 ejs 模板的帮助下打印 PDF 时,它迫不及待地等待解析路径。所以它会打印样式路径之前的页面,图像被解析。结果,它将只打印没有 CSS 和图像的数据
index.ejs
<head>
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<h2 class="fourth-one">Testing</h2>
<div class="logo-img">
<img style="margin-left: 200px;" src="/img/paybooks.jpg" width=300px height=250px>
</div>
</body>
脚本文件代码
const path = require('path');
const express = require('express');
require('dotenv').config();
const ejs = require('ejs');
const getSheetData = require('./googleSheetData');
const puppeteer = require('puppeteer');
const port = process.env.PORT;
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
app.set('views', 'views');
app.use('/testing', (req, res, next) => {
getSheetData()
.then((response) => {
for (let i = 1; i < response.length; i++) {
(async () => {
const browser = await puppeteer.launch();
const [page] = await browser.pages();
const html = await ejs.renderFile('views/index.ejs', {
data: response[i],
});
await page.setContent(html, { waitUntil: 'load' });
const pdf = await page.pdf({
path: `result-${i}.pdf`,
printBackground: true,
format: 'A4',
});
await browser.close();
})();
}
})
.catch((err) => {
console.log('Can not find data');
});
});
app.listen(port);
我尝试从互联网复制图片地址,它适用于该图片,但无法加载本地存储在同一文件夹中的图片
我的代码结构:
记住我在 app.js 中使用了
app.use(express.static(path.join(__dirname, 'public')));
所以不需要写完整的路径