PHPWord 是一个用纯 PHP 编写的库,它提供了一组用于写入和读取不同文档文件格式的类。 当前版本的 PHPWord 支持 Microsoft Office Open XML(OOXML 或 OpenXML)、用于 Office 应用程序的 OASIS 开放文档格式(OpenDocument 或 ODF)、富文本格式 (RTF)、HTML 和 PDF。
项目地址:https://github.com/PHPOffice/PHPWord
PHPWord 是根据 LGPL 第 3 版条款获得许可的开源项目。
那么,什么是 LGPL 第 3 版呢?
GNU宽通用公共许可证(英语:GNU Lesser General Public License,简称:LGPL)是由自由软件基金会公布的自由软件授权条款。它允许企业与软件开发者使用,或将LGPL授权的软件整合至他们自己的软件内(即使该软件是私有软件也被允许),同时不会受到Copyleft特性的许可证强制对软件开源的限制。该许可证常被用于一些(但不是全部)GNU程序库。
一言蔽之,可以作为商业软件的类库,但是不能二次修改当做闭源商品来卖。
LGPL协议官网地址: https://www.gnu.org/licenses/lgpl-3.0.html
composer require phpoffice/phpword
// Creating the new document...
$phpWord = new \PhpOffice\PhpWord\PhpWord();
/* Note: any element you append to a document must reside inside of a Section. */
// Adding an empty Section to the document...
$section = $phpWord->addSection();
// Adding Text element to the Section having font styled by default...
$section->addText(
'"Learn from yesterday, live for today, hope for tomorrow. '
. 'The important thing is not to stop questioning." '
. '(Albert Einstein)'
);
/*
* Note: it's possible to customize font style of the Text element you add in three ways:
* - inline;
* - using named font style (new font style object will be implicitly created);
* - using explicitly created font style object.
*/
// Adding Text element with font customized inline...
$section->addText(
'"Great achievement is usually born of great sacrifice, '
. 'and is never the result of selfishness." '
. '(Napoleon Hill)',
array('name' => 'Tahoma', 'size' => 10)
);
// Adding Text element with font customized using named font style...
$fontStyleName = 'oneUserDefinedStyle';
$phpWord->addFontStyle(
$fontStyleName,
array('name' => 'Tahoma', 'size' => 10, 'color' => '1B2232', 'bold' => true)
);
$section->addText(
'"The greatest accomplishment is not in never falling, '
. 'but in rising again after you fall." '
. '(Vince Lombardi)',
$fontStyleName
);
// Adding Text element with font customized using explicitly created font style object...
$fontStyle = new \PhpOffice\PhpWord\Style\Font();
$fontStyle->setBold(true);
$fontStyle->setName('Tahoma');
$fontStyle->setSize(13);
$myTextElement = $section->addText('"Believe you can and you\'re halfway there." (Theodor Roosevelt)');
$myTextElement->setFontStyle($fontStyle);
// Saving the document as OOXML file...
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('helloWorld.docx');
输出结果如下图所示。
我们可以看到PHPWord是可以做一系列格式化的操作的,这对实际的业务非常重要。
本文为PHPWord的入门介绍,本专栏后续会解决实际业务中需要用到PHPWord的完整解决方案,包括但不限于:
欢迎订阅本专栏。