PHPWord生成word 下載 解決中文亂碼

文章分兩部分:一是代碼部分,第二是解決中文亂碼。

使用PHPWord生成Word文檔 下載或保存到服務器

	/*生成word文檔*/
	public function makePhpWord()
    {
    	vendor('PHPWord.PHPWord');
		vendor('PHPWord.PHPWord.PHPWord_IOFactory');

		$path_img = rtrim($_SERVER["SCRIPT_FILENAME"],"admin.php") ."Down/ceyan/report/img/";
		if (!file_exists($path_img)) { mkdir($path_img, 0777 ,true); }

		// New Word Document
		$PHPWord = new \PHPWord();
		//設置默認字體
		$PHPWord-> setDefaultFontName('黑體');
		
		// 添加新頁
		$section = $PHPWord->createSection();
		
		// 設置頁眉頁腳樣式
		$PHPWord->addFontStyle('hStyle', array('bold'=>false, '黑體'=>true, 'size'=>8));
		$PHPWord->addParagraphStyle('fStyle', array('align'=>'center', 'spaceAfter'=>100));
		// 頁眉 爲Word文檔添加頁眉
		$header = $section->createHeader();
		$header->addText($this->myIconv("頁眉是否可以居中以後完善"), 'hStyle', 'fStyle');

		// 頁腳 爲word文檔添加頁腳,頁腳內容是頁碼,格式居中
		$footer = $section->createFooter();
		$footer->addPreserveText($this->myIconv("第").' {PAGE}'.$this->myIconv(" 頁  共").' {NUMPAGES}'.$this->myIconv(" 頁"), 'hStyle', 'fStyle');
		 
		//報價函
		$PHPWord->addFontStyle('rStyle', array('bold'=>true, '黑體'=>true, 'size'=>14));
		$PHPWord->addParagraphStyle('pStyle', array('align'=>'center', 'spaceAfter'=>100));
		$section->addText($this->myIconv("報價函"), 'rStyle', 'pStyle');
		 
		//XX公司
		$section->addText($this->myIconv("致:科技信息技術公司"), array('bold'=>true, '黑體'=>true, 'size'=>11), array('spacing'=>120));
		 
		// 簡介
		$PHPWord->addFontStyle('r_descStyle', array('黑體'=>true, 'size'=>11));
		$PHPWord->addParagraphStyle('p_descStyle', array('spacing'=>120));
		$section->addText($this->myIconv("    我司十分榮幸地就貴司“XXX項目”與貴司達成合作意向。在與貴司相關負責人仔細分析製作要求及探討製作內容的基礎上,經我司召開技術部會議部署製作計劃,現向貴司發出報價函,同時我司承諾:"), r_descStyle, p_descStyle);


		$listStyle = array('listType'=>\PHPWord_Style_ListItem::TYPE_NUMBER);
		$section->addListItem($this->myIconv('該報價一旦爲貴司認可,即爲合同價;該報價有效期爲6個工作日。'), 0, r_descStyle, $listStyle, p_descStyle);
		$section->addListItem($this->myIconv('本公司報價函一經發出,即不可撤回。本公司一旦榮幸地成爲本項目的簽約方,同意將按項目洽談會上所達成的相關要求進一步深入推進製作進程。'), 0, r_descStyle, $listStyle, p_descStyle);
		$section->addListItem($this->myIconv('若貴司對報價函持有異議,請務必通過書面或其他渠道與我司相關負責人進行磋商,以免影響項目進度。'), 0, r_descStyle, $listStyle, p_descStyle);
		 
		//製作內容
		$section->addText($this->myIconv('製作內容:  公園壹號項目'), array('bold'=>true, '黑體'=>true, 'size'=>11));
		//$section->addText('XX項目', array('underline'=>true));
		//段落文字換行,參數可以控制換行的行數
		$section->addTextBreak(2);
		
		// 圖片 可以在word中添加圖片,如圖片地址logo.png,尺寸爲64x64。圖片源也可以是遠程圖片
		$section->addImage($path_img.'test.png', array('width'=>200, 'height'=>200,'align'=>'center') );
		 
		// 鏈接 可以爲Word文檔中的文字添加用於點擊跳轉的鏈接
		$section->addLink('http://www.baidu.com', $this->myIconv('歡迎訪問baidu'), array('color' => '0000FF', 'underline' => \PHPWord_Style_Font::UNDERLINE_SINGLE));

		// 添加新頁
		$section = $PHPWord->createSection();
		//費用明細
		$section->addText($this->myIconv('費用明細:'), array('bold'=>true, '黑體'=>true, 'size'=>11));
		$section->addTextBreak();

		/**************table start*******************/

		$styleTable = array('borderSize'=>6, 'borderColor'=>'000000', 'cellMargin'=>80);
		$styleCell = array('valign'=>'center', 'align'=>'center');
		$fontStyle = array('size'=>11 /*,'bold'=>true*/);
		$PHPWord->addTableStyle('myOwnTableStyle', $styleTable, $fontStyle);
		 
		$table = $section->addTable('myOwnTableStyle');
		$table->addRow(900);
		$table->addCell(2000, $styleCell)->addText($this->myIconv('製作項目'), $fontStyle, $styleCell);
		$table->addCell(2000, $styleCell)->addText($this->myIconv('內容說明'), $fontStyle, $styleCell);
		$table->addCell(2000, $styleCell)->addText($this->myIconv('價格(萬)'), $fontStyle, $styleCell);
		for($i = 1; $i <= 3; $i++) {
			$table->addRow();
			$table->addCell(2000)->addText("", $fontStyle, $styleCell);
			$table->addCell(2000)->addText("", $fontStyle, $styleCell);
			$table->addCell(2000)->addText("", $fontStyle, $styleCell);
		}
		/**************table end*******************/
		$section->addTextBreak(1);
		 
		 
		//製作工期
		$section->addText($this->myIconv('製作工期:  5個月'), array('bold'=>true, '黑體'=>true, 'size'=>11));
		//$section->addText('XX項目', array('underline'=>true));
		

		$section->addTextBreak(2);
		//北京信息技術有限公司
		$section->addText($this->myIconv('北京信息技術有限公司'), array('黑體'=>true, 'size'=>11), array('align'=>'right', 'spaceBefore'=>200));
		$section->addText($this->myIconv('娜娜  18663930415'), array('黑體'=>true, 'size'=>11), array('align'=>'right', 'spaceBefore'=>200));
		$section->addText(date("Y-m-d"), array('黑體'=>true, 'size'=>11), array('align'=>'right', 'spaceBefore'=>200));
		 
		 
		// 設置下載路徑
		$path_a = rtrim($_SERVER["SCRIPT_FILENAME"],"admin.php") ."Down/ceyan/report/word/";
		if (!file_exists($path_a)) { mkdir($path_a, 0777 ,true); }

		$fileName = $this->myIconv('中文的word文檔'.uniqid());
        $path =  $path_a . '/' . $fileName .'.doc';

		// 生成Word文檔 並保存在服務器上
		$objWriter = \PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
		$objWriter->save($path);
		exit();


		/**設置在瀏覽器下載**/
		header('Pragma: public');
		header('Expires: 0');
		header('Cache-Control:must-revalidate, post-check=0, pre-check=0');
		header('Content-Type:application/force-download');
		header('Content-Type:application/vnd.ms-word');
		header('Content-Type:application/octet-stream');
		header('Content-Type:application/download');
		header('Content-Disposition:attachment;filename='.$fileName.'.doc');
		header('Content-Transfer-Encoding:binary');
		$objWriter = \PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
		$objWriter->save('php://output');

        exit;
 
    }


    public function myIconv($info){
    	$info = iconv('UTF-8', 'GB2312//IGNORE', $info);
    	return $info;
    }
    

