12

I have an instance of a template on PHPWord. Is it possible to replace or add an image? Something like a setImageValue?

$phpWord = new \PhpOffice\PhpWord\Template('a.docx');
$phpWord->setImageValue('IMAGE_PLACEHOLDER', 'a.jpg');
$phpWord->saveAs('b.docx');

Is something like this possible?

4

7 に答える 7

7

template.docx の画像を追加、削除、または置き換えたい場合は、これを TemplateProcessor.php ファイルに追加できます (PhpWord 0.14.0 バージョンで動作します)。

1.

// add this in the class
protected $_rels;
protected $_types;

public function __construct($documentTemplate){
    // add this line to this function
    $this->_countRels=100; 
}

2.

public function save()
{
    //add this snippet to this function after $this->zipClass->addFromString('word/document.xml', $this->tempDocumentMainPart);
    if($this->_rels!=""){
        $this->zipClass->addFromString('word/_rels/document.xml.rels', $this->_rels);
    }
    if($this->_types!=""){
        $this->zipClass->addFromString('[Content_Types].xml', $this->_types);
    }
}

3. この関数も追加します。

public function setImg( $strKey, $img){
    $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>';

    $toAdd = $toAddImg = $toAddType = '';
    $aSearch = array('RID', 'IMG');
    $aSearchType = array('IMG', 'EXT');
    $countrels=$this->_countRels++;
    //I'm work for jpg files, if you are working with other images types -> Write conditions here
    $imgExt = 'jpg';
    $imgName = 'img' . $countrels . '.' . $imgExt;

    $this->zipClass->deleteName('word/media/' . $imgName);
    $this->zipClass->addFile($img['src'], 'word/media/' . $imgName);

    $typeTmpl = '<Override PartName="/word/media/'.$imgName.'" ContentType="image/EXT"/>';


    $rid = 'rId' . $countrels;
    $countrels++;
    list($w,$h) = getimagesize($img['src']);

    if(isset($img['swh'])) //Image proportionally larger side
    {
        if($w<=$h)
        {
            $ht=(int)$img['swh'];
            $ot=$w/$h;
            $wh=(int)$img['swh']*$ot;
            $wh=round($wh);
        }
        if($w>=$h)
        {
            $wh=(int)$img['swh'];
            $ot=$h/$w;
            $ht=(int)$img['swh']*$ot;
            $ht=round($ht);
        }
        $w=$wh;
        $h=$ht;
    }

    if(isset($img['size']))
    {
        $w = $img['size'][0];
        $h = $img['size'][1];           
    }

    $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->tempDocumentMainPart=str_replace('<w:t>' . $strKey . '</w:t>', $toAddImg, $this->tempDocumentMainPart);
    //print $this->tempDocumentMainPart;

    if($this->_rels=="")
    {
        $this->_rels=$this->zipClass->getFromName('word/_rels/document.xml.rels');
        $this->_types=$this->zipClass->getFromName('[Content_Types].xml');
    }

    $this->_types = str_replace('</Types>', $toAddType, $this->_types) . '</Types>';
    $this->_rels = str_replace('</Relationships>', $toAdd, $this->_rels) . '</Relationships>';
}

4. そしてこれ:

function limpiarString($str) {
    return str_replace(
            array('&', '<', '>', "\n"), 
            array('&amp;', '&lt;', '&gt;', "\n" . '<w:br/>'), 
            $str
    );
}

5. 使い方:

