站長資訊網(wǎng)
        最全最豐富的資訊網(wǎng)站

        玩轉PHP之快速制作Word簡歷

        PHP制作word簡歷

        PHP操作word有一個非常好用的輪子,就是phpword,該輪子可以在github上查找到(PHPOffice/PHPWord)。上面有較為詳細的例子和代碼,其中里面的源碼包含有一些常用的操作例子,包括設置頁眉、頁腳、頁碼、字體樣式、表格、插入圖片等常用的操作。這里介紹的是如何使用該輪子來制作一個簡歷。

        模板替換的方式制作簡歷

        在許多招聘網(wǎng)站都有一個簡歷下載的功能,如何用php實現(xiàn)呢?在PHPOffice/PHPWord里面就有一個非常簡單的生成一個word文檔,向文檔中插入一些文字。這里我使用的方式比較取巧,這個輪子的說明文檔中有template processing,我理解為模板替換,也就是跟laravel的blade模板一個概念。接下來就不多廢話,直接說如何操作,這里提一句使用的是laravel框架。

        1.安裝PHPOffice/PHPWord

        composer require phpoffice/phpword

        2.創(chuàng)建控制器DocController及test方法用于測試,并建立路由。

        php artisan make:controller DocController

        3.建立word模板,這里說明一下,該輪子替換的是word文檔中格式為${value}格式的字符串,這里我簡易的搭建一個模板如下圖1所示:
        玩轉PHP之快速制作Word簡歷

        從圖中可以看到有一些基本的信息,這些可以從數(shù)據(jù)庫中撈取數(shù)據(jù)。不過這次是直接使用替換的方式,像工作經歷和教育經歷這種多行表格的模式這里也只需要取一行作為模板即可。

        4.具體代碼

        //load template docx         $templateProcessor = new TemplateProcessor('./sample.docx');          //基礎信息填寫替換         $templateProcessor->setValue('update_at', date('Y-m-d H:i:s'));         $templateProcessor->setValue('number', '123456');         $templateProcessor->setValue('Name', '張三');         $templateProcessor->setValue('sex', '男');         $templateProcessor->setValue('birth', '1996年10月');         $templateProcessor->setValue('age', '22');         $templateProcessor->setValue('shortcut', '待業(yè)/aaa');         $templateProcessor->setValue('liveArea', '福建省莆田市涵江區(qū)');         $templateProcessor->setValue('domicile', '福建省莆田市涵江區(qū)');         $templateProcessor->setValue('address', '');         $templateProcessor->setValue('hopetodo', 'IT');         $templateProcessor->setValue('hopeworkin', '互聯(lián)網(wǎng)');         $templateProcessor->setValue('hopes', '7000+');         $templateProcessor->setValue('worklocation', '福建省莆田市');         $templateProcessor->setValue('phone', '123456789');         $templateProcessor->setValue('mail', '456789@qq.com');         $templateProcessor->setValue('qqnum', '456789');         $templateProcessor->setValue('selfjudge', '哇哈哈哈哈哈哈哈');          //工作經歷表格替換         $templateProcessor->cloneRow('experience_time', 2);//該表通過克隆行的方式,形成兩行         $templateProcessor->setValue('experience_time#1', '2010-09~2014-06');//每行參數(shù)是用value#X(X表示行號,從1開始)         $templateProcessor->setValue('job#1', 'ABC company CTO');         $templateProcessor->setValue('experience_time#2', '2014-09~至今');         $templateProcessor->setValue('job#2', 'JBC company CTO');          //教育經歷         $templateProcessor->cloneRow('time', 2);         $templateProcessor->setValue('time#1', '2010-09~2014-06');         $templateProcessor->setValue('school#1', 'ABC');         $templateProcessor->setValue('major#1', 'Computer science');         $templateProcessor->setValue('time#2', '2014-09~至今');         $templateProcessor->setValue('school#2', 'JBC');         $templateProcessor->setValue('major#2', 'Computer science');          //語言能力         $templateProcessor->cloneRow('lang',2);         $templateProcessor->setValue('lang#1', '漢語|精通');         $templateProcessor->setValue('lang#2', '英語|精通');          //技能         $templateProcessor->cloneRow('skill',3);         $templateProcessor->setValue('skill#1', 'JAVA|精通');         $templateProcessor->setValue('skill#2', 'Python|精通');         $templateProcessor->setValue('skill#3', 'PHP|精通');          // Saving the document         $templateProcessor->saveAs('my.docx');

        這樣就可以通過建立word模板的方式產生一個簡歷了。以上內容沒有提到如何將圖片替換進去,如果你查看文檔的話會發(fā)現(xiàn)這個包的模板替換并沒有說怎么替換圖片,因為好像壓根這種方式就沒有提供,暈死。不過github的issue中有人提出了這個問題并且也有人給出了解決方案。下面我就來說說如何實現(xiàn)將圖片替換進去的功能。

        替換圖片

        假設你的簡歷模板中有個表格單元格中要插入一張圖片,如下:
        玩轉PHP之快速制作Word簡歷

        我要將public/img下的against the current.jpg圖片替換進去,而源代碼沒有將圖片替換進word的功能,所以只能自己編寫了。

        • 1.修改composer.json,將TemplateDocx類自動加載進來:
        "autoload": {         "classmap": [             "database/seeds",             "database/factories",             "app/Core/TemplateDocx.php"         ],         "psr-4": {             "App\": "app/"         }     },

        運行下列代碼:

        composer dump-autoload
        • 2.實現(xiàn)TemplateDocx類:

        該類的內容我直接放在我的gist上了,連接TemplateDocx.php

        由于code是放在gist上,國內訪問不了所以我直接把code貼出來,如下:

        <?php namespace AppCore; use PhpOfficePhpWordExceptionException; use PhpOfficePhpWordTemplateProcessor; class TemplateDocx extends TemplateProcessor {     /**      * @since 0.12.0 Throws CreateTemporaryFileException and CopyFileException instead of Exception      *      * @param string $documentTemplate The fully qualified template filename      *      * @throws PhpOfficePhpWordExceptionCreateTemporaryFileException      * @throws PhpOfficePhpWordExceptionCopyFileException      */     public function __construct($documentTemplate)     {         parent::__construct($documentTemplate);         //添加下列屬性,后面會用到         $this->_countRels = 100; //start id for relationship between image and document.xml         $this->_rels = '';         $this->_types = '';     }     /**      * Saves the result document.      *      * @throws PhpOfficePhpWordExceptionException      *      * @return string      */     public function save()     {         foreach ($this->tempDocumentHeaders as $index => $xml) {             $this->zipClass->addFromString($this->getHeaderName($index), $xml);         }         $this->zipClass->addFromString($this->getMainPartName(), $this->tempDocumentMainPart);         /*****************重寫原有的save方法中添加的內容******************/         if ($this->_rels != "") {             $this->zipClass->addFromString('word/_rels/document.xml.rels', $this->_rels);         }         if ($this->_types != "") {             $this->zipClass->addFromString('[Content_Types].xml', $this->_types);         }         /*********************我是分割線******************************/         foreach ($this->tempDocumentFooters as $index => $xml) {             $this->zipClass->addFromString($this->getFooterName($index), $xml);         }         // Close zip file         if (false === $this->zipClass->close()) {             throw new Exception('Could not close zip file.');         }         return $this->tempDocumentFilename;     }     /**      * 實現(xiàn)將圖片替換進word穩(wěn)定的方法      * @param $strKey      * @param $img      */     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>';     } }
        • 3.使用方法:
        $templateProcessor = new TemplateDocx('./sample.docx');         $imgPath = './img/against the current.jpg';          $templateProcessor->setImg('img', array(             'src'  => $imgPath, //圖片路徑             'size' => array( 150, 150 ) //圖片大小,單位px         ));         $templateProcessor->setValue('name', 'Sun');          $templateProcessor->cloneRow('key', 2);//該表通過克隆行的方式,形成兩行         $templateProcessor->setValue('key#1', '2010-09~2014-06');//每行參數(shù)是用value#X(X表示行號,從1開始)         $templateProcessor->setValue('val#1', 'ABC company CTO');         $templateProcessor->setValue('key#2', '2014-09~至今');         $templateProcessor->setValue('val#2', 'JBC company CTO'); //        $templateProcessor->setValue('img', 'Sun');          $templateProcessor->saveAs('my.docx');
        • 4.運行結果

        玩轉PHP之快速制作Word簡歷

        至此就可以產生簡歷啦,如果這篇文章對你有所幫助記得點贊哦,親!如果有任何問題可以留言!!(* ̄︶ ̄)

        贊(0)
        分享到: 更多 (0)
        網(wǎng)站地圖   滬ICP備18035694號-2    滬公網(wǎng)安備31011702889846號
        主站蜘蛛池模板: 999精品视频| 国产精品粉嫩美女在线观看| 国产精品久久久久久| 香港aa三级久久三级老师2021国产三级精品三级在 | 精品性影院一区二区三区内射| 精品人妻一区二区三区毛片| 久久精品国产免费一区| 精品人无码一区二区三区| 一本一道久久a久久精品综合| 精品欧美激情在线看| 99久久综合国产精品二区| 狠狠色丁香婷婷综合精品视频| 国内精品九九久久久精品| 人人妻人人澡人人爽人人精品97| 日韩精品人妻av一区二区三区| 国产精品热久久毛片| 91精品国产色综久久| 华人在线精品免费观看| 成人国产精品高清在线观看| 国产精品免费观看调教网| 久久精品中文无码资源站| 无码国产精品一区二区免费3p | 精品视频在线免费观看| 国产精品日本一区二区在线播放| 亚洲AV无码成人精品区天堂| 亚洲欧洲自拍拍偷精品 美利坚| 四虎国产精品永久地址入口| 久久久久国产精品嫩草影院| 精品a在线观看| 精品人妻无码专区中文字幕 | 亚洲第一永久AV网站久久精品男人的天堂AV | 99久久成人国产精品免费| 国语精品一区二区三区| 国产精品VA在线观看无码不卡| 国产三级久久久精品麻豆三级 | 国产日产韩国精品视频| 国产乱码精品一区二区三区中文 | 国内精品伊人久久久久| 51精品资源视频在线播放| 国产精品理论片在线观看 | 国产精品 一区 在线|