I am attempting to convert a HTML file to PDF using Puppeteer and I want to save the converted PDF file absolutely to the root. (I am using MacOS btw).
export const HTML_PATH = path.resolve(
"/Users/me/dev/script/src/template/index.html",
);
This is the current method I am using to achieve this. Doing this gives me an error:
[Error: ENOENT: no such file or directory, open 'file://Users/me/TestDirectory/RandomName.pdf']
private async convertHtmlToPdf(config: Config, name: string) {
const browser = await puppeteer.launch({
headless: "new",
});
const page = await browser.newPage();
await page.setContent(fs.readFileSync(HTML_PATH, "utf-8"), {
waitUntil: "domcontentloaded",
});
await page.emulateMediaType("screen");
const pdf = await page.pdf({
format: "A4",
path: `file://Users/me/TestDirectory/${name}-${Math.round(
Math.random() * 50,
)}.pdf`,
printBackground: true,
});
await browser.close();
}
I have already tried:
path: /Users/me/TestDirectory/${name}.pdf
path: ~/TestDirectory/${name}.pdf
path: file://Users/me/TestDirectory/${name}.pdf
2
Answers
So I have found a workaround, which allows me to use absolute paths which may start with
~
.EDIT with Symbolic Link Example
Example:
PDF Absolute path:
/Users/me/TestDirectory/pdfs
Project Save Folder:
/Users/me/Projects/puppeteer-project/pdfs
Create a symbolic link (using both absolute paths):
Save into Project Save Folder with relative path:
If symbolic linking isn’t an option in your project, one last thing I could suggest is creating a script that runs after Puppeteer to just manually move (
mv
) or copy (cp -R
) the files after they are saved. Hope this helps, good luck.So I am able to replicate that same error when I try to use an absolute path when saving an image as well (used both macOS & Ubuntu). I think this is most likely intended to protect system files. However, I think there is another solution that may accomplish your task, but doesn’t use an absolute path. The answer to your question is that saving with an absolute path isn’t a good idea or requires very specific permissions/environment settings.
Instead of the absolute path, you could instead use a relative path that uses the
../
syntax to travel into the previous directory, or a symbolic link. Below is a snippet of my filepdfs.js
code to take PDF of a webpage.To run the code below, use this command:
node pdf.js https://example.com
There may also be another option to save outside of the project directory with sym links, but that is outside of this question scope.
Let me know if that helps out or not, good luck!