Forum


Replies: 6   Views: 282
Replacing multiple images
Topic closed:
Please note this is an old forum thread. Information in this post may be out-to-date and/or erroneous.
Every phpdocx version includes new features and improvements. Previously unsupported features may have been added to newer releases, or past issues may have been corrected.
We encourage you to download the current phpdocx version and check the Documentation available.

Posted by admin  · 25-04-2024 - 06:41

Hello,

You can add images using addImage:

$options = array(
    'src' => 'image.png',
);

$docx->addImage($options);

or embedHTML:

$html = '<img src="image.png">';

$docx->embedHTML($html);

By default, these methods add the contents at the end of the document. If you need to add the images into specific positions of the document or replace existing elements you can use insertWordFragment or replaceWordContent from DOCXPath. For example, to add an image after the second paragraph:

$content = new WordFragment($docx, 'document');
$content->addImage(['src' => 'image.png']);

$referenceNode = [
    'type' => 'paragraph',
    'occurrence' => 2,
];

$docx->insertWordFragment($content, $referenceNode, 'after');

or to replace the second paragraph with an image:

$content = new WordFragment($docx, 'document');
$content->addImage(['src' => 'image.png']);

$referenceNode = [
    'type' => 'paragraph',
    'occurrence' => 2,
];

$docx->replaceWordContent($content, $referenceNode, 'after');

The WordFragment can be generated with addImage, embedHTML or any other phpdocx content method (even multiple contents).

In addition to replacePlaceholderImage, you can use replaceVariableByWordFragment to add images (for example replacing text placeholders by a WordFragment that contains an image); maybe this is the easiest approach to accomplish your task. For example:

$imageFragment = new WordFragment($docx, 'document');
$imageFragment->addImage(['src' => 'image.png']);

$docx->replaceVariableByWordFragment(['VAR_IMAGE' => $imageFragment], ['type' => 'block']);

The WordFragment can be generated with addImage, embedHTML or any other phpdocx content method (even multiple contents).
As other template methods, replacePlaceholderImage and replaceVariableByWordFragment replace all placeholders with the same name unless you set the firstMatch option as true.

Regards.