我正在尝试使用 puppeteer lib 动态创建 PDF 文件,但生成的 pdf 不使用自定义字体(.woff)而是使用默认系统字体,即 Times new roman。
我使用 Next.js 来创建网站,并做了一个相当棘手的设置来加载自定义字体和样式组件。最好是我不必弄乱 Nextjs 设置,但不管怎样让它工作。
我什至添加了延迟(超时),以确保在生成 pdf 之前正确下载字体,但徒劳无功。但是截屏显示正确的自定义字体。
下面是我用来创建 pdf 的代码。
puppeteer 代码:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({headless: true});
const page = await browser.newPage();
await page.goto('https://threads-web.vercel.app/threads/1385978750743973894', {
waitUntil: 'networkidle2',
});
// const document = await page.evaluate(() => document);
// console.log(document.fonts) ----- This also returns undefined
try {
await page.screenshot({ path: 'beforeTimeout.png' });
await page.waitForTimeout(15000);
await page.screenshot({ path: 'afterTimeOut.png' });
await page.evaluateHandle('document.fonts.ready');
await page.pdf({ path: 'hn.pdf', format: 'a4' });
}
catch (err) {
console.log(err)
}
await browser.close();
})();
Next.js:_app.jsconst GlobalStyle = createGlobalStyle`
@font-face {
font-family: 'ProximaNova-Regular';
src: url('/fonts/ProximaNova-Regular.woff') format('woff');
font-style: normal;
font-weight: 400;
font-display: swap;
}
@font-face {
font-family: 'ProximaNova-Bold';
src: url('/fonts/ProximaNova-Bold.woff') format('woff');
font-style: bold;
font-weight: 700;
font-display: swap;
}
`;
function MyApp({ Component, pageProps }) {
const [open, setOpen] = useState(false);
return (
<>
<ThemeProvider theme ={{colors: colors.light, bp: bp}}>
<GlobalStyle />
<Layout open={open} setOpen={setOpen}>
<Component {...pageProps} />
</Layout>
</ThemeProvider>
</>
);
}
任何帮助将不胜感激!谢谢!
最佳答案
文件: face.css
@font-face {
font-family: "MyFontRegular";
src: url("data:font/ttf;base64,--fontInBase64FontHere--");
}
注意:上面的“--fontInBase64FontHere--”是任何字体,如真字体,使用任何在线工具获取该数据并转换为base64格式。也与 Buffer.from("FontFileDataHere").toString('base64')
相同如果您需要动态,但静态转换更快。文件: main.js
import myFont from "./face.css";
const html = `
<style>
${myFont}
</style>
<div style="font-family: MyFontRegular">
Welcome to Ben's Minecraft
</div>
`;
// convert "html" to pdf code here
关于javascript - Puppeteer - 自定义字体未加载到 pdf 中,但确实出现在屏幕截图中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67353683/