Skip to content

Instantly share code, notes, and snippets.

@surferxo3
Last active September 29, 2017 17:04
Show Gist options
  • Save surferxo3/709e493271fa0f3bb4209b112d6bbd32 to your computer and use it in GitHub Desktop.
Save surferxo3/709e493271fa0f3bb4209b112d6bbd32 to your computer and use it in GitHub Desktop.
Script to replace Placeholders with Values in Editable Form in PDF
<?php
/*#############################
* Developer: Mohammad Sharaf Ali
* Designation: Web Developer
* Version: 1.0
*/#############################
/* REQUIREMENTS
* https://www.pdflabs.com/tools/pdftk-server/
* https://github.com/mikehaertl/php-pdftk
* If on windows -> place the files (pdftk.exe, libiconv2.dll) in your working directory
*/
require_once 'vendor/autoload.php';
use mikehaertl\pdftk\Pdf;
### STEP 1: get total no of pages
$pdf = new Pdf('sample.pdf');
$data = $pdf->getData();
$pages = 0;
if (preg_match('/NumberOfPages: (\d+)/', $data, $match)) {
$pages = $match[1];
}
### STEP 2: split each page into single file
// if provided single multi-page file, pdftk will cater form fields of first page only
for ($i = 1; $i <= $pages; $i++) {
// you can also use $pdf->burst()
$pdf = new Pdf('sample.pdf');
$pdf->cat(array($i))
->saveAs('sample_' . $i . '.pdf');
}
### STEP 3: replace placeholders in each file
for ($i = 1; $i <= $pages; $i++) {
$pdf = new Pdf('sample_' . $i . '.pdf');
$dataFields = $pdf->getDataFields();
$fillForm = [];
foreach ($dataFields as $dataField) {
if (isset($dataField['FieldStateOption'])) { // handle dropdown, radio, & checkbox inputs
$fillForm[$dataField['FieldName']] = $dataField['FieldStateOption'][1];
} else { // handle text inputs
$fillForm[$dataField['FieldName']] = mt_rand(1, 100000);
}
}
$pdf = new Pdf('sample_' . $i . '.pdf');
$pdf->fillForm($fillForm)
->flatten() // if you need final file to be un-editable
//->needAppearances() // if you need final file to be editable
->saveAs('sample_' . $i . '.pdf');
}
### STEP 4: merge splitted files into a single file
$pdf = new Pdf();
for ($i = 1; $i <= $pages; $i++) {
$pdf->addFile('sample_' . $i . '.pdf');
}
$pdf->saveAs('sample_final.pdf');
### Step5: remove splitted files
for ($i = 1; $i <= $pages; $i++) {
unlink('sample_' . $i . '.pdf');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment