New: PDF to E-Invoice for Factur-X/ZUGFeRD, and PDF to PDF/A for archive-ready PDF/A-3b.

Convert a Base64-Encoded Image to PDF in JavaScript Using PDF.co

This tutorial uploads a Base64-encoded PNG or JPEG image, converts it to PDF asynchronously, and downloads the finished file.

Step 1: Prepare Your Project

Install a supported Node.js version. Create a project folder and run:

npm init -y
npm install axios

Save your image’s Base64 content in a text file named image-base64.txt. It can contain either raw Base64 or a data URL such as data:image/png;base64,....

Step 2: Add the JavaScript Code

Create index.js and paste the following code.

Replace the API key placeholder with your key from the PDF.co dashboard. Set IMAGE_NAME to match the encoded image’s format.

const axios = require("axios");
const fs = require("node:fs/promises");
const { setTimeout: delay } = require("node:timers/promises");

const API_KEY = "YOUR_PDFCO_API_KEY";
const INPUT_FILE = "image-base64.txt";
const IMAGE_NAME = "source.png"; // Use source.jpg for a JPEG.
const OUTPUT_FILE = "result.pdf";

const api = axios.create({
  baseURL: "https://api.pdf.co/v1",
  headers: {
    "x-api-key": API_KEY,
    "Content-Type": "application/json"
  },
  timeout: 60000
});

async function post(path, payload) {
  const { data } = await api.post(path, payload);

  if (data.error) {
    throw new Error(data.message || `Request failed: ${path}`);
  }

  return data;
}

async function waitForResult(jobId, initialUrl) {
  for (let attempt = 0; attempt < 60; attempt++) {
    await delay(3000);

    const result = await post("/job/check", { jobid: jobId });

    if (result.status === "success") {
      const url = result.url || initialUrl;

      if (!url) {
        throw new Error("The completed job has no output URL.");
      }

      return url;
    }

    if (result.status !== "working") {
      throw new Error(
        result.message || `Job ended with status: ${result.status}`
      );
    }
  }

  throw new Error(
    `Stopped waiting for job ${jobId}. The server job may still be running.`
  );
}

async function main() {
  const input = (await fs.readFile(INPUT_FILE, "utf8")).trim();

  const base64 = input
    .replace(/^data:image\/[^;]+;base64,/i, "")
    .replace(/\s/g, "");

  if (!base64) {
    throw new Error("The input file contains no Base64 data.");
  }

  const uploaded = await post("/file/upload/base64", {
    file: base64,
    name: IMAGE_NAME
  });

  if (!uploaded.url) {
    throw new Error("The upload returned no file URL.");
  }

  const conversion = await post("/pdf/convert/from/image", {
    url: uploaded.url,
    name: OUTPUT_FILE,
    async: true
  });

  if (!conversion.jobId) {
    throw new Error("The conversion returned no job ID.");
  }

  console.log(`Processing job: ${conversion.jobId}`);

  const outputUrl = await waitForResult(
    conversion.jobId,
    conversion.url
  );

  // Download without sending the PDF.co API key to the file server.
  const download = await axios.get(outputUrl, {
    responseType: "arraybuffer",
    timeout: 60000
  });

  await fs.writeFile(OUTPUT_FILE, Buffer.from(download.data), {
    flag: "wx"
  });

  console.log(`Saved ${OUTPUT_FILE}`);
}

main().catch((error) => {
  // Avoid logging the full Axios error, which may include request headers.
  const message = error.response?.data?.message || error.message;
  console.error(message);
  process.exitCode = 1;
});

Keep your API key private and do not place it in browser-side JavaScript or a public repository.

Step 3: Run the Program

With both files in your project folder, run:

node index.js

The script performs four operations:

  1. Uploads the image through Upload File Using Base64.
  2. Starts an asynchronous Image-to-PDF conversion.
  3. Checks the background job status until processing finishes.
  4. Downloads the PDF as result.pdf.

Step 4: Review the PDF

Open result.pdf and confirm that the image appears correctly.

The sample avoids overwriting an existing file. Move or rename a previous result.pdf before running it again.

If your Base64 content already represents a PDF, it only needs decoding or uploading as a PDF; the image-conversion step is unnecessary.

In this tutorial, you learned how to convert Base64 to PDF in JavaScript using the PDF.co Web API with asynchronous processing. You saw how to upload Base64 content and convert an image to a PDF. Asynchronous processing enables efficient handling of large files, providing a seamless experience for long-running tasks.

For more details on implementing asynchronous processing, refer to the official PDF.co Asynchronous Processing Documentation.

Related Tutorials

See Related Tutorials