资讯专栏INFORMATION COLUMN

使用PHPWord合并Word文档,在文档指定页插入另一个文档的内容

RobinTang / 2100人阅读

摘要:提示不支持文件的读取有一个客户有这样的需求,需要在里使用组件,把一个文档的内容,插入另一个文档的指定页内。由于两个文档的内容都不是固定的,所以不能使用的功能。当读取到指定的分页符之后,再读取的内容,跟着前面的内容插入,最后保存新的文档。

提示:不支持.doc文件的读取
有一个客户有这样的需求,需要在ThinkPHP里使用PHPWord组件,把一个文档(DOC1)的内容,插入另一个文档(DOC2)的指定页内。由于两个文档的内容都不是固定的,所以不能使用PHPWord的Template功能。
以前从来没有使用过PHPWord,所以前后也折腾了几天。从熟悉PHPWord的功能开始,看示例代码,还有源码,最终还是摸索出来解决方案,下面说下解决思路:

首先读取DOC1的内容,PHPWord把内容分成不同的节点和容器,最顶级的是Section,里面有TextRun(文本块),Table(表格)等容器。这些容器里又有Text(文本),Row(表格行),Cell(单元格)等,还有一些其他的TextBreak,PageBreak(分页符)等制表符。
逐级读取内容后,然后把读取出的内容插入到一个新的文档内。当读取到指定的分页符之后,再读取DOC2的内容,跟着前面的内容插入,最后保存新的文档。

贴一部分代码:

</>复制代码

  1. namespace HomeLogic;
  2. Vendor("PhpOffice.autoload");
  3. use PhpOfficePhpWordPhpWord;
  4. use PhpOfficePhpWordIOFactory;
  5. use PhpOfficePhpWordStyleFont;
  6. use PhpOfficePhpWordSharedipArchive;
  7. use PhpOfficePhpWordSettings;
  8. class MergeFile {
  9. private $currentPage = 0; // 当前分页
  10. private $page = 0; // 插入页数
  11. private $args = null; // 文本段样式
  12. private $tmpFiles = []; // 临时文件
  13. /**
  14. * 合并文件
  15. *
  16. * @param URI
  17. * 文件1地址
  18. * @param URI
  19. * 文件2地址
  20. * @param Numeric
  21. * 指定插入的页数
  22. *
  23. * @return String
  24. * 新文件的URI
  25. */
  26. public function joinFile($file1, $file2, $page)
  27. {
  28. $S1 = IOFactory::load($file1)->getSections();
  29. $S2 = IOFactory::load($file2)->getSections();
  30. $this->page = $page > 0 ? $page - 1 : $page;
  31. $phpWord = new PhpWord();
  32. foreach ($S1 as $S) {
  33. $section = $phpWord->addSection($S->getStyle());
  34. $elements = $S->getElements();
  35. # 逐级读取/写入节点
  36. $this->copyElement($elements, $section, $S2);
  37. }
  38. $F1 = IOFactory::createWriter($phpWord);
  39. $path = $_SERVER["DOCUMENT_ROOT"] . __ROOT__ . "/Public/Write/";
  40. if(!is_dir($path)) mkdir($path);
  41. $filePath = $path . time() . ".docx";
  42. $F1->save($filePath);
  43. # 清除临时文件
  44. foreach($this->tmpFiles as $P) {
  45. unlink($P);
  46. }
  47. return $filePath;
  48. }
  49. /**
  50. * 逐级读取/写入节点
  51. *
  52. * @param Array
  53. * 需要读取的节点
  54. * @param PhpOfficePhpWordElementSection
  55. * 节点的容器
  56. * @param Array
  57. * 文档2的所有节点
  58. */
  59. private function copyElement($elements, &$container, $S2 = null)
  60. {
  61. $inEls = [];
  62. foreach ($elements as $i => $E) {
  63. # 检查当前页数
  64. if ($this->currentPage == $this->page && !is_null($S2)) {
  65. # 开始插入
  66. foreach ($S2 as $k => $v) {
  67. $ELS = $v->getElements();
  68. $this->copyElement($ELS, $container);
  69. }
  70. # 清空防止重复插入
  71. $S2 = null;
  72. }
  73. $ns = get_class($E);
  74. $elName = end(explode("", $ns));
  75. $fun = "add" . $elName;
  76. # 统计页数
  77. if ($elName == "PageBreak") {
  78. $this->currentPage ++;
  79. }
  80. # 合并文本段
  81. if($elName == "TextRun"
  82. #&& !is_null($S2)
  83. ) {
  84. $tmpEls = $this->getTextElement($E);
  85. if(!is_null($tmpEls)) {
  86. $inEls = array_merge($inEls, $tmpEls);
  87. }
  88. $nextElName = "";
  89. if($i + 1 < count($elements)) {
  90. $nextE = $elements[$i + 1];
  91. $nextClass = get_class($nextE);
  92. $nextElName = end(explode("", $nextClass));
  93. }
  94. if($nextElName == "TextRun") {
  95. # 对比当前和下一个节点的样式
  96. if(is_object(end($inEls))) {
  97. $currentStyle = end($inEls)->getFontStyle();
  98. } else {
  99. continue;
  100. }
  101. $nextEls = $this->getTextElement($nextE);
  102. if(is_null($nextEls)) {
  103. $nextStyle = new Font();
  104. } else {
  105. $nextStyle = current($nextEls)->getFontStyle();
  106. }
  107. }
  108. }
  109. # 设置参数
  110. $a = $b = $c = $d = $e = null;
  111. @list($a, $b, $c, $d, $e) = $args;
  112. $newEl = $container->$fun($a, $b, $c, $d, $e);
  113. $this->setAttr($elName, $newEl, $E);
  114. #$inEls = [];
  115. if(method_exists($E, "getElements")
  116. && $elName != "TextRun"
  117. ) {
  118. $inEls = $E->getElements();
  119. }
  120. if(method_exists($E, "getRows"))
  121. $inEls = $E->getRows();
  122. if(method_exists($E, "getCells"))
  123. $inEls = $E->getCells();
  124. if (count($inEls) > 0) {
  125. $this->copyElement($inEls, $newEl);
  126. $inEls = [];
  127. $this->args = null;
  128. }
  129. }
  130. return $pageIndex;
  131. }
  132. /**
  133. * 获取Text节点
  134. */
  135. private function getTextElement($E) {
  136. $elements = $E->getElements();
  137. $result = [];
  138. foreach($elements as $inE) {
  139. $ns = get_class($inE);
  140. $elName = end(explode("", $ns));
  141. if($elName == "Text") {
  142. $inE->setPhpWord(null);
  143. $result[] = $inE;
  144. } elseif (method_exists($inE, "getElements")) {
  145. $inResult = $this->getTextElement($inE);
  146. }
  147. if(!is_null($inResult))
  148. $result = array_merge($result, $inResult);
  149. }
  150. return count($result) > 0 ? $result : null;
  151. }
  152. private function setAttr($elName, &$newEl, $E)
  153. {
  154. switch (strtolower($elName)) {
  155. case "footnote":
  156. $newEl->setReferenceId($E->getReferenceId());
  157. break;
  158. case "formfield":
  159. $newEl->setName($E->getName());
  160. $newEl->setDefault($E->getDefault());
  161. $newEl->setValue($E->getValue());
  162. $newEl->setEntries($E->getEntries());
  163. break;
  164. case "object":
  165. $newEl->setImageRelationId($E->getImageRelationId());
  166. $newEl->setObjectId($E->getObjectId());
  167. break;
  168. case "sdt":
  169. $newEl->setValue($E->getValue());
  170. $newEl->setListItems($E->getListItems());
  171. break;
  172. case "table":
  173. $newEl->setWidth($E->getWidth());
  174. break;
  175. }
  176. }
  177. }

