Skip to content

Save all documents - Nodejs

You can get a single document from your storage by calling the /v1/files/${id} endpoint with the GET method. If you do not specify an Accept header on the request or specify application/json you get the document information.

ts
const path = `/v1/files/${id}`;
const url = `${api_url}${path}`;
const method = "GET";
const headers = getAuthorizationHeaders(method, path);

const response = await fetch(url, {
  headers,
  method,
});

if (response.status !== 200) {
  const error = await getError(response);

  console.error(error);
  throw new Error(
    `Error "${JSON.stringify(error)}" calling UnoPdf API "GET ${url}".`,
  );
}

return response.json() as Promise<{ id: string; originalFileName: string }>;

If you specify application/pdf on the accept header you get the actual pdf.

ts
const path = `/v1/files/${pdfInfo.id}`;
const url = `${api_url}${path}`;
const method = "GET";
const headers = getAuthorizationHeaders(method, path);

// Add the Accept header with a value of `application/pdf` to download the document stream.
const response = await fetch(url, {
  headers: { ...headers, Accept: "application/pdf" },
  method,
});

if (response.status !== 200) {
  const error = await getError(response);

  console.error(error);
  throw new Error(
    `Error "${JSON.stringify(error)}" calling UnoPdf API "GET ${url}".`,
  );
}

if (response.body) {
  // In this example we add the datetime before the filename to make them unique between subsequent runs of this sample.
  // You might want to implement a better check/verification.
  const target = resolve(
    os.tmpdir(),
    new Date().toISOString().replaceAll(':', '_') + "-" + pdfInfo.originalFileName,
  );

  // Get the document stream from `response.body` and write it to a file.
  const fileStream = createWriteStream(resolve(target), {
    flags: "wx",
  });
  await finished(Readable.fromWeb(response.body).pipe(fileStream));
  console.log(`PDF document saved to ${target}`);
} else {
  console.error("No body");
}

In this code sample we upload one document and then retrieve that document from storage and save it to /tmp.

Code

ts
import dotenv from "dotenv";
import os from "os";
dotenv.config();

import { createWriteStream, readFileSync } from "node:fs";
import { finished } from "node:stream/promises";
import { Readable } from "node:stream";
import { resolve } from "node:path";

import { getError } from "./errorhandling";
import { getAuthorizationHeaders } from "./authorization";

const api_url = process.env.UNOPDF_API_URL;

async function postDocument() {
  const form = new FormData();
  const buffer = readFileSync("./classic-form-all-field-types.pdf");
  const filename = "classic-form-all-field-types.pdf";

  const blob = new Blob([buffer], { type: "application/pdf" });
  form.append("file", blob, filename);

  const path = "/v1/files";
  const url = `${api_url}${path}`;
  const method = "POST";
  const headers = getAuthorizationHeaders(method, path);

  const response = await fetch(url, {
    headers,
    method,
    body: form,
  });

  if (response.status !== 200) {
    const error = await getError(response);

    console.error(error);
    throw new Error(`Error "${error}" calling UnoPdf API "${method} ${url}".`);
  }

  return (await response.json()) as Promise<{ id: string }>;
}

async function getDocument(id: string) {
  // #region get-document-info
  const path = `/v1/files/${id}`;
  const url = `${api_url}${path}`;
  const method = "GET";
  const headers = getAuthorizationHeaders(method, path);

  const response = await fetch(url, {
    headers,
    method,
  });

  if (response.status !== 200) {
    const error = await getError(response);

    console.error(error);
    throw new Error(
      `Error "${JSON.stringify(error)}" calling UnoPdf API "GET ${url}".`,
    );
  }

  return response.json() as Promise<{ id: string; originalFileName: string }>;
  // #endregion get-document-info
}

async function saveDocument(pdfInfo: { id: string; originalFileName: string }) {
  // #region get-document-stream
  const path = `/v1/files/${pdfInfo.id}`;
  const url = `${api_url}${path}`;
  const method = "GET";
  const headers = getAuthorizationHeaders(method, path);

  // Add the Accept header with a value of `application/pdf` to download the document stream.
  const response = await fetch(url, {
    headers: { ...headers, Accept: "application/pdf" },
    method,
  });

  if (response.status !== 200) {
    const error = await getError(response);

    console.error(error);
    throw new Error(
      `Error "${JSON.stringify(error)}" calling UnoPdf API "GET ${url}".`,
    );
  }

  if (response.body) {
    // In this example we add the datetime before the filename to make them unique between subsequent runs of this sample.
    // You might want to implement a better check/verification.
    const target = resolve(
      os.tmpdir(),
      new Date().toISOString().replaceAll(':', '_') + "-" + pdfInfo.originalFileName,
    );

    // Get the document stream from `response.body` and write it to a file.
    const fileStream = createWriteStream(resolve(target), {
      flags: "wx",
    });
    await finished(Readable.fromWeb(response.body).pipe(fileStream));
    console.log(`PDF document saved to ${target}`);
  } else {
    console.error("No body");
  }
  // #endregion get-document-stream
}

// We first create a document, get the info for that document and finally download it again.

postDocument()
  .then(({ id }) => getDocument(id))
  .then((pdfInfo) => saveDocument(pdfInfo));

Running the example

  • Download the rest - Save all documents - Nodejs project
  • Unzip the file to a directory rest-save-a-document-nodejs.
    shell
    unzip rest-save-a-document-nodejs.zip -d rest-save-a-document-nodejs
  • Open a terminal and go to that directory
    shell
    cd rest-save-a-document-nodejs
  • Install dependencies
    shell
    npm install
    shell
    yarn
  • Start the project
    shell
    npm run start
    shell
    yarn start