PHPWord使用簡介

   PHP導出word文檔,可實現自動分頁,可插入圖片,表格。

1、下載PHPWord

        (1)使用composer:

               "require":{

                    "phpoffice/phpword": "v0.14.*"

                  }

         (2)GitHub:點擊打開鏈接

2、使用

      (1)GitHub上有詳細說明,下載的包裏面有很多例子

       (2)附上中文文檔(不知怎麼上傳附件)

       (3)簡單示例

       

require_once './ThinkPHP/Library/Org/PHPWord/vendor/autoload.php';
$title = $data['version'] . ' ' . $data['semester'] . ' ' . $data['unit'];
$num = $data['num'];
$mean = $data['mean'];
$phpWord = new \PhpOffice\PhpWord\PhpWord();
// 新建文檔
$section = $phpWord->addSection();
$phpWord->addTitleStyle(2, array('bold' => true, 'size' => 14, 'name' => 'Arial', 'Color' => '333'), array('align' => 'center'));
$section->addTitle("$title", 2);
$section->addTextBreak(1);
$section->addText("姓名:                                                    題量: $num                                                    分數:          ");
$tableStyle = array(
    'borderSize' => 6,
    'borderColor' => '006699'
);
$table = $section->addTable($tableStyle);
$fancyTableCellStyle = array('valign' => 'center');
$cellRowSpan = array('vMerge' => 'restart', 'valign' => 'center');
$cellRowContinue = array('vMerge' => 'continue');
$fontStyle['name'] = 'Arial';
$fontStyle['size'] = 14;
$thStyle['name'] = 'Arial';
$thStyle['size'] = 12;
$thStyle['bold'] = true;
$paraStyle['align'] = 'center';
$table->addRow(500);
$table->addCell(3500, $fancyTableCellStyle)->addText('答題區', $thStyle, $paraStyle);
$table->addCell(1000, $fancyTableCellStyle)->addText('批改區', $thStyle, $paraStyle);
$table->addCell(3500, $fancyTableCellStyle)->addText('答題區', $thStyle, $paraStyle);
$table->addCell(1000, $fancyTableCellStyle)->addText('批改區', $thStyle, $paraStyle);
$len = ceil($num / 2);
for ($i = 0; $i < $len; $i++) {
    $table->addRow(500);
    $table->addCell(3500, $fancyTableCellStyle)->addText(($i * 2 + 1) . '.' . $mean[$i * 2], $fontStyle);
    $table->addCell(1000, $cellRowSpan)->addText(' ');
    if ($num % 2 != 0 && $i == $len - 1) {
        $table->addCell(3500, $fancyTableCellStyle)->addText('');
    } else {
        $table->addCell(3500, $fancyTableCellStyle)->addText(($i * 2 + 2) . '.' . $mean[$i * 2 + 1], $fontStyle);
    }
    $table->addCell(1000, $cellRowSpan)->addText(' ');
    $table->addRow(1000);
    $table->addCell(3500, $fancyTableCellStyle)->addText('答案:');
    $table->addCell(null, $cellRowContinue);
    if ($num % 2 != 0 && $i == $len - 1) {
        $table->addCell(3500, $fancyTableCellStyle)->addText('');
    } else {
        $table->addCell(3500, $fancyTableCellStyle)->addText('答案:');
    }

    $table->addCell(null, $cellRowContinue);
}
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save("./Public/doc/word.docx");



PHPWord Beta 0.6.2

開發者指南

 


 

首先我們要了解文檔最基本的信息和設置 4