//open your template  
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('files/template.docx');
//add image to selector
$templateProcessor->setImg('selector',array('src' => 'image.jpg','swh'=>'200', 'size'=>array(0=>$width, 1=>$height));
// You can also clone row if you need
//$templateProcessor->cloneRow('NAME_IN_TEMPLATE', NUMBER_OF_TABLE_RECORDS);
$templateProcessor->cloneRow('SELECTOR', 4);
//save
header("Content-Disposition: attachment; filename='helloWord.docx'");
$templateProcessor->saveAs('php://output');
于 2018-02-01T14:52:26.843 に答える
4

Jerome のソリューションを拡張する関数をいくつか作成しました。問題は、画像を変更するために、docx ファイル内の参照名を知る必要があることでした。これは、平均的なユーザーにとっては見つけるのが難しい場合があります (docx を「解凍」して、手動で画像を見つける必要があります)。

私のソリューションでは、代替テキスト (通常の形式である必要があります: ${abc} ) で写真を参照できるようになるため、プレースホルダーの写真に単語がどのように名前を付けるかを知る必要はありません。変数で十分です。代替テキストを追加する方法についてのリンクは次のとおりです: http://accessproject.colostate.edu/udl/modules/word/tut_alt_text.php?display=pg_2

TemplateProcessor.php のみを変更しました

最初にこれをクラスに追加します。

/**
     * Content of document rels (in XML format) of the temporary document.
     *
     * @var string
     */
    private $temporaryDocumentRels; 

コンストラクター関数 (パブリック関数 __construct($documentTemplate)) は最後に拡張する必要があります。これを追加:

$this->temporaryDocumentRels = $this->zipClass->getFromName('word/_rels/document.xml.rels'); 

$this->temporaryDocumentRels を使用して、document.xml.rels から内容を読み取ることができるようになりました。

Jerome のコードを保持します。

/**
     * Set a new image
     *
     * @param string $search
     * @param string $replace
     */

    public function setImageValue($search, $replace){
        // Sanity check
        if (!file_exists($replace))
        {
            return;
        }

        // Delete current image
        $this->zipClass->deleteName('word/media/' . $search);

        // Add a new one
        $this->zipClass->addFile($replace, 'word/media/' . $search);
    }

この関数は、ラベル付けした画像の rId を返します。

/**
     * Search for the labeled image's rId
     *
     * @param string $search
     */

    public function seachImagerId($search){
        if (substr($search, 0, 2) !== '${' && substr($search, -1) !== '}') {
            $search = '${' . $search . '}';
        }
        $tagPos = strpos($this->temporaryDocumentMainPart, $search);
        $rIdStart = strpos($this->temporaryDocumentMainPart, 'r:embed="',$tagPos)+9;    
        $rId=strstr(substr($this->temporaryDocumentMainPart, $rIdStart),'"', true);
        return $rId;
    }

rId であることがわかっている場合、これは画像のファイル名を返します。

/**
     * Get img filename with it's rId
     *
     * @param string $rId
     */

    public function getImgFileName($rId){
        $tagPos = strpos($this->temporaryDocumentRels, $rId);
        $fileNameStart = strpos($this->temporaryDocumentRels, 'Target="media/',$tagPos)+14;
        $fileName=strstr(substr($this->temporaryDocumentRels, $fileNameStart),'"', true);
        return $fileName;
    }

TemplateProcessor.php の変更が完了しました。

これを呼び出すことで画像を置き換えることができます:

$templateProcessor->setImageValue($templateProcessor->getImgFileName($templateProcessor->seachImagerId("abc")),$replace);

次のように呼び出す関数を TemplateProcessor.php で作成することもできます。

public function setImageValueAlt($searchAlt, $replace){
        $this->setImageValue($this->getImgFileName($this->seachImagerId($searchAlt)),$replace);
    }
于 2015-08-27T12:45:59.903 に答える
1

画像を追加するソリューションを探していました。多くの記事を読みましたが、古いバージョンに適したソリューションしか見つかりませんでした。コードを取得する決定を変更して確定しました。

ファイル TemplateProcessor.php の変更に進みましょう

public function __construct($documentTemplate)
{
//add to this function

$this->_countRels=100; //start id for relationship between image and document.xml
}

public function save()
{
//add to this function after $this->zipClass->addFromString('word/document.xml', $this->tempDocumentMainPart);

if($this->_rels!="")
{
    $this->zipClass->addFromString('word/_rels/document.xml.rels', $this->_rels);
}
if($this->_types!="")
{
    $this->zipClass->addFromString('[Content_Types].xml', $this->_types);
}
}

//add function

public function setImg( $strKey, $img){
        $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>';

        $toAdd = $toAddImg = $toAddType = '';
        $aSearch = array('RID', 'IMG');
        $aSearchType = array('IMG', 'EXT');
        $countrels=$this->_countRels++;
        //I'm work for jpg files, if you are working with other images types -> Write conditions here
    $imgExt = 'jpg';
        $imgName = 'img' . $countrels . '.' . $imgExt;

            $this->zipClass->deleteName('word/media/' . $imgName);
            $this->zipClass->addFile($img['src'], 'word/media/' . $imgName);

            $typeTmpl = '<Override PartName="/word/media/'.$imgName.'" ContentType="image/EXT"/>';


            $rid = 'rId' . $countrels;
            $countrels++;
        list($w,$h) = getimagesize($img['src']);

 if(isset($img['swh'])) //Image proportionally larger side
 {
 if($w<=$h)
 {
    $ht=(int)$img['swh'];
    $ot=$w/$h;
    $wh=(int)$img['swh']*$ot;
    $wh=round($wh);
 }
 if($w>=$h)
 {
    $wh=(int)$img['swh'];
    $ot=$h/$w;
    $ht=(int)$img['swh']*$ot;
    $ht=round($ht);
 }
 $w=$wh;
 $h=$ht;
 }

if(isset($img['size']))
{
$w = $img['size'][0];
$h = $img['size'][1];           
}


            $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->tempDocumentMainPart=str_replace('<w:t>' . $strKey . '</w:t>', $toAddImg, $this->tempDocumentMainPart);
        //print $this->tempDocumentMainPart;



        if($this->_rels=="")
        {
            $this->_rels=$this->zipClass->getFromName('word/_rels/document.xml.rels');
            $this->_types=$this->zipClass->getFromName('[Content_Types].xml');
        }

        $this->_types       = str_replace('</Types>', $toAddType, $this->_types) . '</Types>';
                $this->_rels        = str_replace('</Relationships>', $toAdd, $this->_rels) . '</Relationships>';
}
//add function

function limpiarString($str) {
        return str_replace(
                array('&', '<', '>', "\n"), 
                array('&amp;', '&lt;', '&gt;', "\n" . '<w:br/>'), 
                $str
        );
}
//HOW TO USE???

$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('templ.docx');

//static zone
$templateProcessor->setValue('date', htmlspecialchars(date('d.m.Y G:i:s')));    
//$templateProcessor->cloneRow('NAME_IN_TEMPLATE', NUMBER_OF_TABLE_RECORDS);
$templateProcessor->cloneRow('AVTOR', 3);

//variant 1
//dynamic zone
$templateProcessor->setValue('AVTOR#1', htmlspecialchars('Garry'));
$templateProcessor->setValue('NAME#1', htmlspecialchars('Black Horse'));
$templateProcessor->setValue('SIZES#1', htmlspecialchars('100x300'));

/*$img = array(
        'src' => 'image.jpg',//path
    'swh'=>'350',//Image proportionally larger side
        'size'=>array(580, 280)
);*/
$templateProcessor->setImg('IMGD#1',array('src' => 'image.jpg','swh'=>'250'));

$templateProcessor->setValue('AVTOR#2', htmlspecialchars('Barry'));
$templateProcessor->setValue('NAME#2', htmlspecialchars('White Horse'));
$templateProcessor->setValue('SIZES#2', htmlspecialchars('200x500'));
$templateProcessor->setImg('IMGD#2',array('src' => 'image2.jpg','swh'=>'250'));

$templateProcessor->setValue('AVTOR#3', htmlspecialchars('Backer'));
$templateProcessor->setValue('NAME#3', htmlspecialchars('Another Side'));
$templateProcessor->setValue('SIZES#3', htmlspecialchars('120x430'));
$templateProcessor->setImg('IMGD#3',array('src' => 'image3.jpg','swh'=>'250'));
//variant 2

$templateProcessor->cloneRow('AVTOR', count($output['ID'])); 
        for($i=0;$i<count($output['ID']);$i++)
        {
            $templateProcessor->setValue('AVTOR'.'#'.($i+1), htmlspecialchars($output['AVTOR'][$i]));
            $templateProcessor->setValue('NAME'.'#'.($i+1), htmlspecialchars($output['PNAM'][$i]));
//GetImg($output['ID'][$i]) my function return image path
            $templateProcessor->setImg('IMGD'.'#'.($i+1), array('src'=>GetImg($output['ID'][$i]),'swh'=>'250'));
        }
//Save

$templateProcessor->saveAs('testTemplate.docx');
于 2016-01-20T08:57:51.350 に答える