GuideHTML to PDFGenerate PDF

Generate a PDF with react-print

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.
  • react-print installed.

Guide

Write your react component:

1import React from 'react';
2// Define the HelloWorld component
3const HelloWorld = () => {
4 return (
5 <h1>Hello World!</h1>
6 );
7};
8// Export the HelloWorld component
9export default HelloWorld;

Compile it to HTML using react-print’s compile function:

1import { compile } from "@fileforge/react-print";
2import HelloWorld from "./HelloWorld";
3
4const HTML = await compile(<HelloWorld />);

Generate the PDF from your compiled HTML

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