RAD Modules

RAD Modules

  • GitHub

›PDF

Documentation

  • Getting started

Security

  • Introduction
  • Getting started
  • Client
  • Api documentation
  • Keycloak integration
  • Advanced configuration
  • Attribute-based access control

Mailer

  • Introduction
  • Getting started
  • Client
  • Api documentation
  • Advanced configuration

Notifications

  • Notifications service
  • Getting started
  • Client
  • Api documentation
  • Advanced configuration

Scheduler

  • Introduction
  • Getting started
  • Client
  • Api documentation
  • Advanced configuration

PDF

  • Introduction
  • Getting started
  • Client
  • Api documentation
  • Advanced configuration

Serverless functions

  • Details
  • Create file
  • Get files
  • Delete file
  • Resize images
  • Watermark
  • RAD Security integration
  • Bitbucket pipelines

Admin panel

  • Introduction

Services communication

  • Communication between services

Changelog

  • Details

Getting started

PDF generator step by step

To start playing with the pdf generator service you need:

  1. The internet connection (only to pull docker images from dockerhub)
  2. Installed docker and docker-compose (optional but it will save you a lot of time)

After that please follow steps:

  1. Create a directory where we will be playing with the pdf service:
mkdir pdf-service-playground
  1. Go to the directory:
cd pdf-service-playground
  1. Create docker-compose.yml:
touch docker-compose.yml
  1. Open docker-compose.yml:
 open -e docker-compose.yml
  1. Copy and paste the example service configuration and save the file
version: "3.7"

services:    
  pdf:
    image: tshio/pdf:latest
    command: "api"
    ports:
      - 50080:50050    
  1. Run docker-compose:
 docker-compose up

Now you can go to http://localhost:50080/api-docs/#/ and check if everything works fine.

We can generate our first pdf from the pdf service:

  1. Click green bar, then "Try it out" button

  2. Past sample request body with required data

 {
  "from": "https://tc39.es/",
  "type": "uri",
  "pdfOptions": {
    "format": "A4"
  }
}
  1. Click "Execute" button

  2. Below you should receive a 201 (Created) response with should look like:

 {
  "url": "http://pdf:50050/api/download-pdf/75af8ef2-ec64-4a2a-b1f9-e503574a2ac5",
  "expiryAt": "2020-07-02T09:07:18.613Z"
}

If we want to check quickly how our pdf looks like, we need to open a postman and make a GET request to the URL from the request.

Note: Now we are working locally so the URL where we want to make request need to be changed from "pdf" to "localhost" and from "50050" to "50080". The URL should look like http://localhost:50080/api/download-pdf/75af8ef2-ec64-4a2a-b1f9-e503574a2ac5

After receiving response save it as PDF file (add .pdf at the end of the file name)

alt text

That was a manual way to download a PDF file from the URL. You can also put some HTML into requests and download the PDF. All steps are similar but the request should look like:

 {
  "from":"<p>Hello word from HTML</p>",
  "type":"html",
  "pdfOptions": {
    "format": "A4"
  }
}

Are there more properties in pdfOptions that I can edit?

As you can see above you can provide some PDF options to change the PDF file. Below you can check all available options:

 pdfOptions: {
        scale: number,
        displayHeaderFooter: boolean,
        headerTemplate: string, // valid parameters: ["date", "title", "url", "pageNumber", "totalPages"]
        footerTemplate: string, // valid parameters: ["date", "title", "url", "pageNumber", "totalPages"]
        printBackground: boolean,
        landscape: boolean,
        pageRanges: string,
        format: string, // valid parameters: ["Letter", "Legal", "Tabloid", "Ledger", "A0", "A1", "A2", "A3", "A4", "A5", "A6"]
        width: number,
        height: number,
        margin:{
          top: number,
          right: number,
          bottom: number,
          left: number,
        },
        preferCSSPageSize: boolean,
      },
}

How to generate PDF from website uri?

const body = {
      from: "https://tc39.es/",
      type: "uri",
      pdfOptions: {
        format: "A4"
      }
    }

const fileDownloadResponse = await fetch("http://pdf:50050/api/pdf/create-pdf", {
  method: "post",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(body),
});

How to generate PDF from custom HTML?

const body = {
      from: "<p>Hello World</p>",
      type: "html",
    };

const fileDownloadResponse = await fetch("http://pdf:50050/api/pdf/create-pdf", {
  method: "post",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(body),
});

I have a URL from PDF service what to do next?

Now when we received the URL from the PDF service, we need to fetch file content from the service and pipe it to response object in our app

const express = require("express");
const fetch = require("node-fetch");
const cors = require("cors");
const fs = require("fs");

const app = express();
app.use(cors());
app.use(express.json());

const port = 30002;

app.post("/api/generate-pdf", async (req, res) => {  
  try {
    const { url } = req.body;

    fetch(url)
      .then((fileContentResponse) => {
        res.setHeader("Content-Type", "application/pdf");
        res.setHeader(
          "Content-Disposition",
          `attachment: filename=test.pdf`
        );
        fileContentResponse.body.pipe(res);
        res.on("end", () => {
          res.send();
        });
      })
      .then((x) => console.log(x));

  } catch (err) {
    console.error(err);
    res.sendStatus(500);
  }
});

app.listen(port, () => console.log(`App listening on ${port}`));

How to use pdf generator in code?

Below is a simple express app with one endpoint to generate a PDF file from provided HTML. If you send a request to "localhost:30002/api/generate-pdf" you will be able to save response as a file. If you would call the endpoint from the client app you would receive the PDF file.

const express = require("express");
const fetch = require("node-fetch");
const cors = require("cors");
const fs = require("fs");

const app = express();
app.use(cors());
app.use(express.json());

const port = 30002;

app.post("/api/generate-pdf", async (req, res) => {  
  try {
    const body = {
      from: "<p>Hello World</p>",
      type: "html",
    };

    const fileDownloadResponse = await fetch("http://pdf:50050/api/pdf/create-pdf", {
      method: "post",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    });

    const json = await fileDownloadResponse.json();
    const { url } = json;

    fetch(url)
      .then((fileContentResponse) => {
        res.setHeader("Content-Type", "application/pdf");
        res.setHeader(
          "Content-Disposition",
          `attachment: filename=test.pdf`
        );
        fileContentResponse.body.pipe(res);
        res.on("end", () => {
          res.send();
        });
      })
      .then((x) => console.log(x));

  } catch (err) {
    console.error(err);
    res.sendStatus(500);
  }
});

app.listen(port, () => console.log(`App listening on ${port}`));
← IntroductionClient →
  • PDF generator step by step
  • Are there more properties in pdfOptions that I can edit?
  • How to generate PDF from website uri?
  • How to generate PDF from custom HTML?
  • I have a URL from PDF service what to do next?
  • How to use pdf generator in code?
RAD Modules
Docs
Getting startedChangelogRAD Modules API Doc
Services
SecurityMailerNotificationsServerless functionsSchedulerPdf generatorAdmin panel
Support:
GitHubhello@tsh.io
Copyright © 2021 The Software House