解決中文亂碼

	//網上有很多解決中文亂碼的文章方法都是正確的,但是要注意修改的文件是不是全面,建議使用全局搜索把utf8_encode();相關的都找一下。
	//一、增加東亞字體支持 
	//打開並編輯路徑/Writer/Word2007/Base.php文件內容,大概在第349行(行數隨着版本可能會有變化)大概函數_writeTextStyle內添加:
	//$objWriter->writeAttribute(‘w:eastAsia’, $font)
	//比如我的修改片段基本是下面這樣:
	Font  if($font != ‘Arial’) {
		$objWriter->startElement(‘w:rFonts’);
			$objWriter->writeAttribute(‘w:eastAsia’, $font);// 添加這行
			$objWriter->writeAttribute(‘w:ascii’, $font);
			$objWriter->writeAttribute(‘w:hAnsi’, $font);
			$objWriter->writeAttribute(‘w:cs’, $font);
		$objWriter->endElement();
	}

	
	二、 解決中文亂碼問題(此解法對於GBK編碼有用,不適用於UTF-8)
	編輯PHPWord/Template.php
	找到代碼$replace = utf8_encode($replace);,刪除或者註釋掉這行代碼,添加$replace = iconv( ‘gbk’,’utf-8′, $replace);,比如代碼改爲如下:
	if(!is_array($replace)) {
		//$replace = utf8_encode($replace);     
		$replace =iconv(‘gbk’, ‘utf-8′, $replace);// 註釋掉上面行後添加這行
	}
	
	調用方式如下:
	//$document->setValue(‘Template’, iconv(‘utf-8′, ‘GB2312//IGNORE’, ‘中文’));
	//上面的代碼主要解決模板的問題,
	//下面同樣的道理,解決Section添加文本的問題,
	//在PHPWord/Section.php找到代碼$givenText = utf8_encode($text);,
	//刪除或者註釋掉這行代碼,添加$givenText = iconv(‘gbk’, ‘utf-8′, $text);,比如代碼如下:
	public function addText($text, $styleFont = null, $styleParagraph = null) {
		//$givenText = utf8_encode($text);   
	 	$givenText = iconv(‘gbk’, ‘utf-8′, $text);// 註釋掉上面行後添加這行
	}

注意:除了PHPWord/Section.php可能還需要改其他文件,但修改原理相同。建議全局搜索utf8_encode();相關的都找一下
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章