Search code examples
javascriptpdfjspdf

How to use clip method in jsPDF?


I want to set lines inside to clipping region using jsPDF like below.

enter image description here

So, I called methods like blew. I Called .clip() after calling .lines() with a style argument of null like below.

var doc = new jsPDF();
doc.lines([[50, 0], [0, 50], [-50, 0], [0, -50]], 20, 20, [1.0, 1.0], null, true); // horizontal line
doc.clip();
doc.rect(50, 50, 100, 100, 'F');

I succeeded clipping lines!

But I cannot make clip regions more than one.

enter image description here


Solution

  • They actually fixed this one recently but apparently didn’t want to break the existing API, so they added a new method by the name clip_fixed:
    https://github.com/MrRio/jsPDF/commit/e32f0a2b222a940b0f228457371a118fc138ec28#diff-8162ee9f6251a2016741ffe67239c3c4

    Once you have drawn your clip path with a style object of null and called doc.clip_fixed(), all shapes you draw subsequently will be clipped to your current clip path.

    If afterwards you ever need to draw another shape without the clipping applied, you’ll realize that there is nothing like doc.unclip(). So your best option to draw unclipped shapes later on is to first save your current state to the Graphics State Stack before drawing your clip path, and when you’re done drawing your last clipped shape, restore the previous state from the stack. Unfortunately the API to this stack is not yet exposed via jsPDF, but you can get access to jsPDF’s internal command queue via doc.internal.write() to insert any PDF command that is not handled by jsPDF.

    So to create a reversable clipping you do:

    doc.internal.write('q'); // saves the currrent state
    // any draw command with a style value of null
    doc.clip_fixed();
    // any number of draw commands with strokes, fills, or null for compound paths
    doc.internal.write('Q'); // restores the state to where there was no clipping
    

    Further reading on clipping:
    http://www.verypdf.com/document/pdf-format-reference/pg_0234.htm