DOCX to PDF with variables

This documentation provides an example of how to use the FileforgeClient to convert a DOCX with variables into PDF.

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

1

Write your DOCX document with a variable (optional)

sample docx file

2

Write the templateLiterals object with the variable to replace

1"templateLiterals": {
2 "replace_me": "John Doe",
3}
3

Generate the PDF

The templateLiterals object is passed in the options parameter. Please note that the options parameter is optional in the event where your document has no variables. The document is returned as a stream, which can be piped to a file or other writable stream.

1import { FileforgeClient } from "@fileforge/client";
2import * as fs from "fs";
3
4(async () => {
5 const ff = new FileforgeClient({
6 apiKey: process.env.FILEFORGE_API_KEY,
7 });
8
9 try {
10 const docxFile = fs.createReadStream(
11 __dirname + "/samples/document-simple.docx",
12 );
13 const pdfStream = await ff.pdf.fromDocx(
14 docxFile,
15 {
16 options:{
17 "templateLiterals": {
18 "replace_me": "John Doe",
19 }
20 }
21 },
22 {
23 timeoutInSeconds: 30,
24 },
25 );
26
27 pdfStream.pipe(fs.createWriteStream("./result_docx.pdf"));
28 console.log("PDF conversion successful. Stream ready.");
29
30 } catch (error) {
31 console.error("Error during PDF conversion:", error);
32 throw error;
33 }
34 })();