Search code examples
phpphpwordelectronic-signature

PHPWord : Is it possible to replace placeholder text in a document with an image (at the same position where the text was)?


As part of the implementation of an electronic signature function. I need to add the signature at a specific position in the Word document. The position however could vary from one document to another. The only potential solution to this seems to be having a signature placeholder which gets replaced with the signature.png once the document is signed.

Is this possible with the PHPWord package ? If not is there any package out there that can do this ?


Solution

  • This is how to do it with phpword, as per their documentation :

    First, the word file needs to have a placeholder :

    ${CompanyLogo}
    ${UserLogo:50:50} ${Name} - ${City} - ${Street}
    ${Signature:50:50}
    

    Then with php, we can replace the placeholder like so :

    $templateProcessor = new TemplateProcessor('Template.docx');
    $templateProcessor->setValue('Name', 'John Doe');
    $templateProcessor->setValue(array('City', 'Street'), array('Detroit', '12th Street'));
    
    $templateProcessor->setImageValue('CompanyLogo', 'path/to/company/logo.png');
    $templateProcessor->setImageValue('UserLogo', array('path' => 'path/to/logo.png', 'width' => 100, 'height' => 100, 'ratio' => false));
    $templateProcessor->setImageValue('Signature', function () {
        // Closure will only be executed if the replacement tag is found in the template
        return array('path' => 'path/to/signature.png', 'width' => 100, 'height' => 100, 'ratio' => false);
    });