【问题标题】:Add image in a .docx with PHPWord using TemplateProcessor使用 TemplateProcessor 使用 PHPWord 在 .docx 中添加图像
【发布时间】:2015-05-11 17:33:50
【问题描述】:

我不知道是否可以使用 TemplateProcessor 使用 PHPWord 在模板中添加图像。

我有一个文档 (form.docx)。本文档是一个模板。我阅读了这些字段(例如 ${name})并将其替换为文本。

$template = new TemplateProcessor('form.docx');
$template->setValue('name', $name);

但是现在,我想放一张图片,但我不知道该怎么做。我试试这个:

$img='img.jpg';
$template->setValue('image',$img);

不起作用。我尝试其他形式,创建一个部分并将此部分添加到模板,但失败了。

$phpWord = new PhpWord();
$section = $phpWord->createSection();   

$section->addImage('img.jpg', array('width'=>210, 'height'=>210, 'align'=>'center'));
$template = new TemplateProcessor('form.docx'); 
$template->setValue('image',$section).

有人知道如何使用模板将图像放入 .docx 中吗?

谢谢。

【问题讨论】:

    标签: php docx phpword


    【解决方案1】:

    这应该可以解决问题:

    // 在你的 templatefile.docx 中必须有一个文本 ${foto} 才能工作

    $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('templatefile.docx');
    $templateProcessor->setImageValue('foto', array('path' => 'dummy_foto.jpg', 'width' => 100, 'height' => 100, 'ratio' => true));
    $templateProcessor->saveAs('result.docx');
    

    //打开文件

    header("Content-disposition: attachment;filename=" .'result.docx' . " ; charset=iso-8859-1");
    echo file_get_contents('result.docx');
    

    【讨论】:

      【解决方案2】:

      模板处理器可以有一个 save_image 功能。 见How to add/set images on PHPOffice/PHPWord Template?

      示例:

       $dokument->save_image('image2',$imagefile,$dokument);
      

      【讨论】:

      • 感谢您的帮助,但不起作用。我使用 TemplateProcessor 是因为 Template 已被弃用,并且使用 TemplateProcessor 此功能不起作用。
      • 我们有一个工作示例,所以我会调查这个问题并回复您。
      【解决方案3】:

      从 phpWord 文件夹中打开 TemplateProcessor.php。 替换里面的这个示例代码。

          <?php
      
      /**
       * PHPWord
       *
       * Copyright (c) 2010 PHPWord
       *
       * This library is free software; you can redistribute it and/or
       * modify it under the terms of the GNU Lesser General Public
       * License as published by the Free Software Foundation; either
       * version 2.1 of the License, or (at your option) any later version.
       *
       * This library is distributed in the hope that it will be useful,
       * but WITHOUT ANY WARRANTY; without even the implied warranty of
       * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
       * Lesser General Public License for more details.
       *
       * You should have received a copy of the GNU Lesser General Public
       * License along with this library; if not, write to the Free Software
       * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
       *
       * @category   PHPWord
       * @package    PHPWord
       * @copyright  Copyright (c) 010 PHPWord
       * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt    LGPL
       * @version    Beta 0.6.2, 24.07.2010
       */
      
      /**
       * PHPWord_DocumentProperties
       *
       * @category   PHPWord
       * @package    PHPWord
       * @copyright  Copyright (c) 2009 - 2010 PHPWord (http://www.codeplex.com/PHPWord)
       */
      class PHPWord_Template {
          private $_objZip;
          private $_tempFileName;
          private $_documentXML;
          private $_header1XML;
          private $_footer1XML;
          private $_rels;
          private $_types;
          private $_countRels;
      
          /**
           * Create a new Template Object
           * @param string $strFilename
           */
          public function __construct($strFilename) {
              $path = dirname($strFilename);
      
              $this->_tempFileName = $path . DIRECTORY_SEPARATOR . time() . '.docx'; // $path doesn't include the trailing slash - Custom code by Matt Bowden (blenderstyle) 04/12/2011
      
              copy($strFilename, $this->_tempFileName); // Copy the source File to the temp File
      
              $this->_objZip = new ZipArchive();
              $this->_objZip->open($this->_tempFileName);
      
              $this->_documentXML = $this->_objZip->getFromName('word/document.xml');
              $this->_header1XML  = $this->_objZip->getFromName('word/header1.xml'); // Custom code by Matt Bowden (blenderstyle) 04/12/2011
              $this->_footer1XML  = $this->_objZip->getFromName('word/footer1.xml'); // Custom code by Matt Bowden (blenderstyle) 04/12/2011
              $this->_rels        = $this->_objZip->getFromName('word/_rels/document.xml.rels'); #erap 07/07/2015
              $this->_types       = $this->_objZip->getFromName('[Content_Types].xml'); #erap 07/07/2015
              $this->_countRels   = substr_count($this->_rels, 'Relationship') - 1; #erap 07/07/2015
          }
      
          /**
           * Set a Template value
           * @param mixed $search
           * @param mixed $replace
           */
          public function setValue($search, $replace) {
              $search = '${' . $search . '}';
              $replace = $this->limpiarString($replace);
              $this->_documentXML = str_replace($search, $replace, $this->_documentXML);
              $this->_header1XML = str_replace($search, $replace, $this->_header1XML); // Custom code by Matt Bowden (blenderstyle) 04/12/2011
              $this->_footer1XML = str_replace($search, $replace, $this->_footer1XML); // Custom code by Matt Bowden (blenderstyle) 04/12/2011
          }
      
          /**
           * Save Template
           * @param string $strFilename
           */
          public function save($strFilename) {
              if (file_exists($strFilename))
                  unlink($strFilename);
              $this->_objZip->addFromString('word/document.xml', $this->_documentXML);
              $this->_objZip->addFromString('word/header1.xml', $this->_header1XML); // Custom code by Matt Bowden (blenderstyle) 04/12/2011
              $this->_objZip->addFromString('word/footer1.xml', $this->_footer1XML); // Custom code by Matt Bowden (blenderstyle) 04/12/2011
              $this->_objZip->addFromString('word/_rels/document.xml.rels', $this->_rels); #erap 07/07/2015
              $this->_objZip->addFromString('[Content_Types].xml', $this->_types); #erap 07/07/2015
              // Close zip file
              if ($this->_objZip->close() === false) 
                  throw new Exception('Could not close zip file.');
      
              rename($this->_tempFileName, $strFilename);
          }
      
          public function replaceImage($path, $imageName) {
              $this->_objZip->deleteName('word/media/' . $imageName);
              $this->_objZip->addFile($path, 'word/media/' . $imageName);
          }
      
          public function replaceStrToImg( $strKey, $arrImgPath ){
              //289x108
              $strKey = '${'.$strKey.'}';
              $relationTmpl = '<Relationship Id="RID" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/IMG"/>';
              $imgTmpl = '<w:pict><v:shape type="#_x0000_t75" style="width:WIDpx;height:HEIpx"><v:imagedata r:id="RID" o:title=""/></v:shape></w:pict>';
              $typeTmpl = ' <Override PartName="/word/media/IMG" ContentType="image/EXT"/>';
              $toAdd = $toAddImg = $toAddType = '';
              $aSearch = array('RID', 'IMG');
              $aSearchType = array('IMG', 'EXT');
      
              foreach($arrImgPath as $img){
                  $imgExt = array_pop( explode('.', $img['img']) );
                  if( in_array($imgExt, array('jpg', 'JPG') ) )
                      $imgExt = 'jpeg';
                  $imgName = 'img' . $this->_countRels . '.' . $imgExt;
                  $rid = 'rId' . $this->_countRels++;
      
                  $this->_objZip->addFile($img['img'], 'word/media/' . $imgName);
      
                  if( isset($img['size']) ){
                      $w = $img['size'][0];
                      $h = $img['size'][1];
                  }
                  else{
                      $w = 289;
                      $h = 108;
                  }
      
                  $toAddImg .= str_replace(array('RID', 'WID', 'HEI'), array($rid, $w, $h), $imgTmpl) ;
                  if( isset($img['dataImg']) )
                      $toAddImg .= '<w:br/><w:t>' . $this->limpiarString($img['dataImg']) . '</w:t><w:br/>';
      
                  $aReplace = array($imgName, $imgExt);
                  $toAddType .= str_replace($aSearchType, $aReplace, $typeTmpl) ;
      
                  $aReplace = array($rid, $imgName);
                  $toAdd .= str_replace($aSearch, $aReplace, $relationTmpl);
              }
      
              $this->_documentXML = str_replace('<w:t>' . $strKey . '</w:t>', $toAddImg, $this->_documentXML);
              $this->_types       = str_replace('</Types>', $toAddType, $this->_types) . '</Types>';
              $this->_rels        = str_replace('</Relationships>', $toAdd, $this->_rels) . '</Relationships>';
          }
      
          function limpiarString($str) {
              return str_replace(
                      array('&', '<', '>', "\n"), 
                      array('&amp;', '&lt;', '&gt;', "\n" . '<w:br/>'), 
                      $str
              );
          }
      
      }
      
      ?>
      

      您可以从here 获得完整的修改代码。

      【讨论】:

        猜你喜欢
        • 2016-10-08
        • 1970-01-01
        • 1970-01-01
        • 2021-11-26
        • 2020-08-18
        • 2021-11-01
        • 1970-01-01
        • 2015-04-20
        • 1970-01-01
        相关资源
        最近更新 更多