GuideHTML to PDFGenerate PDF

Generate a local PDF

This documentation provides an example of how to use the FileforgeClient to generate a hosted PDF file from HTML.

Prerequisites

Ensure you have the following:

  • An API key for Fileforge as an environment variable: process.env.FILEFORGE_API_KEY
  • Node.js and npm installed.
  • The Fileforge Client installed.

Guide

Write your HTML content

1// HTML content with an embedded image
2const HTML = `<!DOCTYPE html>
3<html>
4 <head>
5 <title>My First Document</title>
6 </head>
7 <body>
8 <h1>Hello World!</h1>
9 </body>
10</html>
11`

Set the host property to false (default)

By setting the options.host property to false, the Fileforge API will now return a stream of your file.

Generate the PDF

The client returns a PDF object with the URL to the hosted PDF file as pdf.url.

1import { FileforgeClient } from "@fileforge/client";
2import * as fs from "fs";
3
4const ff = new FileforgeClient({
5 apiKey: process.env.FILEFORGE_API_KEY,
6});
7
8(async () => {
9 try {
10 const pdfStream = await ff.pdf.generate(
11 [
12 new File([HTML],"index.html",{
13 type: "text/html",
14 },
15 ),
16 ],
17 {
18 options: {
19 host: false, // default
20 },
21 },
22 {
23 timeoutInSeconds: 30,
24 },
25 );
26 pdfStream.pipe(fs.createWriteStream("./result.pdf"));
27 } catch (error) {
28 console.error("Error during PDF conversion:", error);
29 }
30})();