pdffillerjs / pdffiller

Take an existing PDF Form and data and PDF Filler will create a new PDF with all given fields populated.
MIT License
286 stars 113 forks source link

Read field values: attached an extension to your code to do this #70

Open calexanderbynum opened 6 years ago

calexanderbynum commented 6 years ago

Figured you might want to add this in. Super helpful for sending out fillable pdf's and then reading the data.

Some extras in here, such as the include, because I overrode your function with mine so when/if I update your code it won't break.

I am kinda bad at regex so please criticize and make changes as you see fit.

pdfFiller.generateFieldJson = function( sourceFile, nameRegex, callback){ var execFile = require('childprocess').execFile; var regName = /FieldName: ([^\n])/, regType = /FieldType: ([A-Za-z\t .]+)/, regFlags = /FieldFlags: ([0-9\t .]+)/, regValue = /FieldValue: ([A-Za-z0-9!@#$%^&()+-=[]{};':"\|,.<>\/?\t .]+)/, fieldArray = [], currField = {};

if(nameRegex !== null && (typeof nameRegex) == 'object' ) regName = nameRegex;

execFile( "pdftk", [sourceFile, "dump_data_fields_utf8"], function (error, stdout, stderr) {
    if (error) {
        console.log('exec error: ' + error);
        return callback(error, null);
    }

    fields = stdout.toString().split("---").slice(1);
    fields.forEach(function(field){
        currField = {};

        currField['title'] = field.match(regName)[1].trim() || '';

        if(field.match(regType)){
            currField['fieldType'] = field.match(regType)[1].trim() || '';
        }else {
            currField['fieldType'] = '';
        }

        if(field.match(regFlags)){
            currField['fieldFlags'] = field.match(regFlags)[1].trim()|| '';
        }else{
            currField['fieldFlags'] = '';
        }

        if(field.match(regValue)){
            currField['fieldValue'] = field.match(regValue)[1].trim()|| '';
        }else{
            currField['fieldValue'] = 'no match';
        }

        fieldArray.push(currField);
    });

    return callback(null, fieldArray);
});

};