javascriptjspdf

Create radio button using jsPDF


I am using jsPdf to generate a pdf on a client side , the documentation is really confusing me. I want to insert a radio button on the pdf. On the official docs there is AcroFormRadioButton Class, that list the constructor and Function Members of this classes, i am not able to create a new object using the constructor on the Documentation. i found a code that can create a new radio button, but i didn't understand it :

      var doc =  new jsPDF('p', 'pt', [ 595.28,  841.89])
      doc.setFontSize(10);
      doc.text(87.03635, 24.691223, 'Original');
      var radioGroup = new RadioButton();
      radioGroup.V = "/Test";
      radioGroup.Subtype = "Form";
      doc.addField(radioGroup);
      var radioButton1 = radioGroup.createOption("Test");
      radioButton1.Rect = [87.0363, 24.691223, 20, 20];
      radioButton1.AS = "/Test";
      radioGroup.setAppearance(AcroForm.Appearance.RadioButton.Circle);
      doc.save('Test.pdf');

on the offical docs i cant found RadioButton() constructor and the methods used to create the radiobutton, i looked on source code of jsPDF, but same issue.

Where i should look on the documentation/source of jsPdf, to understand this code.


Solution

  • This demo site is super helpful - http://raw.githack.com/MrRio/jsPDF/master/

    In the dropdown, select AcroForms and it runs through a quick and dirty setup for each form element.

    Here's the short version:

    /* global jsPDF */
    var doc = new jsPDF();
    var {
      RadioButton,
      Appearance
    } = jsPDF.AcroForm;
    
    
    doc.text("RadioGroup:", 50, 165);
    var radioGroup = new RadioButton();
    radioGroup.value = "Test";
    radioGroup.Subtype = "Form";
    
    doc.addField(radioGroup);
    
    var radioButton1 = radioGroup.createOption("Test");
    radioButton1.Rect = [50, 170, 30, 10];
    radioButton1.AS = "/Test";
    
    var radioButton2 = radioGroup.createOption("Test2");
    radioButton2.Rect = [50, 180, 30, 10];
    
    var radioButton3 = radioGroup.createOption("Test3");
    radioButton3.Rect = [50, 190, 20, 10];
    
    radioGroup.setAppearance(Appearance.RadioButton.Cross);
    

    I needed to alter the imports and use of constructors a bit:

    // import
    const jsPDF = require('jspdf');
    const doc = jsPDF('p', 'pt'); 
    
    // then using the radio button constructor
    var radioGroup = new doc.AcroFormRadioButton();
    
    // and using 'appearance'
    radioGroup.setAppearance(doc.AcroFormAppearance.RadioButton.Cross);
    

    Hope that helps.