-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Open
Labels
Description
Describe the bug and add attachments
When i trying to replace placeholders in a Word document (.docx) with HTML content using Html::addHtml, the HTML content is always appended to the end of the section, rather than being inserted at the position of the placeholder.
The expected behavior is that the HTML content would replace the placeholder at its original position within the section. Instead, it appears as a new block at the bottom, disrupting the document structure.
This is logical behavior in itself, however I would like to know if there is a possibility of changing the index (I tried with setIndex but it did not work) so that it takes the requested place?
Expected behavior
When replacing a placeholder (e.g., ###KEY###) with HTML content:
- The HTML should be rendered at the exact position of the placeholder.
- The placeholder's TextRun or Text element should be replaced by the HTML content in the same location.
Steps to reproduce
<?php
use PhpOffice\PhpWord\TemplateProcessor;
use PhpOffice\PhpWord\Shared\Html;
$templateProcessor = new TemplateProcessor('/path/to/template.docx');
$htmlContent = "<p>This is a <b>test</b> paragraph with <i>HTML</i>.</p>";
$templateProcessor->setValue('PLACEHOLDER', '###PLACEHOLDER###');
$templateProcessor->saveAs('/path/to/temp.docx');
$phpWord = \PhpOffice\PhpWord\IOFactory::load('/path/to/temp.docx');
foreach ($phpWord->getSections() as $section) {
foreach ($section->getElements() as $element) {
if ($element instanceof \PhpOffice\PhpWord\Element\TextRun) {
foreach ($element->getElements() as $text) {
if ($text instanceof \PhpOffice\PhpWord\Element\Text && $text->getText() === '###PLACEHOLDER###') {
$section->removeElement($element->getElementIndex());
Html::addHtml($section, $htmlContent, false, false); // <-- Here, the HTML content is append to end of file. How could I set its index so that it replaces my Text that i want to modify ?
}
}
}
}
}
$phpWord->save('/path/to/final.docx');
PHPWord version(s) where the bug happened
^0.18.2
PHP version(s) where the bug happened
7.4
Priority
- I want to crowdfund the bug fix (with @algora-io) and fund a community developer.
- I want to pay the bug fix and fund a maintainer for that. (Contact @Progi1984)