PHP Symfony 2设置PDF字段的值



有没有用php 设置PDF字段值的优雅解决方案

示例

$read = readPdfFile('pdf_file.pdf');
$array = ['param1'=> 'Foo'];
$newFile = setFromFile($read,$array);

谢谢

所以经过研究,我找到了解决方案:

首先你应该在你的笔记本电脑上安装pdftk

在我构建了一个类/服务来调用pdftk命令行之后(PS,这个类还没有完成,但它可以工作(

class PdfFormService implements ContainerAwareInterface
{
use ContainerAwareTrait;
/** @var $pdfUrl string */
private $pdfUrl;

/** @var $data array */
private $data;

/** @var  $output string */
private $outPut;

/** @var string string */
private $flatten = "";
public function __construct()
{
}
/**
* @param $pdfUrl
* @param array $data
* @param null $outPut
*
* Init Service
*/
public function setAttribute($pdfUrl, array $data, $outPut = null)
{
$this->pdfUrl = $pdfUrl;
$this->data = $data;
$this->outPut = $outPut;
}
/**
* Rendre les champ nom modifiable après
*/
public function setFlatten()
{
$this->flatten = ' flatten ';
return $this;
}
/**
* Return un fichier tmp
* @return bool|string
*/
private function getTmpFile()
{
return tempnam(sys_get_temp_dir(), gethostname());
}
/**
* @param $fdpFile
*
* Execute de commande line
*/
private function execute($fdpFile)
{
if (substr(php_uname(), 0, 3) == "Win") {
$pdftk = escapeshellarg("C:/Program Files (x86)/PDFtk/bin/pdftk.exe");
exec("$pdftk $this->pdfUrl fill_form $fdpFile output $this->outPut  $this->flatten");
} else {
exec("pdftk $this->pdfUrl fill_form $fdpFile output $this->outPut $this->flatten");
}
unlink($fdpFile);
}

private function generateFdf($data)
{
// pas touche a l'indentation 
$fdfHeader = <<< FDF
%FDF-1.2
1 0 obj<< /FDF<< /Fields[
FDF;
$fdfFooter = <<< FDF
] >> >>
endobj
trailer
<</Root 1 0 R>>
%%EOF
FDF;
$fdfContent = '';
foreach ($data as $key => $value) {
$fdfContent .= "<< /T({$key})/V({$value})>>";
}
$content = $fdfHeader . $fdfContent . $fdfFooter;
$fdfFile = $this->getTmpFile();
file_put_contents($fdfFile, $content);
return $fdfFile;
}

public function save($path = null)
{
if (!is_null($path)) {
$this->outPut = $path;
}
if (empty($this->data)) {
throw new NotFoundHttpException("Empty data Generate PDF");
}
$fdlFile = $this->generateFdf($this->data);
if (empty($this->outPut) || empty($this->pdfUrl)) {
throw new NotFoundHttpException("Url de sortie ou entrer vide ");
}
$this->execute($fdlFile);
return $this;
}

public function download()
{
$filepath = $this->outPut;
if (file_exists($filepath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename=' . uniqid(gethostname()) . '.pdf');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
exit;
}
}

}

如果你在symfony

$data  = ['KEY_PARAMS_IN_PDF' => 'Light yagami'];
/** @var  $pdf PdfFormService */
$pdf = $this->get('gdf.pdf.from.service');
$pdf->setAttribute('modele.pdf',$data,'toto.pdf');
$pdf->setFlatten()
->save()
->download();

最新更新