程序员客栈,汇集各路码农,找到你的靠谱技术小伙伴 http://t.cn/RXz4ONT

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/22695.html

相关文章

  • PHPWord中文手册整理

    摘要:修正中文支持的问题,使用前如果发现乱码,需要进行一些修正解决编码问题,会对输入的文字进行编码转化,如果你使用或者编码的话就会出现乱码,如果你用编码,就查找类库中所有方法中的转码将其删除,如果你采用或者编码,使用进行编码转换。 修正 中文支持的问题,使用前如果发现乱码,需要进行一些修正: 解决编码问题,PHPword 会对输入的文字进行utf8_encode编码转化,如果你使用GBK、...

    wangdai 评论0 收藏0
  • PHP制作word简历

    摘要:模板替换的方式制作简历在许多招聘网站都有一个简历下载的功能,如何用实现呢在里面就有一个非常简单的生成一个文档,向文档中插入一些文字。安装创建控制器及方法用于测试,并建立路由。 PHP操作word有一个非常好用的轮子,就是phpword,该轮子可以在github上查找到(PHPOffice/PHPWord)。上面有较为详细的例子和代码,其中里面的源码包含有一些常用的操作例子,包括设置页眉...

    Donne 评论0 收藏0
  • 使用PHPWordWord文件做模板替换

    摘要:注文件需要使用编码在文件中按照参考文件方式插入复制符号到文件正常的输出替换。 因工作需要,使用了版本比较旧的PHPWord项目官方已不见维护更新,上次版本更新是在Fri Jul 8, 2011 at 8:00 AM如果PHP版本>=5.3.3,强烈推荐使用PHPOffice/PHPWord这个开源项目本篇针对的为旧版本的PHPWord 基本安装 见官网 问题总结 Autoloader...

    468122151 评论0 收藏0
  • 前端——HTML

    摘要:方式是将内容放在了请求头,所以会显示在上,将内容放在了请求体。此外,方式对提交内容的长度有限制,必须在之内,而没有。如果属性设置,表示选择框只能同时显示三项。表头会自动加粗居中,在表格内容区,表示行,表示列。HTML HTML叫做超文本标记语言,是一种制作万维网页面标准语言。相当于定义一套规则,大家都来遵守它,这样浏览器就可以去解释它。 浏览器负责将标签翻译成用户看得懂的格式,呈现给用户。 ...

    番茄西红柿 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<