[PDF] Set KM Variables to PDF Extracted Form Fields [Example]

###MACRO:   [PDF] Set KM Variables to PDF Extracted Form Fields [Example]

~~~ VER: 1.0.1    2016-10-08 ~~~

  • UPDATE: Choose File script is now embedded in the Macro Action

####DOWNLOAD:
[PDF] Set KM Variables to PDF Extracted Form Fields [Example].kmmacros (33 KB)


###ReleaseNotes

Author.@JMichaelTX

PURPOSE:

  • Extract PDF Form Fields from text, and create a KM Variable for each Field, set to the value of the field.

HOW TO USE:

  1. User will be prompted to choose SOURCE text from any of the following:
  • Selection
  • Clipboard
  • File (using Choose File dialog)
    .
  1. Run the Macro, and choose your source
    .
  2. KM Variables are created, and the results are displayed

SOURCE DATA ISSUES:
The example source text provided in the below reference has these issues:

  1. Some PDF FieldNames contain dashes ("-"), which are NOT allowed in KM Variable names
  • All dashes are replaced with underscores ("_")
  1. All of the PDF Field blocks are terminated with a "---", except for the last block.
  • This has been handled in the RegEx pattern.
  1. Some of the PDF Field blocks do NOT have a "FieldValue" attribute.
  • These are set to the empty string "".

REF:

TAGS: @PDF @File @Variable @Script @JXA

USER SETTINGS:

  • Any Action in magenta color is designed to be changed by end-user
  • The user need to ADD KM Actions to process the extracted PDF data that is now in KM Variables. All of these variables have a prefix of "PDF__".

ACTION COLOR CODES

  • To facilitate the reading, customizing, and maintenance of this macro,
    key Actions are colored as follows:
  • GREEN -- Key Comments designed to highlight main sections of macro
  • MAGENTA -- Actions designed to be customized by user
  • YELLOW -- Primary Actions (usually the main purpose of the macro)
  • ORANGE -- Actions that permanently destroy Varibles or Clipboards

REQUIRES:
(1) Keyboard Maestro Ver 7.2.1+
(2) Yosemite (10.10.5)+

By downloading or installing this software, you agree to the terms of usage in the below Action labeled "License and Usage Agreement".  
Do not install or use if you do not agree.

###Example Results


###Macro Image


###Script
Here is the script for the Choose File action.

// SET JavaScript STRICT MODE for ALL Code/Functions in this script
// See bottom of this document for details
'use strict';
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

