New: PDF/A-3b conversion with a compliance report included.See Docs

Convert Webpage to PDF Online Using PDF.co

10 Minutes Read

Use PDF.co’s Webpage to PDF API to save an accessible webpage as a PDF. This tutorial uses Node.js to request the conversion, read the complete API response, and download the generated file.

Prerequisites

The example uses Node.js’s built-in fetch, so no additional packages are required.

Step 1: Set Your API Key

Set PDFCO_API_KEY in the terminal where you will run the script.

On macOS or Linux:

export PDFCO_API_KEY="YOUR_PDFCO_API_KEY"

In PowerShell:

$env:PDFCO_API_KEY = "YOUR_PDFCO_API_KEY"

Use your own key and keep it out of published code or shared repositories.

Step 2: Create the Conversion Script

Save the following code as webpage-to-pdf.cjs. Replace the Wikipedia URL with the webpage you want to convert.

const { writeFile } = require("node:fs/promises");

async function main() {
  const apiKey = process.env.PDFCO_API_KEY;
  if (!apiKey) throw new Error("Set PDFCO_API_KEY first.");

  const response = await fetch(
    "https://api.pdf.co/v1/pdf/convert/from/url",
    {
      method: "POST",
      headers: {
        "x-api-key": apiKey,
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        url: "https://en.wikipedia.org/wiki/Style_sheet_(web_development)",
        name: "result.pdf",
        async: false
      }),
      signal: AbortSignal.timeout(60000)
    }
  );

  const result = await response.json();

  if (!response.ok || result.error || !result.url || result.jobId) {
    throw new Error(
      result.message ||
      "No completed synchronous PDF result was returned."
    );
  }

  const output = await fetch(result.url, {
    signal: AbortSignal.timeout(60000)
  });

  if (!output.ok) {
    throw new Error(`Download failed: ${output.status}`);
  }

  await writeFile(
    "result.pdf",
    Buffer.from(await output.arrayBuffer())
  );

  console.log("Saved result.pdf. Open it to verify the rendered page.");
}

main().catch(error => {
  console.error(error.message);
  process.exitCode = 1;
});

The script sends a POST request to the Webpage to PDF endpoint. The API key authenticates that request; it is not included in the subsequent PDF download request.

await response.json() reads the complete response body before parsing it, so JSON split across multiple network chunks is handled correctly.

Step 3: Run the Script

From the folder containing the script, run:

node webpage-to-pdf.cjs

On success, the script saves result.pdf in the current working directory. An existing file with that name will be replaced.

This example uses synchronous conversion. For longer conversions, adapt it to the asynchronous workflow with job-status checks. A client-side timeout does not establish whether processing stopped on the server.

Step 4: Check the Rendered Layout

Open result.pdf and compare it with the content you need to preserve.

Login screens, blocked resources, print CSS, and dynamic page behavior can affect the result. Check that images and fonts load correctly and that page breaks do not hide important content.

You can adjust settings such as:

  • paperSize: For example, A4 or Letter.
  • orientation: Portrait or Landscape.
  • margins: For example, 10mm.
  • printBackground: Whether to include background colors and images.
  • mediaType: Whether to use print or screen styles.

Add the settings you need to the request body. See the endpoint documentation for available options.

Frequently Asked Questions

How can I save a webpage as a PDF?

Pass its URL to the Webpage to PDF endpoint and inspect the result. The converter must be able to load the page and its required resources. File size and appearance depend on the content and rendering settings.

What if I already have the HTML?

Use the HTML to PDF operation for raw HTML markup. After conversion, download the PDF or pass its output URL to your storage or delivery step before the temporary link expires.

Related Tutorials

See Related Tutorials