Forum


Replies: 2   Views: 465
How to add new page and insert image
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  · 13-07-2023 - 21:21

Hello,

You can use addBreak to add page breaks or addSection to add new sections. With both methods new pages are added.

Using templates you can replace template placeholders and also add new contents with the same methods as creating the DOCX from scratch. New contents are added at the end of the document by default.

For example, using addBreak to insert a page break and an image in a DOCX template (sample files available in the package):

$docx = new CreateDocxFromTemplate('examples/files/TemplateSimpleText.docx');

$docx->addBreak(array('type' => 'page'));

$options = array(
    'src' => 'examples/img/image.png'
);
$docx->addImage($options);

$docx->createDocx('output');

Another sample using addSection:

$docx = new CreateDocxFromTemplate('examples/files/TemplateSimpleText.docx');

$docx->addSection('nextPage', 'letter');

$options = array(
    'src' => 'examples/img/image.png'
);
$docx->addImage($options);

$docx->createDocx('output');

With both sample scripts a new page is generated and an image is added. Adding a page break is the easiest approach, and addSection allows generating complex layouts.

Regarding your code, please note that DOCXPath methods, such as insertWordFragment, allow to do specific tasks such as insert WordFragments in specific positions, move contents, use DOMXPath queries... In your code you are inserting a WordFragment after all content types with the body tag as parent, because you are not adding any reference node. You don't need to use DOCXPath methods to accomplish the requested task.
On https://www.phpdocx.com/documentation/introduction/docxpath you can read more information about DOCXPath methods.

Regards.