(function chooseFileKM() {    // ~~~ automatically executed when this script is executed ~~~
  
var ptyScriptName   = "Choose File"
var ptyScriptVer     = "1.1"
var ptyScriptDate   = "2016-10-08"
var ptyScriptAuthor = "JMichaelTX"
/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PURPOSE:  Allow User to Choose File from Popup Window

RETURNS:  One of these, as text:
  • Actual Results of script if all goes well
    • POSIX path to selected file
    
  • "[USER_CANCELED]" at start of results if the user canceled something
  • "[ERROR]" at start of results if a script error occurred.
  
AUTHOR:  @JMichaelTX

KM VARIABALES REQUIRED:
  • SCPT__ParentFolder         [optional]: "~/Documents"
  • SCPT__ChooseFilePrompt  [optional]: "Choose FILE for KM Macro"
  
KM VARIABLES SET:
  • SCPT__ScriptLog    Logs each run of the script.  KM Var may be deleted by user.
  
TAGS:  @File @Prompt @Choose @Script @KM @JXA

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

var returnResults = "TBD"  // Set your results to this var


try {
  //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  
  // --- SET CURRENT APP VARIABLE NEEDED FOR DIALOGS & StandardAdditions.osax ---
  var app = Application.currentApplication()
  app.includeStandardAdditions = true
  
  //--- SET SYSTEM UI SERVER FOR USE WITH DIALOGS IN KM ---
  var susApp = Application('SystemUIServer');
  susApp.includeStandardAdditions = true;


  updateKMScriptLog(ptyScriptName, "Start Script");
  
  // --- SET KME APP VARIABLE NEEDED TO GET/SET KM VARIABLES ---
  //      (remove if not needed)
  var kme = Application("Keyboard Maestro Engine");
  
  //--- ACTIVATE SAFARI DEBUGGER IS KM VAR IS SET ---
  var debugBool = kme.getvariable("ScriptDebug");    // To debug, set to one of these: yes|on|true
  debugBool = RegExp(/yes|on|true/i).test(debugBool) ? true : false;
  if (debugBool) {
    debugger;
  }

  //--- GET KM VARIABLES ---  
  var defaultFolderPath = kme.getvariable("SCPT__ParentFolder") || "~/Documents";
  var choosePrompt       = kme.getvariable("SCPT__ChooseFilePrompt") || "Choose FILE for KM Macro";


  defaultFolderPath = defaultFolderPath.replace("~", app.pathTo("home folder").toString())
  
  susApp.activate();
  
  var myFile = susApp.chooseFile({ 
    withPrompt:       choosePrompt,
    defaultLocation:   defaultFolderPath })
    
    // ofType: ['public.jpeg', 'public.png']
    
  returnResults = myFile.toString();
  
  //~~~~ END TRY ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

} catch (oError) {
  
  console.log(oError);
  var msgLog;
  
  if (oError.errorNumber === -128) {  // User Canceled
  
    returnResults =  "[USER_CANCELED]\n\n"
      + "SCRIPT: " + ptyScriptName + "   Ver: " + ptyScriptVer;
      
    msgLog = "User Canceled";
  }
  
  else {
    returnResults = "[ERROR]\n\n"
      + "SCRIPT: " + ptyScriptName + "   Ver: " + ptyScriptVer + "\n"
      + "Error Number: " + oError.errorNumber + "\n"
      + oError.message
      
    msgLog = oError.message;
    
  } // END if/else
  
  try {
      updateKMScriptLog(ptyScriptName, "[ERROR]\t" + msgLog);
  } catch (err) {
  }
  
} // END catch
//~~~~ END TRY/CATCH BLOCK ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

return returnResults

//======================== END OF MAIN SCRIPT =============================================


//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function toISOFormat(pDate) {
/*      Ver 1.0    2016-10-07
---------------------------------------------------------------------------------
  PURPOSE:  Convert JS Date Object to ISO Format in LOCAL Time Zone
  PARAMETERS:
    • pDate    | date  |  The DATE to convert;  Default:  new Date()
  RETURNS:  String of Date/Time:  YYYY-MM-DD HH:MM:SS
  
  AUTHOR:  @JMichaelTX

  TAGS:  @Date @String @ISO @International @Format
—————————————————————————————————————————————————————————————————————————————————
*/

  pDate       = pDate || new Date();
  var isoDate = new Date(pDate);
  
  //--- SUBTRACT OFFSET FOR LOCAL TZ ---
  //    (will be added back by toIOSString())
  isoDate.setMinutes(pDate.getMinutes() - pDate.getTimezoneOffset());
  
  //--- GET DATE FORMATED IN ISO FORMAT ---
  var isoDateStr = isoDate.toISOString();
  
  //--- GET JUST THE DATE AND TIME PARTS ---
  isoDateStr = isoDateStr.substring(0,10) + " " + isoDateStr.substring(11,19);
  
  return isoDateStr;    // "YYYY-MM-DD HH:MM:SS"

  
} //~~~~~~~~~~~~~~~ END OF function toISOFormat ~~~~~~~~~~~~~~~~~~~~~~~~~


//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
function updateKMScriptLog(pScriptName, pRemarks) {
/*      Ver 1.0    2016-10-07
---------------------------------------------------------------------------------
  PURPOSE:  Update the Script Log for Script used in Keyboard Maestro
  PARAMETERS:
    • pScriptName    | text  |  Name of script invoked
    • pRemarks      | text  |  Optional remarks 
  RETURNS:  NOTHING

  AUTHOR:  @JMichaelTX

  TAGS:  @Log @Script @KM @JXA
—————————————————————————————————————————————————————————————————————————————————
*/

  var kme = Application("Keyboard Maestro Engine");
  var kmVarName  = "SCPT__ScriptLog"
  var scriptLog  = kme.getvariable(kmVarName);
  
  if (!scriptLog) {
    scriptLog = "LOG DATE\tSCRIPT NAME\tREMARKS"
    scriptLog += "\n\nThis KM Variable may be deleted by you, the user, at any time."
    scriptLog += "\nA log entry is made by the script each time it is run. "
    scriptLog += "This log is TAB-delimited, and may be easily viewed in Excel via copy/paste."
  }
  
  //--- UPDATE SCRIPT LOG ---
  kme.setvariable(kmVarName, { to: (
    toISOFormat() 
    + "\t" + pScriptName 
    + "\t" + pRemarks
    + "\n"  + scriptLog) 
    });

  return
  
} //~~~~~~~~~~~~~~~ END OF function updateKMScriptLog ~~~~~~~~~~~~~~~~~~~~~~~~~


})();  // ~~~ function run() is automatically executed when this script is executed ~~~

/*  FOR MORE INFO:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
• STRICT MODE
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode
  • http://www.w3schools.com/js/js_strict.asp
  
*/