How can I create a linearGradient with pdfkit

I was looking for and example on how to use linearGradient with pdfkit - see https://github.com/devongovett/pdfkit/issues/95 "Use doc.linearGradient and doc.radialGradient to create a gradient object, passing in the required parameters. Then call the stop method on the object to add color stops. Finally, set the fillColor to the gradient object."

This is the example I crafted:

doc.rect(50, 50, 100, 100)
      .linearGradient(60, 60, 90, 90)
      .stop([100, 100], "blue")
      .fillColor("red", 1)

But I get a compile error:

node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
TypeError: Object #<PDFLinearGradient> has no method 'fillColor

'

Thanks!

You are close. The error was because the linearGradient function returns a PDFLinearGradient object, and since you chained everything, the fillColor method is being called on the gradient rather than the document as you intended.

Also, the gradient stop method takes a percentage (from 0 to 1) along the line created between the two points (x1, y1) to (x2, y2) rather than an explicit position.

Here's a working example:

var grad = doc.linearGradient(x1, y1, x2, y2);
grad.stop(0, '#000');
grad.stop(1, '#fff');
doc.fillColor(grad);

why don't you use css?

something like:

background-image: linear-gradient(left , rgb(48,58,242) 14%, rgb(235,156,120) 62%);
background-image: -o-linear-gradient(left , rgb(48,58,242) 14%, rgb(235,156,120) 62%);
background-image: -moz-linear-gradient(left , rgb(48,58,242) 14%, rgb(235,156,120) 62%);
background-image: -webkit-linear-gradient(left , rgb(48,58,242) 14%, rgb(235,156,120) 62%);
background-image: -ms-linear-gradient(left , rgb(48,58,242) 14%, rgb(235,156,120) 62%);

background-image: -webkit-gradient(
    linear,
    left top,
    right top,
    color-stop(0.14, rgb(48,58,242)),
    color-stop(0.62, rgb(235,156,120))
);

adjusted to your needs of course

but according to the docs pdfkit does support both linear and radial gradients - maybe try the latest download.