使用表单字段将图像添加到PDF

时间:2019-09-25 06:35:14

标签: php forms pdf

我正在尝试使用PHP来填充现有PDF上的表单字段并向其中添加图像。

我找到了FPDM库来填写表单字段:

$formInputArray = ['field1' => 'test value', 'field2' => 'second value'];

$pdf = new FPDM('orginal-file.pdf');
$pdf->getEntries($templatePDF, 'PDF');
$pdf->Load($formInputArray);
$pdf->Merge();
$pdf->Output('F', 'form-filled-file.pdf');

到目前为止有效。

在下一步中,我尝试将具有Fpdi类的图像添加到已编辑的文档中:

$pdf = new Fpdi();
$pdf->setSourceFile('form-filled-file.pdf');
$pageId = $pdf->importPage(1, \setasign\Fpdi\PdfReader\PageBoundaries::MEDIA_BOX);
$pdf->addPage();
$pdf->useTemplate($pageId);
$pdf->Image('test-image.jpg', 150*0.39, 150*0.39, 100*0.39);
$pdf->Output('F', 'finished-file.pdf');

问题在于,Fpdi正在将模板pdf结构转换为新的pdf结构。因此所有给定的表单字段都消失了。

所以问题是:

  

如何将图像添加到具有表单域的现有PDF中?

我还查看了iText / PDFtk(服务器端)和mPDF PHP库,但是由于GPL许可证,它们不是正确的库。

是否存在其他方法或其他库来填充表单字段并将图像添加到PHP中的PDF?

1 个答案:

答案 0 :(得分:1)

我们(Setasign,也是FPDI的作者)为这两项任务提供了商业解决方案:用纯PHP填充PDF表单并使用图像填充字段。

如果您使用FPDM,则只能填写文本字段。替换为SetaPDF-FormFiller Lite Component。完整版可让您填写其他字段类型,例如复选框或单选按钮组。

用图像填充单个文本字段和附加字段的简单示例是:

<?php

require_once('library/SetaPDF/Autoload.php');
// or if you use composer require_once('vendor/autoload.php');

// create a file writer
$writer = new SetaPDF_Core_Writer_File('image-in-form-field.pdf');
// get the main document instance
$document = SetaPDF_Core_Document::loadByFilename($filename, $writer);

// now get an instance of the form filler
$formFiller = new SetaPDF_FormFiller($document);

// Get the form fields of the document
$fields = $formFiller->getFields();

// Let's fill a field
$fields['Text Field']->setValue("Some example text.");

// Now prepare an appearance for the Logo field
// First of all let's get the annotation of the form field
$annotation = $fields['Logo']->getAnnotation();
// Remember the width and height for further calculations
$width = $annotation->getWidth();
$height = $annotation->getHeight();

// Create a form xobject to which we are going to write the image.
// This form xobject will be the resulting appearance of our form field.
$xobject = SetaPDF_Core_XObject_Form::create($document, array(0, 0, $width, $height));
// Get the canvas for this xobject
$canvas = $xobject->getCanvas();

// Let's create an image xobject
$image = SetaPDF_Core_Image::getByPath('Logo.png')->toXObject($document);

// scale image into available space and align in the center
if ($image->getHeight($width) >= $height) {
    $image->draw($canvas, $width / 2 - $image->getWidth($height) / 2, 0, null, $height);
} else {
    $image->draw($canvas, 0, $height / 2 - $image->getHeight($width) / 2, $width);
}

// Now add the appearance to the annotation
$annotation->setAppearance($xobject);

// Flatten all appearances to the pages content stream
$fields->flatten();

// finish the document
$document->save()->finish();

此脚本是this演示的简短版本。