Categories
JavaScript Answers Nodejs

How to Convert HTML to PDF with Node.js and JavaScript?

Sometimes, we want to convert HTML to PDF with Node.js and JavaScript.

In this article, we’ll look at how to convert HTML to PDF with Node.js and JavaScript.

Convert HTML to PDF with Node.js and JavaScript

To convert HTML to PDF with Node.js and JavaScript, we can use the html-pdf library.

To use the library, we first install it by running:

npm i html-pdf

Then, we can write:

const pdf = require('html-pdf');
const html = `<b>hello world</b>`
const options = {
  format: 'Letter'
}

pdf.create(html, options).toFile('./pdfname.pdf', (err, res) => {
  if (err) {
    console.log(err);
  }
});

to use it by importing the library.

Then we add the html variable with the HTML string that we want to convert to a PDF file.

Next, set the options variable to an object that has some options for how to render the PDF.

Then we call pdf.create with html and options to render the HTML into a PDF with the given options.

The toFile method takes the file path to save the PDF to and a callback that runs when the PDF conversion is done.

err is defined when there’s an error with converting the PDF.

Therefore, we should see hello world in bold in the rendered PDF.

Conclusion

To convert HTML to PDF with Node.js, we can use the html-pdf library.

Categories
Express JavaScript Answers

How to Add a Single Routing Handler for Multiple Routes in a Single Line with JavaScript Express?

Sometimes, we want to add a single routing handler for multiple routes in a single line with JavaScript Express.

In this article, we’ll look at how to add a single routing handler for multiple routes in a single line with JavaScript Express.

Add a Single Routing Handler for Multiple Routes in a Single Line with JavaScript Express

To add a single routing handler for multiple routes in a single line with Express, we can pass in an array of route path patterns that will be handled by one route handler.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000

const routes = ['/', '/foo', '/bar', '/baz/:id']
app.get(routes, (req, res) => {
  res.send('hello world')
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

We have the routes array that has strings with different route path patterns.

And we use it as the first argument of the app.get method.

Therefore, when we go to / , /foo , /bar or /baz with anything after it, we’ll see hello world displayed.

This also works with app.post , app.delete , app.put , and other route defining methods.

Conclusion

To add a single routing handler for multiple routes in a single line with Express, we can pass in an array of route path patterns that will be handled by one route handler.

Categories
Express JavaScript Answers

How to Accept Multiple URL Parameters in JavaScript Express Routes?

Sometimes, we want to accept multiple URL parameters in JavaScript Express routes.

In this article, we’ll look at how to accept multiple URL parameters in JavaScript Express routes.

Accept Multiple URL Parameters in JavaScript Express Routes

To accept multiple URL parameters in JavaScript Express routes, we can put them as the placeholders for each URL parameter in the route path string.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('hello world')
});

app.get('/fruit/:fruitName/:fruitColor', (req, res) => {
  const {
    fruitName,
    fruitColor
  } = req.params
  res.json({
    fruitName,
    fruitColor
  });
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

We add the ‘/fruit/:fruitName/:fruitColor’ route, where :fruitName and :fruitColor are the URL params placeholders.

We can get the values of them from the req.params object.

Then, we return the extracted parameter values in the response object with res.json .

So if we make a GET request to /fruit/apple/green , we see:

{
    "fruitName": "apple",
    "fruitColor": "green"
}

returned as the response.

Categories
JavaScript Answers

How to Use setTimeout Sequentially in JavaScript?

Sometimes, we want to use setTimeout sequentially in JavaScript.

In this article, we’ll look at how to use setTimeout sequentially in JavaScript.

Use setTimeout Sequentially in JavaScript

To use setTimeout sequentially in JavaScript, we can create a promise with a callback that calls setTimeout and use it multiple times.

For instance, we can write:

const sleep = (ms) => {
  return new Promise(resolve => setTimeout(resolve, ms));
}

(async () => {
  await sleep(100)
  await sleep(200)
})()

We create the sleep function that returns a promise we create with the Promise constructor.

The callback use resolve as the callback for setTimeout .

ms is the number of milliseconds to delay the call of resolve .

Then we create an async function that calls sleep with 100 and 200 milliseconds and call it immediately.

Conclusion

To use setTimeout sequentially in JavaScript, we can create a promise with a callback that calls setTimeout and use it multiple times.

Categories
JavaScript Answers

How to Resize Then Crop an Image with HTML Canvas and JavaScript?

Sometimes, we want to resize then crop an image with HTML canvas and JavaScript.

In this article, we’ll look at how to resize then crop an image with HTML canvas and JavaScript.

Resize Then Crop an Image with HTML Canvas and JavaScript

To resize then crop an image with HTML canvas and JavaScript, we can call the drawImage method with the original image with the coordinates of the boundaries of the image we want to crop.

For instance, if we have the following HTML:

Image: <br/>
<img src="https://i.stack.imgur.com/I4jXc.png" /><br/>
Canvas: <br/>
<canvas id="canvas" width="300" height="300"></canvas>

we write:

const image = new Image()
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d');

image.src = 'https://i.stack.imgur.com/I4jXc.png';

image.onload = () => {
  ctx.drawImage(image,
    70, 20,
    50, 50,
    0, 0,
    100, 100);
}

to do the cropping.

We create an image element with the Image constructor.

Then we get the canvas with document.getElementById .

Next, we get the canvas context with getContext .

Then we setr the src property of thr image to the image URL.

This will trigger the image.onload method to run.

In the onload method, we call drawImage with the

  • image
  • x and y coordinates of the top left corner
  • width of the part of the source image to get relative to the top left corner
  • height of part of source image to get relative to the top left corner
  • x and y coordinates of the top left corner of the cropped image
  • width and height of the cropped image

in this order.

Therefore, we should get the ‘o’ from the word ‘Google’ in the image.

Conclusion

To resize then crop an image with HTML canvas and JavaScript, we can call the drawImage method with the original image with the coordinates of the boundaries of the image we want to crop.