平头哥
- 平头哥 2017-10-16 已签到连续签到1天,获得了5个金钱
- 平头哥 评论了教程 PHPWord(很少人会用到吧!)
1.最好用xml的格式做模板。
2.图片也可以替换,改类库
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="position:absolute;left:0;text-align:left;margin-left:MLpt;margin-top:MTpt;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]; } if (isset($img['mt'])) { $mt = $img['mt']; } if (isset($img['ml'])) { $ml = $img['ml']; } $toAddImg .= str_replace(array('RID', 'WID', 'HEI','ML', 'MT'), array($rid, $w, $h,$ml, $mt), $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); 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>'; }
$templateProcessor->setImg('IMG', array('src' => $model->img, 'swh' => '180', 'ml' => '45', 'mt' => '160'));