将html内容转换成word文档,有两种实现方式
1、直接输入html内容到word文档中 优点:简单粗暴,基本上支持所有html标签和样式 缺点:无法操作word文档其他功能,例如页码,页眉,目录之类的 代码:
$html = '';
$data = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40">'.$html.'</html>';
$dir = "../public/";
if(!file_exists($dir)) mkdir($dir,777,true);
$fileName=$dir.date('His').'.doc';
$writefile = fopen($fileName,'wb') or die("创建文件失败"); //wb以二进制写入
fwrite($writefile,$data);
fclose($writefile);
2、使用phpword导出 优点:提供了丰富的操作word文档的功能 缺点:对html标签、样式的支持不够全面,有些样式可能会失效 代码:
<?php
namespace Alqm\Api\Tools;
use PhpOffice\PhpWord\Shared\ZipArchive;
use PhpOffice\PhpWord\TemplateProcessor;
class OfficeWord
{
public $path = 'word/';
public function createWord($data)
{
$phpWord = new \PhpOffice\PhpWord\PhpWord();
//打开时自动重新计算字段
$phpWord->getSettings()->setUpdateFields(true);
//关闭拼写和语法检查,大内容文档可以提高打开速度
$phpWord->getSettings()->setHideGrammaticalErrors(true);
$phpWord->getSettings()->setHideSpellingErrors(true);
//文档设置
$properties = $phpWord->getDocInfo();
$properties->setCreator('xiaoming');//作者
$properties->setTitle('title');//标题
$properties->setSubject('subject');//主题
//添加一页
$section = $phpWord->addSection();//创建一页
//设置页码
$footer = $section->addFooter();
$footer->addPreserveText('{PAGE} / {NUMPAGES}', [
'bold' => true,//粗体
], [
'alignment' => \PhpOffice\PhpWord\SimpleType\Jc::END,//对其方式
]);
//page 1 title
$section->addTextBreak(10);//添加多个回车
$fontStyle = [//字体样式
'size' => 30,//字号
'bold' => true,//粗体
'name' => 'stsongstdlight',//字体
];
$paragraphStyle = [//段落样式
'alignment' => \PhpOffice\PhpWord\SimpleType\Jc::CENTER,//对其方式
];
$section->addText($data->title, $fontStyle, $paragraphStyle);
//page 2 list
$section->addPageBreak();//新建一页,也可以用$section = $phpWord->addSection();
$phpWord->addTitleStyle(1, $fontStyle);
$toc = $section->addTOC();
//page 3 content
$section->addPageBreak();//分页
$section->addTitle($data->title);//标题
\PhpOffice\PhpWord\Shared\Html::addHtml($section, $content);
//save
if (!is_dir($this->path)) {
mkdir($this->path, 0777, true);
}
$word_name = $this->path . $data->title . '_' . $data->version_no . '.docx';
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save($word_name);
return $word_name ;
}
}
|