12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- import puppeteer from "puppeteer-core";
- import fs from "node:fs";
- import path from "node:path";
- import { fileURLToPath } from "node:url";
- async function run(fileName) {
- console.log(7, fileName);
- const pdfName = `${fileName}`.replace(".html", ".pdf");
- try {
- const browser = await puppeteer.launch({
- // executablePath: '/Applications/Google\ Chrome.app/Contents/MacOS/bin',
- executablePath:
- "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
- // ignoreHTTPSErrors: false, // 在导航期间忽略 HTTPS 错误
- // headless: false,
- defaultViewport: {
- // 为每个页面设置一个默认视口大小
- width: 1240,
- height: 1080,
- },
- });
- const page = await browser.newPage();
- // await page.goto(`file://${process.env.PWD}/${fileName}`);
- await page.goto(`file://${fileName}`);
- let inputElement = await page.$("html");
- const offsetHeight = await page.evaluate(
- () => document.querySelector("body").offsetHeight
- );
- console.log(offsetHeight, 21);
- console.log(inputElement);
- try {
- fs.unlinkSync(pdfName);
- } catch (e) {
- console.log(e);
- }
- await page.pdf({
- path: pdfName,
- height: offsetHeight + 110,
- width: 1240,
- margin: { left: 20, top: 20, right: 20, bottom: 20 },
- printBackground: true
- });
- // await page.pdf({path: 'index_002.pdf', format:'A4'})
- await browser.close();
- } catch (e) {
- console.log(e);
- }
- }
- export default run;
- // const filePath = path.join(__dirname, "index.html")
- // console.log(35, filePath)
- // const __filename = fileURLToPath(import.meta.url);
- //
- // // 👇️ "/home/john/Desktop/javascript"
- // const __dirname = process.cwd()
- // console.log('directory-name 👉️', __dirname);
- //
- // console.log('2222', process.execPath)
- // console.log('2222', process.cwd())
|