計量單位:緹(twips 4

字體設置 4

文檔屬性設置 4

新建文檔 5

添加頁面 5

頁面樣式 5

頁面樣式屬性 6

文本 7

添加文本 7

添加文本資源 7

文本樣式 8

樣式屬性列表 9

添加換行符 10

添加分頁符 10

列表 10

添加列表 10

列表樣式 11

列表樣式屬性列表 11

超鏈接 11

添加超鏈接 11

超鏈接樣式 12

圖片 13

添加圖片 13

圖片樣式 13

圖片樣式屬性 13

添加GD生成圖片 14

添加水印 14

添加對象 15

添加標題 15

添加目錄 16

表格 17

添加表格 17

添加行 17

添加單元格 17

單元格樣式 19

表格樣式 20

頁腳 22

頁眉 23

模版 23

其他問題修改 25

解決文本縮進問題 25

表格對齊和表格縮進 27

圖片縮進和絕對相對懸浮定位 30


首先我們要了解文檔最基本的信息和設置

 因爲是國外編輯的類庫,存在對中文支持的問題,使用前,我們需要進行一些修正:

1、解決編碼問題,PHPword 會對輸入的文字進行utf8_encode編碼轉化,如果你使用GBK、GB2312或者utf8編碼的話就會出現亂碼,如果你用utf8編碼,就查找類庫中所有方法中的 utf8_encode 轉碼將其刪除,如果你採用GBK或者GB2312編碼,使用iconv進行編碼轉換。

2、解決中文字體支持,在writer/word2007/base.php中 312行添加 $objWriter->writeAttribute('w:eastAsia',$font)

3、啓動php zip支持,windows環境下在php配置文件php.ini中,將extension=php_zip.dll前面的分號“;”去除;(如果沒有,請添加extension=php_zip.dll此行並確保php_zip.dll文件存在相應的目錄),然後同樣在php.ini文件中,將 zlib.output_compression = Off 改爲zlib.output_compression = On  

 

計量單位:緹(twips

 

首先解釋一下PHPWord最基本的計量單位:“緹”(twips),我們常常在文件中看到或使用計量單位“緹”,它是開源辦公軟件中最基本的計量單位,“緹”是"TWentieth of an Inch Point"的簡寫,意思 1/20磅,與其他常用劑量單位的換算是1緹=1/1,440英寸,1緹=1/567釐米,1緹=1/15像素

 

字體設置

 

文檔默認字體是Arial,字號10號,我們可以通過以下方法設置默認字體和字號:

注,該庫存在中文字體支持問題,解決方法:見文檔開頭

 

$PHPWord->setDefaultFontName('Tahoma');

$PHPWord->setDefaultFontSize(12);

 

文檔屬性設置

 

我們可以設置下列文檔屬性

 

名稱

類型

描述

Creator

String

創建者

Company

String

公司

Title

String

標題

Description

String

描述

Category

String

分類

Last modified by

String

最後修改者

Created

Datetime

創建時間

Modified

Datetime

修改時間

Subject

String

主題

Keywords

String

關鍵詞

 

我們可以通過以下方法設置文檔屬性

 

$properties = $PHPWord->getProperties();

$properties->setCreator('My name');

$properties->setCompany('My factory');

$properties->setTitle('My title');

$properties->setDescription('My description');

$properties->setCategory('My category');

$properties->setLastModifiedBy('My name');

$properties->setCreated( mktime(0, 0, 0, 3, 12, 2010) );

$properties->setModified( mktime(0, 0, 0, 3, 14, 2010) );

$properties->setSubject('My subject');

$properties->setKeywords('my, key, word');

 

 

新建文檔

 

添加頁面

 

添加默認頁面(默認頁面方向和頁邊距):

 

$section = $PHPWord->createSection();

 

頁面樣式

 

調整頁面樣式和佈局有兩種方法:

 

創建樣式數組:

 

$sectionStyle = array('orientation' => null,

    'marginLeft' => 900,

    'marginRight' => 900,

    'marginTop' => 900,

    'marginBottom' => 900);

$section = $PHPWord->createSection($sectionStyle);

 

直接調用樣式屬性設置方法進行設置:

 

$section = $PHPWord->createSection();

$sectionStyle = $section->getSettings();

$sectionStyle->setLandscape();

$sectionStyle->setPortrait();

$sectionStyle->setMarginLeft(900);

$sectionStyle->setMarginRight(900);

$sectionStyle->setMarginTop(900);

$sectionStyle->setMarginBottom(900);

 

 

頁面樣式屬性

 

注意:所有的屬性對大小寫敏感 !

 

屬性

描述

orientation

頁面方向:

默認豎向:null    

橫向:landscape

marginTop

上邊距,單位:twips.

marginLeft

左邊距,單位:twips.

marginRight

右邊距,單位:twips.

marginBottom

下邊距,單位:twips..

borderTopSize

上邊框尺寸,單位:twips.

borderTopColor

上邊框顏色

borderLeftSize

左邊框尺寸,單位 :twips.

borderLeftColor

左邊框顏色

borderRightSize

右邊框尺寸,單位:twips.

borderRightColor

右邊框顏色

borderBottomSize

底邊框尺寸,單位:twips.

borderBottomColor

底邊框顏色

 

頁面高度和寬度是自動設置的,你可以通過以下兩個屬性來修改,但不推薦進行修改。

 

屬性

描述

pageSizeW

頁面寬度,單位: twips.

pageSizeH

頁面高度,單位:twips.

 

 

文本

 

添加文本

 

向文檔添加文本使用方法函數: addText.(注意PHPword 會對輸入的文字進行utf8_encode編碼轉化,如果你使用GBK、GB2312或者utf8編碼的話就會出現亂碼,如果你用utf8編碼,就查找類庫中所有方法中的 utf8_encode 轉碼將其刪除,如果你採用GBK或者GB2312編碼,使用iconv進行編碼轉換。)

 

$section->addText( $text, [$fontStyle], [$paragraphStyle] );

 

addText()

參數

類型

描述

$text

String

文本內容.

$fontStyle

String / Array

字體樣式.

$paragraphStyle

String / Array

段落樣式

 

添加文本資源

 

文本資源可以包含文本和鏈接,可以統一賦予段落樣式,添加文本資源使用函數方法createTextrun.

 

createTextRun()

參數

類型

描述

$paragraphStyle

String / Array

文本樣式.

 

添加文本資源後,就可以添加具有獨特樣式的文本或鏈接了。

$textrun = $section->createTextRun();

$textrun->addText('I am bold', array('bold'=>true));

$textrun->addText('I am italic, array('italic'=>true));

$textrun->addText('I am colored, array('color'=>'AACC00'));

 

當然也可以繼承使用段落或文字樣式

 

 

文本樣式

 

設置文本樣式有兩種方法:

內嵌樣式:

 

$fontStyle = array('color'=>'006699', 'size'=>18, 'bold'=>true);

$section->addText('helloWorld', $fontStyle);

 

$text = $section->addText('helloWorld');

$style = $text->getStyle();

$style->setColor('006699');

$style->setSize(18);

$style->setBold();

 

或者定義一個樣式定義設置文本樣式,定義一種樣式後,必須把第二個參數設置爲樣式名稱,使用方法函數addFontStyle:

 

$PHPWord->addFontStyle( $styleName, $fontStyle);

 

addFontStyle()

參數

類型

描述

$styleName

String

樣式名稱

$fontStyle

Array

樣式風格.

 

示例:

 

$fontStyle = array('color'=>'006699', 'size'=>18, 'bold'=>true);

$PHPWord->addFontStyle('myOwnStyle', $fontStyle);

$text = $section->addText('helloWorld', 'myOwnStyle');

 

添加段落樣式,使用方法函數addParagraphStyle:

 

addParagraphStyle()

參數

類型

描述

$styleName

String

段落樣式名稱.

$paragraphStyle

Array

段落樣式.

 

 

樣式屬性列表

 

屬性大小寫敏感 !

 

Font Style

名稱

描述

size

字號.

name

字體

bold

粗體

italic

斜體

superScript

上標

subScript

下標

underline

下劃線,使用常量: PHPWord_Style_Font::UNDERLINE_...

Color

字體顏色

fgColor

前景色. 只能使用預定義常量:
PHPWord_Style_Font::FGCOLOR_...

 

Paragraph Style

名稱

描述

align

水平對齊:

§ left

§ right

§ center

§ both / justify

spaceBefore

段前間距,單位: twips.

spaceAfter

段後間距,單位:twips

spacing

行間距,單位: twips.

 

添加換行符

 

添加換行符,使用方法函數 addTextBreak:

 

$section->addTextBreak();

 

添加多個換行符:

 

$section->addTextBreak(15);

.

 

 

添加分頁

 

添加分頁符,使用方法函數:addPageBreak:

 

$section->addPageBreak();

 

 

列表

 

添加列表

 

添加列表使用方法函數: addListItem:

 

$section->addListItem( $text, [$depth], [$styleText], [$styleList], [$styleParagraph] );

 

addListItem()

參數

類型

描述

$text

String

文本內容.

$depth

Integer

編號

$styleText

String / Array

文本樣式.

$styleList

Array

列表樣式.

$styleParagraph

String / Array

段落樣式

 

列表樣式

 

示例:

 

$listStyle = array('listType' => PHPWord_Style_ListItem::TYPE_NUMBER);

$section->addListItem('Listitem 1', 0, null, $listStyle);

 

列表樣式屬性列表

 

屬性大小寫敏感!

 

名稱

描述

listType

列表符號樣式.

使用常量 PHPWord_Style_ListItem::TYPE_...

 

 

超鏈接

 

添加超鏈接

添加超鏈接,使用方法函數: addLink:

 

$section->addLink( $linkSrc, [$linkName], [$styleFont], [$styleParagraph]);

 

addListItem()

參數

類型

描述

$linkSrc

String

鏈接地址

$linkName

String

鏈接名稱.

$styleFont

String / Array

文本樣式

$styleParagraph

String / Array

段落樣式

 

注意在添加鏈接地址時最好trim一下前後有空格很可有可能導致文檔打不開

 

 

超鏈接樣式

 

定義超鏈接風格的兩種方法

 

內嵌樣式:

 

$linkStyle = array('color'=>'0000FF',

 'underline'=>PHPWord_Style_Font::UNDERLINE_SINGLE);

$section->addLink('http://www.google.de', null, $linkStyle);

 

或者定義一個樣式定義設置超鏈接樣式,定義一種樣式後,必須把第三個參數設置爲樣式名稱

 

 

$linkStyle = array('color'=>'0000FF',

 'underline'=>PHPWord_Style_Font::UNDERLINE_SINGLE);

$PHPWord->addLinkStyle('myHyperlinkStyle', $linkStyle);

$section->addLink('http://www.google.de', null, 'myHyperlinkStyle');

 

 

addLinkStyle()

參數

類型

描述

$styleName

String

超鏈接樣式名稱.

$styles

Array

鏈接樣式.可以使用各種字體樣式屬性

 

 

圖片

 

添加圖片

 

添加圖片的函數方法: addImage:

 

$section->addImage( $src, [$style] );

 

addImage()

參數

類型

描述

$src

String

圖像的服務器路徑,支持相對和絕對路徑 

$style

Array

圖片樣式.

 

注意在添加圖片路徑時最好trim一下前後有空格很可有可能導致文檔打不開

 

圖片樣式

 

添加圖片樣式只能使用數組方式 :

 

$imageStyle = array('width'=>350, 'height'=>350, 'align'=>'center');

$section->addImage('EARTH.jpg', $imageStyle);

 

圖片樣式屬性

 

大小寫敏感!

 

名稱

描述

width

圖像寬度,單位像素

height

圖像高度,單位像素

align

圖像對齊方式

§ left

§ right

§ center

 

如果沒有指定圖片高或寬的屬性,系統將使用PHP原生函數”getimagesize”來獲取相關屬性。

 

PHPWord 支持的圖片格式: gif, jpeg, png, bmp, tiff.

 

 

添加GD生成圖片

 

你也可以添加由GD庫生成的圖片,使用函數方法:addMemoryImage:

 

$section->addMemoryImage( $link, [$style] );

 

addMemoryImage()

參數

類型

描述

$link

String

生成圖片的php文件的路徑.

注意: 應設置文件的絕對路徑(就像你在瀏覽器中調用php文件),否則會發生錯誤。

$style

Array

圖像樣式.

 

示例:

 

$section->addMemoryImage('http://localhost/image.php');

 

GD圖片樣式的設置和本地圖片一樣.

 

PHPWord 支持的 GD 圖片類型: png, jpeg, gif.

 

 

添加水印

 

添加水印的頁面需要一個頭部引用,添加水印方法函數:addWatermark

 

addWatermark()

參數

類型

描述

$src

String

水印圖片的文件地址 

$style

Array

水印圖片樣式

 

水印圖片是在頁面是絕對定位的,所以水印圖片至少需要兩個樣式屬性

 

名稱

描述

marginLeft

左邊距,單位像素

marginTop

上邊距,單位像素

注:圖片樣式並沒有提供圖像並排,文字環繞等功能,可以通過與表格想結合進行解決。

 

添加對象

 

我們可以使用方法函數 addObject,添加對象和鏈接

 

$section->addObject( $src, [$style] );

 

addObject()

參數

類型

描述

$src

String

文件的服務器,支持相對和絕對路徑.

$style

Array

對象樣式.

 

對象屬性是有一個樣式:

 

屬性區分大小寫!

 

名稱

描述

align

對齊方式

§ left

§ right

§ center

 

PHPWord 支持的對象類型: XLS, DOC, PPT.

 

 

添加標題

 

我們可以使用標題來爲結構化文檔或爲文檔建立目錄,添加標題使用方法函數addTitleStyle addTitle:

 

$PHPWord->addTitleStyle( $titleCount, [$fontStyle] );

 

addTitleStyle()

參數

類型

描述

$src

Integer

標題級別,最多支持9級標題

$fontStyle

Array

標題字體樣式

 

 

需要添給標題添加一個樣式,否則文檔不會將其作爲一個真正的標題來處理。

 

定義標題樣式後,定義標題就很簡單了,可以使用函數方法:addTitle;

 

$section->addTitle( $text, [$depth] );

 

addTitle()

參數

類型

描述

$text

String

標題文本內容

$depth

Integer

標題級別編號,通過該參數調用addTtileStyle()設置的標題樣式

 

 

添加目錄

 

添加目錄使用方法函數: addTOC:

 

$styleTOC = array('tabLeader'=>PHPWord_Style_TOC::TABLEADER_DOT);

$styleFont = array('spaceAfter'=>60, 'name'=>'Tahoma', 'size'=>12);

$section->addTOC($styleFont, $styleTOC);

 

addTOC()

參數

類型

描述

$styleFont

Array

目錄字體樣式

$styleTOC

Array

目錄樣式

 

 

目錄樣式屬性列表:

 

樣式屬性區分大小寫 !

 

名稱

描述

tabLeader

標題的類型和對應頁碼.默認使用系統常量 PHPWord_Style_TOC::TABLEADER_...

tabPos

標題與頁碼的位置,單位: twips.

Indent

標題縮進,單位: twips.

 

 

表格

 

添加表格

 

添加表格使用函數方法:addTable:

 

$table = $section->addTable( [$tableStyle] );

 

參數 $tableStyle 是可選的. 表格樣式這章有關於表格樣式的詳細說明。addTable建立一個本地對象,我們需要使用這個對象來調用相關函數方法。

 

添加行

$table->addRow( [$height] );

 

行的高度可以通過$height參數來設置,單位:twips.

 

添加單元格

 

單元格添加前必須先添加行,添加單元格的函數方法爲: addCell

 

$cell = $table->addCell(h, [$cellStyle] );

 

addCell()

參數

類型

描述

$width

Integer

單元格寬度: twips.

$cellStyle

Array

單元格樣式

 

addcell創建一個本地對象,需要使用該對象來 調用以下函數

 

名稱

描述

addText

添加文本

addTextBreak

添加換行符

addLink

添加鏈接

addImage

添加圖片

addMemoryImage

添加水印

addListItem

添加列表

addObject

添加對象

addPreserveText

添加頁碼,只對頁眉和頁腳有效

 

示例1:

 

$table = $section->addTable();

$table->addRow();

$cell = $table->addCell(2000);

$cell->addText('Cell 1');

$cell = $table->addCell(2000);

$cell->addText('Cell 2');

$cell = $table->addCell(2000);

$cell->addText('Cell 3');

 

示例2:

 

$table = $section->addTable();

$table->addRow(400);

$table->addCell(2000)->addText('Cell 1');

$table->addCell(2000)->addText('Cell 2');

$table->addCell(2000)->addText('Cell 3');

 

$table->addRow(1000);

$table->addCell(2000)->addText('Cell 4');

$table->addCell(2000)->addText('Cell 5');

$table->addCell(2000)->addText('Cell 6');

 

 

單元格樣式

 

使用addCell的第二個參數來給單元格設置樣式

 

示例:

 

$cellStyle = array('textDirection'=>PHPWord_Style_Cell::TEXT_DIR_BTLR,  'bgColor'=>'C0C0C0');

 

$table = $section->addTable();

$table->addRow(1000);

$table->addCell(2000, $cellStyle)->addText('Cell 1');

$table->addCell(2000, $cellStyle)->addText('Cell 2');

$table->addCell(2000, $cellStyle)->addText('Cell 3');

$table->addRow();

$table->addCell(2000)->addText('Cell 4');

$table->addCell(2000)->addText('Cell 5');

$table->addCell(2000)->addText('Cell 6');

 

單元格樣式屬性列表:

 

屬性大小寫敏感 !

 

名稱

描述

valign

單元格內容對齊方式: left, right, center

textDirection

文本方向. 使用預定常量 PHPWord_Style_Cell:: TEXT_DIR_...

bgColor

單元格背景色

borderTopSize

單元格上邊框尺寸,單位 twips.

borderTopColor

單元格上邊框 顏色

borderLeftSize

單元格左邊框尺寸,單位twips

borderLeftColor

單元格左邊框顏色

borderRightSize

單元格右邊框尺寸,單位twips

borderRightColor

單元格右邊框顏色

borderBottomSize

單元格下邊框尺寸 ,單位twips

borderBottomColor

單元格下邊框顏色

 

 

 

表格樣式

 

我們可以設置整個表格的樣式,通過創建表格函數addTable的參數$tableStyle,表格具有如下樣式屬性 

屬性名稱大小寫敏感!

 

名稱

描述

cellMarginTop

單元格上邊距,單位: twips.

cellMarginLeft

單元格左邊距,單位: twips.

cellMarginRight

單元格右邊距,單位: twips.

cellMarginBottom

單元格下邊距,單位: twips.

 

示例:

$tableStyle = array('cellMarginTop'=>80,

  'cellMarginLeft'=>80,

  'cellMarginRight'=>80,

  'cellMarginBottom'=>80);

$table = $section->addTable($tableStyle);

 

我們可以使用函數方法: addTableStyle,爲表格定義一個完整的樣式。

 

$PHPWord->addTableStyle($styleName,  $styleTable, [$styleFirstRow] );

 

addTableStyle()

參數

類型

描述

$styleName

String

表樣式名稱

$styleTable

Array

這個表的樣式

$styleFirstRow

Array

表頭樣式(第一行)

 

示例:

 

$styleTable = array('borderColor'=>'006699',

  'borderSize'=>6,

  'cellMargin'=>50);

$styleFirstRow = array('bgColor'=>'66BBFF');

$PHPWord->addTableStyle('myTable', $styleTable, $styleFirstRow);

 

$table = $section->addTable('myTable');

$table->addRow(400);

$table->addCell(2000)->addText('Cell 1');

$table->addCell(2000)->addText('Cell 2');

$table->addCell(2000)->addText('Cell 3');

$table->addRow(1000);

$table->addCell(2000)->addText('Cell 4');

$table->addCell(2000)->addText('Cell 5');

$table->addCell(2000)->addText('Cell 6');

 

表格樣式屬性,注意屬性名稱大小寫敏感!

 

名稱

描述

cellMarginTop

單元格上邊距,單位:twips.

cellMarginLeft

單元格左邊距,單位:twips.

cellMarginRight

單元格右邊距,單位:twips.

cellMarginBottom

單元格下邊距,單位:twips.

cellMargin

單元格間距,單位:twips.

bgColor

表格背景色

borderTopSize

表格上邊框尺寸,單位:twips.

borderTopColor

表格上邊框顏色

borderLeftSize

表格左邊框尺寸,單位:twips.

borderLeftColor

表格左邊框顏色

borderRightSize

表格右邊框尺寸,單位:twips.

borderRightColor

表格右邊框顏色

borderBottomSize

表格下邊框尺寸,單位:twips..

borderBottomColor

表格下邊框顏色

borderInsideHSize

表格內水平網格尺寸,單位: twips.

borderInsideHColor

表格內水平網格顏色

borderInsideVSize

表格內垂直網格尺寸,單位: twips.

borderInsideVColor

表格內垂直網格顏色

borderSize

表格邊框尺寸,單位:twips.

borderColor

表格邊框顏色

 

注意:表格在word佈局中的功能可以進行體現,例如進行圖片,對象等的佈局可以考慮與表格結合進行處理

 

頁腳

 

添加文檔頁腳使用函數方法: createFooter:

 

$footer = $section->createFooter();

 

確保在本地對象中保存頁腳,並使用下列函數

名稱

描述

addText

添加文本

addTextBreak

添加換行符

addImage

添加圖像

addMemoryImage

添加GD生成圖像

addListItem

添加列表

addPreserveText

添加頁碼,只能在頁眉或頁腳使用

addTable

添加表格

createTextrun

添加文本資源

 

向頁腳(頁眉)添加頁碼使用函數方法:addPreserveText:

 

addPreserveText( $text, [$style] );

 

addPreserveText()

參數

類型

描述

$text

String

頁腳(頁眉)的文本內容

$style

Array

文字樣式.

 

示例:

 

$footer->addPreserveText('Page {PAGE} of {NUMPAGES}.');

 

 

頁眉

 

添加頁眉,使用函數方法: createHeader:

 

$header = $section->createHeader();

 

確保頁眉是建立在一個文檔中,頁眉和頁腳使用相同的屬性和函數,詳見頁腳章節 

 

注意:只用添加了頁眉的頁面,才能添加和使用圖片水印

 

模版

 

我們可以利用搜索替換功能創建一個docx格式的模版文檔,來替換文檔中你想替換的文本. 但是要注意,只有文本或鏈接可以被替換。加載模版文檔使用函數方法:loadTemplate function.

 

loadTemplate()

參數

方法

描述

$strFilename

String

模版文件路徑和名稱

 

加載完成模版文檔後,你可以使用函數方法: setValue 來搜索替換相關內容

setValue()

參數

Type

Description

$search

Mixed

搜索的值

$replace

Mixed

替換的值

 

$template = $PHPWord->loadTemplate('Template.docx');

$template->setValue('Name', 'Somebody someone');

$template->setValue('Street', 'Coming-Undone-Street 32');

 

被搜索替換的標籤格式爲: ${YOUR_SEARCH_PATTERN}

不能添加新的PHPWORD元素到加載的模版文檔中、

 

模版使用的幾個注意事項:

1、從模板生成word文檔,支持在word模板文檔裏寫替換標籤,標籤格式爲${xxx},不過一定要注意,不要直接在word裏編輯這些標籤,一定要在文本文檔裏先寫好標籤,直接拷貝粘貼上去,千萬不要編輯,否則無法替換,原因也很簡單,把word文檔另存爲xml,然後看xml裏標籤的位置,會發現標籤中間被插入了很多沒用的xml節點,還有中文字體的節點。。。

2、模版文檔要一次性完成在保存,否則會出現替換失敗問題。

3、中文亂碼問題,這個一定是存在的,如果php環境已經是utf8了,要找到關鍵地方,轉utf8的代碼,去掉,否則就是轉兩次編碼了,典型的是phpword\template.php文件,把這行註釋掉:$replace = utf8_encode($replace);

4、linux下報“Could not close zip file.”錯誤,這個你永遠想不到,要將模板文件所在目錄權限改爲可寫,因爲要在那個目錄下生成臨時文件

5、引用模板文件和另存文件路徑什麼的,最好用絕對路徑

 

 

 

 

 

 

其他問題修改

 

PHPWord庫相對功能比較簡單,部分功能需要進行二次開發才能解決

這裏要感謝網友yukirin_fans,以下是他發佈的開發代碼

解決文本縮進問題

 

1/PHPWord/Style/Paragraph.php  添加以下屬性

 

    /**

     * 縮進 indentleft and indentright段落縮進值,單位爲twips

     *  

     * 縮進indentFirstLine and indentFirstChars  首行縮進twips

     *  

     * @var int          

     */

    private $_indentLeft;

    private $_indentRight;

    private $_indentFirstLine;

    private $_indentFirstLineChars;

    // 獲取左縮進值 

    public function getIndentLeft()

    {

        return $this->_indentLeft;

    }

    

    // 設置左縮進值 

    public function setIndentLeft($pValue = null)

    {

        $this->_indentLeft = $pValue;

        return $this;

    }   

    

    // 獲取右縮進值 

    public function getIndentRight()

    {

        return $this->_indentRight;

    }

     

    // 設置右縮進值 

    public function setIndentRight($pValue = null)

    {

        $this->_indentRight = $pValue;

        return $this;

    }

    // 首行縮進相關方法 

    public function setIndentFirstLine($pValue = null)

    {

        $this->_indentFirstLine = $pValue;

        return $this;

    }

     

    public function getIndentFirstLine()

    {

        return $this->_indentFirstLine;

    }

     

    public function setIndentFirstLineChars($pValue = null)

    {

        $this->_indentFirstLineChars = $pValue;

        return $this;

    }

     

    public function getIndentFirstLineChars()

    {

        return $this->_indentFirstLineChars;

    }

 

2、/PHPword/Writer/Word2007/Base.php,在_writeParagraphStyle方法中大約第117行添加

 

                $indentLeft = $style->getIndentLeft();

 

$indentRight = $style->getIndentRight();

 

$indentFirstLine = $style->getIndentFirstLine();

 

$indentFirstLineChars = $style->getIndentFirstLineChars();

 

然後同文件大約第156行

 

if (!is_null($indentLeft) || !is_null($indentRight) || !is_null($indentFirstLine) || !is_null($indentFirstLineChars))

 

{

 

    $objWriter->startElement('w:ind');

 

    

 

    if (!is_null($indentLeft))

 

    {

 

        $objWriter->writeAttribute('w:left', $indentLeft);

 

    }

 

    if (!is_null($indentRight))

 

    {

 

        $objWriter->writeAttribute('w:right', $indentRight);

 

    }

 

    if (!is_null($indentFirstLine))

 

    {

 

        $objWriter->writeAttribute('w:firstLine', $indentFirstLine);

 

    }

 

    if (!is_null($indentFirstLineChars))

 

    {

 

        $objWriter->writeAttribute('w:firstLineChars', $indentFirstLineChars);

 

    }

 

    $objWriter->endElement();

 

}

 

這樣就可以在addtext時在段落樣式中用縮進屬性了

 

$section->addText('test', array('bold' => true), array('indentLeft' => 1440));

 

注意計量單位,首行縮進2個字符,設置indentFirstLineChars的值是 200而不是2

 

 

表格對齊和表格縮進

 

/PHPWord/Style/TableFull.php添加相關屬性和方法

 

    // 表格居中屬性,用法:表格style數組中:'alignMent' => 'center'        

    private $_alignMent = null;

 

    // 表格縮進屬性

    private $_tableIndent = null;

 

    public function setTableAlign($pValue = null)

    {

        $this->_alignMent = $pValue;

    }

    

    public function getTableAlign()

    {

        return $this->_alignMent;

    }

    

    public function getTableIndent()

    {

        return $this->_tableIndent;

    }

    

    public function setTableIndent($pValue = null)

    {

        $this->_tableIndent = $pValue;

        return $this;

    }

 

構造函數中添加

unset($this->_firstRow->_alignMent);  

unset($this->_firstRow->_tableIndent);

 

/PHPWord/Writer/Word2007/Styles.php大約144行_writeFullTableStyle方法內添加

$tableAlign = $style->getTableAlign();

$tableIndent = $style->getTableIndent();

 

同文件$objWriter->startElement('w:tblPr');下面

 

if ($tableAlign) {          

$objWriter->startElement('w:jc');

$objWriter->writeAttribute('w:val', $tableAlign);

$objWriter->endElement();

}

       if (!is_null($tableIndent))

               {

                $objWriter->startElement('w:tblInd');

                

                if (!is_null($tableIndent))

                {

                    $objWriter->writeAttribute('w:w', $tableIndent);

                    $objWriter->writeAttribute('w:type', 'dxa');

                }

                $objWriter->endElement();   // w:ind

               }

 

這樣就可以設置表格對齊方式和縮進了

 

    $styleTable = array('borderSize'=>6, 'alignMent' => 'right', 'tableInden' => 1440);

    $styleFirstRow = array('bgColor'=>'#1F497D');

    $PHPWord->addTableStyle('tableStyle', $styleTable, $styleFirstRow);

    $table = $section->addTable('tableStyle');

 

 

2、單元格合併

/PHPWord/Style/Cell.php添加屬性和方法

 

private $_rowMerge = null;

private $_cellMerge = null;

 

public function getRowMerge()

{

    return $this->_rowMerge;

}

 

public function setRowMerge($pValue = null)

{

    $this->_rowMerge = $pValue;

    return $this;

}

 

public function getCellMerge()

{

    return $this->_cellMerge;

}

 

public function setCellValue($pValue = null)

{

    $this->_cellMerge = $pValue;

    return $this;

}

 

 /PHPWord/Writer/Word2007/base.php中_writeCellStyle方法添加

 

$rowMerge = $style->getRowMerge();  

        $cellMerge = $style->getCellMerge();

 

在同方法中修改$styles(感謝網友提出,還真忘了加上這個),通過這個才能進入if ($styles)代碼塊裏面:

 

$styles = (!is_null($bgColor) || !is_null($valign) || !is_null($textDir)

           || $borders || !is_null($rowMerge) || !is_null($cellMerge)) ? true : false;

 

在同方法if ($styles)中添加

 

if (!is_null($cellMerge))

{

    //$objWriter->startElement('w:gridSpan');

    $objWriter->startElement('w:hMerge');

    if ((string)$cellMerge !== 'continue')

    {

                                $objWriter->writeAttribute('w:val', $cellMerge);

    }

                            $objWriter->endElement();

}

 

if (!is_null($rowMerge))

{

    $objWriter->startElement('w:vMerge');

    if ((string)$rowMerge !== 'continue')

    {

                                $objWriter->writeAttribute('w:val', $rowMerge);

    }

                            $objWriter->endElement();

}

 

 

使用方法:

   $table->addRow(400);

   $table->addCell(1600, array('cellMerge' => 'restart', 'valign' => "center"))->addText('橫向合併');

   $table->addCell(1600, array('cellMerge' => 'continue'));

   $table->addCell(1600, array('cellMerge' => 'continue'));

   $table->addCell(1600, array('cellMerge' => 'continue'));

 

 

附調試心得:如果生成的word文件和自己預想的樣式不太一致,可以直接用解壓縮軟件如rar、zip打開word文件解壓出來,直接查看裏面的相關文件。

 

 

圖片縮進和絕對相對懸浮定位

如果不修改代碼,也可以通過表格與圖片配合進行功能實現

/Style/image.php添加以下屬性和方法

// 圖片縮進+絕對定位

private $_indentLeft = null;

private $_indentRight = null;

private $_position = null;

private $_top = null;

private $_left = null;

private $_zIndex = null;

 

    public function getIndentLeft()

    {

        return $this->_indentLeft;

    }

    

    public function setIndentLeft($pValue = null)

    {

        $this->_indentLeft = $pValue;

        return $this;

    }

    

    public function getIndentRight()

    {

        return $this->_indentRight;

    }

    

    public function setIndentRight($pValue = null)

    {

        $this->_indentRight = $pValue;

        return $this;

    }

    

    public function getPosition()

    {

        return $this->_position;

    }

    

    public function setPosition($pValue = null)

    {

        $this->_position = $pValue;

        return $this;

    }

 

    public function getTop()

    {

        return $this->_top;

    }

 

    public function getLeft()

    {

        return $this->_left;

    }

 

    public function setTop($pValue = null)

    {

        $this->_top = $pValue;

        return $this;

    }

 

    public function setLeft($pValue = null)

    {

        $this->_left = $pValue;

        return $this;

    }

 

    public function getZIndex()

    {

        return $this->_zIndex;

    }

 

    public function setZIndex($pValue = null)

    {

        $this->_zIndex = $pValue;

        return $this;

    }

 

base.php方法修改爲如下方法

protected function _writeImage(PHPWord_Shared_XMLWriter $objWriter = null, $image, $is_textrun = false) {

$rId = $image->getRelationId();

 

$style = $image->getStyle();

$width = $style->getWidth();

$height = $style->getHeight();

$align = $style->getAlign();

 

$indentLeft = $style->getIndentLeft();

$indentRight = $style->getIndentRight();

$position = $style->getPosition();

$top = $style->getTop();

$left = $style->getLeft();

$zIndex = $style->getZIndex();

 

if (!$is_textrun)

{

  $objWriter->startElement('w:p');

}

if(!is_null($align) || !is_null($indentLeft) || !is_null($indentRight)) {

$objWriter->startElement('w:pPr');

 

if (!is_null($align))

{

$objWriter->startElement('w:jc');

$objWriter->writeAttribute('w:val', $align);

$objWriter->endElement();  // w:jc

}

 

if (!is_null($indentLeft) || !is_null($indentRight))

{

    $objWriter->startElement('w:ind');

    

    if (!is_null($indentLeft))

    {

        $objWriter->writeAttribute('w:left', $indentLeft);

    }

    if (!is_null($indentRight))

    {

        $objWriter->writeAttribute('w:right', $indentRight);

    }

    $objWriter->endElement();   // w:ind

}

 

$objWriter->endElement();   // w:pPr

}

 

$objWriter->startElement('w:r');

 

$objWriter->startElement('w:pict');

 

$objWriter->startElement('v:shape');

$objWriter->writeAttribute('type', '#_x0000_t75');

if (!empty($position) && $top !== null && $left !== null && $zIndex !== null)

{

    $objWriter->writeAttribute('style',

           'width:'.$width.'px;height:'.$height.'px;position:'.$position.';top:'.$top.'px;left:'.$left.'px;z-index:'.$zIndex.';');

}

else

{

  $objWriter->writeAttribute('style', 'width:'.$width.'px;height:'.$height.'px');

}

 

$objWriter->startElement('v:imagedata');

$objWriter->writeAttribute('r:id', 'rId'.$rId);

$objWriter->writeAttribute('o:title', '');

$objWriter->endElement();

$objWriter->endElement();  // v:shape

 

$objWriter->endElement();// w:pict

 

$objWriter->endElement();    // w:r

if (!$is_textrun)

{        

  $objWriter->endElement();         // w:p

}

}

 

同文件_writeTextRun方法中修改

 

if(count($elements) > 0) {

foreach($elements as $element) {

if($element instanceof PHPWord_Section_Text) {

$this->_writeText($objWriter, $element, true);

} elseif($element instanceof PHPWord_Section_Link) {

$this->_writeLink($objWriter, $element, true);

} elseif ($element instanceof PHPWord_Section_Image) {

    $this->_writeImage($objWriter, $element,true);

}

}

}

 

調用方法

 

    $tmp_textrun = $section->createTextRun(array('indentLeft' => 2600));

    $tmp_textrun->addText("段落", array('size' => 11), array('indentLeft' => 0));

    $tmp_textrun->addImage('./test.jpg', array('position' => 'absolute', 'top' => 0, 'left' => 25, 'zIndex' => 4));

 

2、使用PHPWord循環生成word文件樣式bug問題。

在項目中需要循環生成不同的word文件,有個很奇怪的問題就是除了第一個生成的以外後面生成的word表格樣式會有各種bug,和寫完預期的不一樣。

這是因爲存儲表格樣式用的是一個靜態變量,當重新實例化PHPWord時沒有重置此變量引起的。通過以下代碼可修復此問題,如果沒有循環生成不同樣式word需求可不做修改。

/PHPWord/Style.php添加一個靜態變量和一個靜態方法

 

    private static $_initElements = array();

 

    /**

     * clear the $_styleElements static property

     */

    public static function clearStyles() {

       //self::$_styleElements = array();    

       self::$_styleElements = self::$_initElements;  

    }

 

/PHPWord/PHPWord.php構造方法中添加一行

 

    PHPWord_Style::clearStyles();

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章