Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a dashed or dotted line in jsPDF

I need to draw a dashed line in a PDF created using jsPDF (https://mrrio.github.io/jsPDF/doc/symbols/jsPDF.html)

A simple line is created as:

doc.line(20, 25, 60, 25);

http://jsfiddle.net/S3XRp/78/

How can I create a dashed or dotted line ?

like image 399
Uncoke Avatar asked Jan 03 '15 23:01

Uncoke


2 Answers

Later versions of jsPDF have a built-in function:

setLineDash [Docs]

The following, for example, draws a dashed line consiting of 10mm of line drawn, followed by 10mm of space repeating along the way from left to right. I've assumed you're drawing onto a page that has all the default settings (i.e. A4, mm units, etc):

doc.setLineDash([10, 10], 0);
doc.line(20, 25, 60, 25);

enter image description here

And the below will draw 7mm of line, 3mm of space, 1mm of line, 3mm of space and then repeats, however, it will start the pattern 10mm in so the first part of the dash to be drawn is the 1mm section:

doc.setLineDash([7, 3, 1, 3], 10);
doc.line(20, 25, 60, 25);

enter image description here

like image 124
Todd Avatar answered Sep 21 '22 13:09

Todd


I had the same problem, and did it like so:

/**
 * Draws a dotted line on a jsPDF doc between two points.
 * Note that the segment length is adjusted a little so
 * that we end the line with a drawn segment and don't
 * overflow.
 */
function dottedLine(doc, xFrom, yFrom, xTo, yTo, segmentLength)
{
    // Calculate line length (c)
    var a = Math.abs(xTo - xFrom);
    var b = Math.abs(yTo - yFrom);
    var c = Math.sqrt(Math.pow(a,2) + Math.pow(b,2));

    // Make sure we have an odd number of line segments (drawn or blank)
    // to fit it nicely
    var fractions = c / segmentLength;
    var adjustedSegmentLength = (Math.floor(fractions) % 2 === 0) ? (c / Math.ceil(fractions)) : (c / Math.floor(fractions));

    // Calculate x, y deltas per segment
    var deltaX = adjustedSegmentLength * (a / c);
    var deltaY = adjustedSegmentLength * (b / c);

    var curX = xFrom, curY = yFrom;
    while (curX <= xTo && curY <= yTo)
    {
        doc.line(curX, curY, curX + deltaX, curY + deltaY);
        curX += 2*deltaX;
        curY += 2*deltaY;
    }
}
like image 27
Florian Müller Avatar answered Sep 22 '22 13:09

Florian Müller