You are here

function fillpdf_execute_parse in FillPDF 7.2

Same name and namespace in other branches
  1. 6 fillpdf.module \fillpdf_execute_parse()
  2. 7 fillpdf.module \fillpdf_execute_parse()

Utility function to allow other functions to parse PDFs with the various methods in a consistent way.

Parameters

string $method The service or program being used. Possible values: local, remote, pdftk. Currently, only pdftk is supported.:

mixed $fillpdf When in URL mode, this is the filename to the PDF to parse. When in Stream mode, this is the PDF data.:

string $mode A special flag to control the behavior of this function. URL mode merges using a PDF on the: file system and Stream mode merges using the value of $fillpdf directly. Possible values: url, stream.

File

./fillpdf.module, line 904
Allows mappings of PDFs to site content

Code

function fillpdf_execute_parse($method, $fillpdf, $mode = 'url') {
  switch ($mode) {
    case 'url':
      $filename = $fillpdf;
      break;
    case 'stream':
      $filename = file_unmanaged_save_data($fillpdf, file_directory_temp() . '/pdf_data.pdf', FILE_EXISTS_RENAME);
      break;
  }
  $path_to_pdftk = variable_get('fillpdf_pdftk_path', 'pdftk');
  $status = fillpdf_pdftk_check($path_to_pdftk);
  if ($status === FALSE) {
    drupal_set_message(t('pdftk not properly installed.'), 'error');
    return array();
  }

  // Use exec() to call pdftk (because it will be easier to go line-by-line parsing the output) and pass $content via stdin. Retrieve the fields with dump_data_fields.
  $output = array();
  exec($path_to_pdftk . ' ' . escapeshellarg(drupal_realpath($filename)) . ' dump_data_fields', $output, $status);
  if (count($output) === 0) {
    drupal_set_message(t('PDF does not contain fillable fields.'), 'warning');
    return array();
  }

  // Build a simple map of dump_data_fields keys to our own array keys
  $data_fields_map = array(
    'FieldType' => 'type',
    'FieldName' => 'name',
    'FieldFlags' => 'flags',
    'FieldJustification' => 'justification',
  );

  // Build the fields array
  $fields = array();
  $fieldindex = -1;
  foreach ($output as $line => $lineitem) {
    if ($lineitem == '---') {
      $fieldindex++;
      continue;
    }

    // Separate the data key from the data value
    $linedata = explode(':', $lineitem);
    if (in_array($linedata[0], array_keys($data_fields_map))) {
      $fields[$fieldindex][$data_fields_map[$linedata[0]]] = trim($linedata[1]);
    }
  }
  if ($mode == 'stream') {
    file_unmanaged_delete($filename);
  }
  return $fields;
}