Insert an existing DOCX document into a section (w:altChunk)
Describe the problem
Merging an existing .docx into a generated document has been asked for many times (#8, #364, #840, #1460, #2420). The current way is to rebuild the other document through the object model, as in #1327, which loses part of its formatting (styles, numbering, table borders...).
Describe the expected behavior
Word already has a mechanism for this: the alternative format content chunk (w:altChunk, ISO/IEC 29500-1 §17.17.2). The file is stored as a part of the package and Word imports its content when the document is opened, without it being rebuilt: direct formatting, numbering, images and tables are kept (a style that also exists in the main document takes the main document's definition, Word's default without w:matchSrc).
It could be exposed as a new element:
$section->addText('Main document');
$section->addPageBreak();
$section->addAltChunk('annex.docx');Proposed implementation:
Element\AltChunk: takes the path of an existing.docxfile, otherwise throwsInvalidObjectException.Writer\Word2007\Element\AltChunk: writes<w:altChunk r:id="rIdN"/>. It is a block-level element, so it can only be added to aSection.- The file is handled as a media relation, like images and OLE objects: stored as
word/section_altChunkN.docx, relationship typehttp://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk, and a default content type for thedocxextension,application/vnd.openxmlformats-officedocument.wordprocessingml.document(the part is a whole package, so not the.main+xmltype). - Other writers skip the element; the Word2007 reader does not see the inserted content, since Word imports it at opening time.
- Section breaks inside the inserted document are kept, but not its last section properties: the end of the inserted content takes the properties of the section it is placed in.
I have tried this approach against master (599e438): generated documents with several inserted files, each after a page break, open in Microsoft Word with the documents merged in place. The patch below applies to master with git apply and contains the element, the Word2007 writer, unit tests and a documentation page. Would this be enough for the feature to be added on your side?
diff --git a/docs/usage/elements/altchunk.md b/docs/usage/elements/altchunk.md
new file mode 100644
index 0000000..2144e4c
--- /dev/null
+++ b/docs/usage/elements/altchunk.md
@@ -0,0 +1,18 @@
+# AltChunk
+
+An existing Word document can be inserted into a section with the ``addAltChunk`` method.
+
+``` php
+<?php
+
+$section->addText('Main document');
+$section->addPageBreak();
+$section->addAltChunk('annex.docx');
+```
+
+The file is stored in the package as is, and a ``w:altChunk`` element is written at this place of the body. Word imports the content of the inserted document when the file is opened: its direct formatting, numbering, images and tables are kept, while a style that also exists in the main document (for example ``Normal``) takes the main document's definition.
+
+- The source must be an existing ``.docx`` file.
+- The element can only be added to a section.
+- Section breaks inside the inserted document are kept, but not its last section properties: the end of the inserted content takes the properties of the section it is placed in. If the inserted document has its own page layout (margins, orientation), add it to a new section so that it does not change the layout of the main document.
+- It is only written by the Word2007 writer. Other writers skip it, and the inserted content is not visible to the Word2007 reader either, since it is imported by Word at opening time.
diff --git a/docs/usage/elements/index.md b/docs/usage/elements/index.md
index fbf97bb..8244c68 100644
--- a/docs/usage/elements/index.md
+++ b/docs/usage/elements/index.md
@@ -26,6 +26,7 @@ Below are the matrix of element availability in each container. The column shows
| 20 | [Field](field.md) | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: |
| 21 | [Line](line.md) | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: | :white_check_mark: |
| 22 | [Chart](chart.md) | :white_check_mark: | | | :white_check_mark: | | |
+| 23 | [AltChunk](altchunk.md) | :white_check_mark: | :red_circle: | :red_circle: | :red_circle: | :red_circle: | :red_circle: |
Legend:
diff --git a/mkdocs.yml b/mkdocs.yml
index e68d154..ebe18fd 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -53,6 +53,7 @@ nav:
- Chart: 'usage/elements/chart.md'
- Checkbox: 'usage/elements/checkbox.md'
- Comment: 'usage/elements/comment.md'
+ - AltChunk: 'usage/elements/altchunk.md'
- Bookmark: 'usage/elements/bookmark.md'
- Field: 'usage/elements/field.md'
- Footnote & Endnote: 'usage/elements/note.md'
diff --git a/src/PhpWord/Element/AbstractContainer.php b/src/PhpWord/Element/AbstractContainer.php
index 05fc1a1..927e06e 100644
--- a/src/PhpWord/Element/AbstractContainer.php
+++ b/src/PhpWord/Element/AbstractContainer.php
@@ -42,6 +42,7 @@ use ReflectionClass;
* @method Table addTable(mixed $style = null)
* @method Image addImage(string $source, mixed $style = null, bool $isWatermark = false, $name = null, $altText = null)
* @method OLEObject addOLEObject(string $source, mixed $style = null)
+ * @method AltChunk addAltChunk(string $source)
* @method TextBox addTextBox(mixed $style = null)
* @method Field addField(string $type = null, array $properties = array(), array $options = array(), mixed $text = null)
* @method Line addLine(mixed $lineStyle = null)
@@ -92,7 +93,7 @@ abstract class AbstractContainer extends AbstractElement
'Footnote', 'Endnote', 'CheckBox', 'TextBox', 'Field',
'Line', 'Shape', 'Title', 'TOC', 'PageBreak',
'Chart', 'FormField', 'SDT', 'Comment',
- 'Formula', 'Ruby',
+ 'Formula', 'Ruby', 'AltChunk',
];
$functions = [];
foreach ($elements as $element) {
@@ -259,6 +260,7 @@ abstract class AbstractContainer extends AbstractElement
'TOC' => ['Section'],
'PageBreak' => ['Section'],
'Chart' => ['Section', 'Cell'],
+ 'AltChunk' => ['Section'],
];
// Special condition, e.g. preservetext can only exists in cell when
diff --git a/src/PhpWord/Element/AbstractElement.php b/src/PhpWord/Element/AbstractElement.php
index 3a29b68..2a077c5 100644
--- a/src/PhpWord/Element/AbstractElement.php
+++ b/src/PhpWord/Element/AbstractElement.php
@@ -422,7 +422,7 @@ abstract class AbstractElement
*/
private function setMediaRelation(): void
{
- if (!$this instanceof Link && !$this instanceof Image && !$this instanceof OLEObject) {
+ if (!$this instanceof Link && !$this instanceof Image && !$this instanceof OLEObject && !$this instanceof AltChunk) {
return;
}
diff --git a/src/PhpWord/Element/AltChunk.php b/src/PhpWord/Element/AltChunk.php
new file mode 100644
index 0000000..7ab7eb6
--- /dev/null
+++ b/src/PhpWord/Element/AltChunk.php
@@ -0,0 +1,74 @@
+<?php
+
+/**
+ * This file is part of PHPWord - A pure PHP library for reading and writing
+ * word processing documents.
+ *
+ * PHPWord is free software distributed under the terms of the GNU Lesser
+ * General Public License version 3 as published by the Free Software Foundation.
+ *
+ * For the full copyright and license information, please read the LICENSE
+ * file that was distributed with this source code. For the full list of
+ * contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
+ *
+ * @see https://github.com/PHPOffice/PHPWord
+ *
+ * @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
+ */
+
+namespace PhpOffice\PhpWord\Element;
+
+use PhpOffice\PhpWord\Exception\InvalidObjectException;
+
+/**
+ * Alternative format content chunk (w:altChunk): embeds a whole existing
+ * DOCX document, which Word imports at this place when the file is opened.
+ *
+ * This is the standard way (ISO/IEC 29500-1, 17.17.2) to merge documents:
+ * the embedded document is not rebuilt through the PhpWord object model, so
+ * its direct formatting, numbering, images and tables are kept. A style that
+ * also exists in the main document takes the main document's definition,
+ * which is Word's default when no w:altChunkPr/w:matchSrc is written.
+ *
+ * The chunk is a block-level element: it is written in the body, before the
+ * final section properties (w:sectPr), where the specification requires it.
+ * It is only rendered by the Word2007 writer; other writers skip it.
+ */
+class AltChunk extends AbstractElement
+{
+ /**
+ * Path of the embedded DOCX file.
+ *
+ * @var string
+ */
+ private $source;
+
+ /**
+ * The embedded file is a relation of the document part.
+ *
+ * @var bool
+ */
+ protected $mediaRelation = true;
+
+ /**
+ * @param string $source Path of an existing DOCX file
+ */
+ public function __construct($source)
+ {
+ $source = (string) $source;
+ if (!is_file($source) || strtolower(pathinfo($source, PATHINFO_EXTENSION)) !== 'docx') {
+ throw new InvalidObjectException("AltChunk source must be an existing .docx file: {$source}");
+ }
+ $this->source = $source;
+ }
+
+ /**
+ * Get the path of the embedded DOCX file.
+ *
+ * @return string
+ */
+ public function getSource()
+ {
+ return $this->source;
+ }
+}
diff --git a/src/PhpWord/Media.php b/src/PhpWord/Media.php
index 0a340a0..bac386d 100644
--- a/src/PhpWord/Media.php
+++ b/src/PhpWord/Media.php
@@ -85,6 +85,11 @@ class Media
case 'object':
$target = "{$container}_oleObject{$mediaTypeCount}.bin";
+ break;
+ // Embedded documents (altChunk)
+ case 'altchunk':
+ $target = "{$container}_altChunk{$mediaTypeCount}.docx";
+
break;
// Links
case 'link':
diff --git a/src/PhpWord/Writer/Word2007.php b/src/PhpWord/Writer/Word2007.php
index 9702c21..5bff93c 100644
--- a/src/PhpWord/Writer/Word2007.php
+++ b/src/PhpWord/Writer/Word2007.php
@@ -85,7 +85,7 @@ class Word2007 extends AbstractWriter implements WriterInterface
}
// Set package paths
- $this->mediaPaths = ['image' => 'word/media/', 'object' => 'word/embeddings/'];
+ $this->mediaPaths = ['image' => 'word/media/', 'object' => 'word/embeddings/', 'altchunk' => 'word/'];
}
/**
@@ -318,6 +318,12 @@ class Word2007 extends AbstractWriter implements WriterInterface
if (!isset($this->contentTypes['default']['bin'])) {
$this->contentTypes['default']['bin'] = 'application/vnd.openxmlformats-officedocument.oleObject';
}
+ } elseif ($mediumType == 'altchunk') {
+ // The embedded part is a whole package, not document.xml:
+ // no ".main+xml" suffix (ISO/IEC 29500-1, 17.17.2.1).
+ if (!isset($this->contentTypes['default']['docx'])) {
+ $this->contentTypes['default']['docx'] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
+ }
}
}
}
diff --git a/src/PhpWord/Writer/Word2007/Element/AltChunk.php b/src/PhpWord/Writer/Word2007/Element/AltChunk.php
new file mode 100644
index 0000000..6fa6fc0
--- /dev/null
+++ b/src/PhpWord/Writer/Word2007/Element/AltChunk.php
@@ -0,0 +1,46 @@
+<?php
+
+/**
+ * This file is part of PHPWord - A pure PHP library for reading and writing
+ * word processing documents.
+ *
+ * PHPWord is free software distributed under the terms of the GNU Lesser
+ * General Public License version 3 as published by the Free Software Foundation.
+ *
+ * For the full copyright and license information, please read the LICENSE
+ * file that was distributed with this source code. For the full list of
+ * contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
+ *
+ * @see https://github.com/PHPOffice/PHPWord
+ *
+ * @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
+ */
+
+namespace PhpOffice\PhpWord\Writer\Word2007\Element;
+
+use PhpOffice\PhpWord\Element\AltChunk as AltChunkElement;
+
+/**
+ * AltChunk element writer: <w:altChunk r:id="..."/>, a block-level element
+ * pointing to the embedded document (relationship type aFChunk).
+ */
+class AltChunk extends AbstractElement
+{
+ /**
+ * Write altChunk element.
+ */
+ public function write(): void
+ {
+ $xmlWriter = $this->getXmlWriter();
+ $element = $this->getElement();
+ if (!$element instanceof AltChunkElement) {
+ return;
+ }
+
+ $rId = $element->getRelationId() + ($element->isInSection() ? 6 : 0);
+
+ $xmlWriter->startElement('w:altChunk');
+ $xmlWriter->writeAttribute('r:id', 'rId' . $rId);
+ $xmlWriter->endElement(); // w:altChunk
+ }
+}
diff --git a/src/PhpWord/Writer/Word2007/Part/Rels.php b/src/PhpWord/Writer/Word2007/Part/Rels.php
index f282f80..8638773 100644
--- a/src/PhpWord/Writer/Word2007/Part/Rels.php
+++ b/src/PhpWord/Writer/Word2007/Part/Rels.php
@@ -82,7 +82,7 @@ class Rels extends AbstractPart
private function writeMediaRel(XMLWriter $xmlWriter, $relId, $mediaRel): void
{
$typePrefix = 'officeDocument/2006/relationships/';
- $typeMapping = ['image' => 'image', 'object' => 'oleObject', 'link' => 'hyperlink'];
+ $typeMapping = ['image' => 'image', 'object' => 'oleObject', 'link' => 'hyperlink', 'altchunk' => 'aFChunk'];
$targetMapping = ['image' => 'media/', 'object' => 'embeddings/'];
$mediaType = $mediaRel['type'];
diff --git a/tests/PhpWordTests/Element/AltChunkTest.php b/tests/PhpWordTests/Element/AltChunkTest.php
new file mode 100644
index 0000000..7ce69f5
--- /dev/null
+++ b/tests/PhpWordTests/Element/AltChunkTest.php
@@ -0,0 +1,108 @@
+<?php
+
+/**
+ * This file is part of PHPWord - A pure PHP library for reading and writing
+ * word processing documents.
+ *
+ * PHPWord is free software distributed under the terms of the GNU Lesser
+ * General Public License version 3 as published by the Free Software Foundation.
+ *
+ * For the full copyright and license information, please read the LICENSE
+ * file that was distributed with this source code. For the full list of
+ * contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
+ *
+ * @see https://github.com/PHPOffice/PHPWord
+ *
+ * @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
+ */
+
+namespace PhpOffice\PhpWordTests\Element;
+
+use BadMethodCallException;
+use PhpOffice\PhpWord\Element\AltChunk;
+use PhpOffice\PhpWord\Element\Section;
+use PhpOffice\PhpWord\Exception\InvalidObjectException;
+use PhpOffice\PhpWord\PhpWord;
+use PHPUnit\Framework\TestCase;
+
+/**
+ * Test class for PhpOffice\PhpWord\Element\AltChunk.
+ */
+class AltChunkTest extends TestCase
+{
+ public function testConstructWithDocx(): void
+ {
+ $src = __DIR__ . '/../_files/documents/reader.docx';
+ $altChunk = new AltChunk($src);
+
+ self::assertEquals($src, $altChunk->getSource());
+ }
+
+ public function testConstructWithUppercaseExtension(): void
+ {
+ $src = tempnam(sys_get_temp_dir(), 'PhpWord') . '.DOCX';
+ copy(__DIR__ . '/../_files/documents/reader.docx', $src);
+
+ try {
+ $altChunk = new AltChunk($src);
+ self::assertEquals($src, $altChunk->getSource());
+ } finally {
+ unlink($src);
+ }
+ }
+
+ public function testConstructWithMissingFile(): void
+ {
+ $this->expectException(InvalidObjectException::class);
+ new AltChunk(__DIR__ . '/../_files/documents/missing.docx');
+ }
+
+ public function testConstructWithOtherFormat(): void
+ {
+ $this->expectException(InvalidObjectException::class);
+ new AltChunk(__DIR__ . '/../_files/documents/reader.odt');
+ }
+
+ public function testRelationId(): void
+ {
+ $altChunk = new AltChunk(__DIR__ . '/../_files/documents/reader.docx');
+ $altChunk->setRelationId(7);
+
+ self::assertEquals(7, $altChunk->getRelationId());
+ }
+
+ public function testAddToSection(): void
+ {
+ $section = new Section(1);
+ $section->setPhpWord(new PhpWord());
+ $altChunk = $section->addAltChunk(__DIR__ . '/../_files/documents/reader.docx');
+
+ self::assertInstanceOf(AltChunk::class, $altChunk);
+ self::assertSame([$altChunk], $section->getElements());
+ self::assertTrue($altChunk->isInSection());
+ }
+
+ public function testAddToTextRunIsNotAllowed(): void
+ {
+ $this->expectException(BadMethodCallException::class);
+ $section = new Section(1);
+ $section->setPhpWord(new PhpWord());
+ $section->addTextRun()->addAltChunk(__DIR__ . '/../_files/documents/reader.docx');
+ }
+
+ public function testAddToCellIsNotAllowed(): void
+ {
+ $this->expectException(BadMethodCallException::class);
+ $section = new Section(1);
+ $section->setPhpWord(new PhpWord());
+ $section->addTable()->addRow()->addCell()->addAltChunk(__DIR__ . '/../_files/documents/reader.docx');
+ }
+
+ public function testAddToHeaderIsNotAllowed(): void
+ {
+ $this->expectException(BadMethodCallException::class);
+ $section = new Section(1);
+ $section->setPhpWord(new PhpWord());
+ $section->addHeader()->addAltChunk(__DIR__ . '/../_files/documents/reader.docx');
+ }
+}
diff --git a/tests/PhpWordTests/Writer/Word2007/Element/AltChunkTest.php b/tests/PhpWordTests/Writer/Word2007/Element/AltChunkTest.php
new file mode 100644
index 0000000..6f28bba
--- /dev/null
+++ b/tests/PhpWordTests/Writer/Word2007/Element/AltChunkTest.php
@@ -0,0 +1,128 @@
+<?php
+
+/**
+ * This file is part of PHPWord - A pure PHP library for reading and writing
+ * word processing documents.
+ *
+ * PHPWord is free software distributed under the terms of the GNU Lesser
+ * General Public License version 3 as published by the Free Software Foundation.
+ *
+ * For the full copyright and license information, please read the LICENSE
+ * file that was distributed with this source code. For the full list of
+ * contributors, visit https://github.com/PHPOffice/PHPWord/contributors.
+ *
+ * @see https://github.com/PHPOffice/PHPWord
+ *
+ * @license http://www.gnu.org/licenses/lgpl.txt LGPL version 3
+ */
+
+namespace PhpOffice\PhpWordTests\Writer\Word2007\Element;
+
+use PhpOffice\PhpWord\PhpWord;
+use PhpOffice\PhpWordTests\TestHelperDOCX;
+use PHPUnit\Framework\TestCase;
+use ZipArchive;
+
+/**
+ * Test class for PhpOffice\PhpWord\Writer\Word2007\Element\AltChunk.
+ */
+class AltChunkTest extends TestCase
+{
+ private const RELATIONSHIP = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk';
+
+ /**
+ * Executed after each method of the class.
+ */
+ protected function tearDown(): void
+ {
+ TestHelperDOCX::clear();
+ }
+
+ public function testWriteAltChunk(): void
+ {
+ $src = __DIR__ . '/../../../_files/documents/reader.docx';
+ $phpWord = new PhpWord();
+ $section = $phpWord->addSection();
+ $section->addText('Before');
+ $section->addAltChunk($src);
+ $section->addText('After');
+
+ $doc = TestHelperDOCX::getDocument($phpWord, 'Word2007');
+
+ // Block-level element, between the paragraphs, not inside one
+ self::aSource: PHPOffice/PHPWord