相关文章:
phpword生成word文档,phpword的使用
背景
项目中有需要自定义样式,导出用户的简历的功能,简历嘛,最好是导出word或者pdf的,最后选择了导出成word
调研
导出word有好几种方法,今天先说使用MHT保存word的方法
使用前期知识补充
1. 什么是MHT
MHT,全称为mono html。MHTML文件又称为聚合HTML文档、Web档案或单一文件网页。单个文件网页可将网站的所有元素(包括文本和图形)都保存到单个文件中。这种封装使您可将整个网站发布为单个内嵌MIME (MIME:通过 Internet 连接传递多媒体资源的一列标准。MIME类型通知程序对象所包含的内容(如图形、声音或视频)的聚合HTML文档(MHTML)文件,或将整个网站作为一个电子邮件或附件发送。Internet Explorer 4.0及更高版本支持此格式。
2. 什么是HTML
HTML,全称HyperTextMark-upLanguage,即超文本标记语言或超文本链接标示语言,是目前网络上应用最为广泛的语言,也是构成网页文档的主要语言。设计HTML语言的目的是为了能把存放在一台电脑中的文本或图形与另一台电脑中的文本或图形方便地联系在一起,形成有机的整体,人们不用考虑具体信息是在当前电脑上还是在网络的其它电脑上。我们只需使用鼠标在某一文档中点取一个图标,Internet就会马上转到与此图标相关的内容上去,而这些信息可能存放在网络的另一台电脑中。 HTML文本是由HTML命令组成的描述性文本,HTML命令可以说明文字、图形、动画、声音、表格、链接等。HTML的结构包括头部(Head)、主体(Body)两大部分,其中头部描述浏览器所需的信息,而主体则包含所要说明的具体内容
3. MHT与HTML的区别
mht格式和html很类似,只不过在mht格式中,外部链接进来的文件,比如图片、Javascript、CSS会被base64进行编码存储。因此,单个mht文件就可以保存一个网页中的所有资源,当然,相比html,它的尺寸也会比较大。
- a 😗*本质上,这两者,没有什么区别,都是一种直观的网页浏览的格式.
- b 😗*简单理解的话,他们的区别在于保存上,mht可以直接保存所有所见,html的话则不能保存全部,服务器端文件不能保存到本地,需要依赖网络,
4.了解word
word本身的功能还是很强大的,它可以打开html格式的文件,并且能够保留格式,即使后缀为doc,它也能识别正常打开。这就为我们提供了方便。
但是有一个问题,html格式的文件中的图片只有一个地址,真正的图片是保存在其他地方的,也就是说,如果将HTML格式写入doc中,那么doc中将不能包含图片。那我们如何创建包含图片的doc文档呢?我们可以使用和html很接近的mht格式。
5. mht格式能被word识别吗
我们来实验一下,随便打开一个网页,将起保存为mht文件,然后修改后缀名为doc,再用word打开,OK,word也可以识别mht文件,并且可以显示图片。
既然doc可以识别mht,下面就是考虑如何将图片放入mht了。由于html代码中的图片的地址都是写在img标签的src属性中,因此,只要提取html代码中的src属性值,就可以获得图片地址。当然,有可能您获取到的是相对路径,没关系,加上URL的前缀,改成绝对路径就可以了。有了图片地址,我们就可以通过file_get_content函数获取到图片文件的具体内容,然后调用base64_encode函数将文件内容编码成base64编码,最后插入到mht文件的合适位置即可
使用
步骤1. 先渲染好页面样式
list($oResume,$oIntension,$oWorkexp,$oEduexp,$oAttach) = self::ViewResume($iMedliveId);
$sHtmlContent = view('enterprise.resume.resume_doc',
compact('oResume','oIntension','oWorkexp','oEduexp','oAttach','title','updated_at'))
->render();
return $sHtmlContent;
步骤2. 根据HTML代码获取word文档内容
通过以上的原理介绍,封装成导出函数,这个函数可以将HTML代码导出成一个mht文档,参数有3个,其中后2个为可选参数:
- content:要转换的HTML代码
- absolutePath: 如果HTML代码中的图片地址都是相对路径,那么这个参数就是HTML代码中缺少的绝对路径。
- isEraseLink:是否去掉HTML代码中的超链接
/**
* 根据HTML代码获取word文档内容
* 创建一个本质为mht的文档,该函数会分析文件内容并从远程下载页面中的图片资源
* 该函数依赖于类MhtFileMaker
* 该函数会分析img标签,提取src的属性值。但是,src的属性值必须被引号包围,否则不能提取
* param string $content HTML内容
* param string $absolutePath 网页的绝对路径。如果HTML内容里的图片路径为相对路径,那么就需要填写这个参数,来让该函数自动填补成绝对路径。这个参数最后需要以/结束
* param bool $isEraseLink 是否去掉HTML内容中的链接
*/
public static function getWordDocument( $content , $absolutePath = "" , $isEraseLink = false )
{
$mht = new MhtFileMaker();
if ($isEraseLink){
$content = preg_replace('/<a\s*.*?\s*>(\s*.*?\s*)<\/a>/i' , '$1' , $content); //去掉链接
}
$images = array();
$files = array();
$matches = array();
//这个算法要求src后的属性值必须使用引号括起来 || preg_match_all('/url\s*\(([^\)]+)\)/i',$content ,$matches )
if ( preg_match_all('/<img.*?src="(.*?)".*?>/is',$content ,$matches)){
$arrPath = $matches[1];
for ( $i=0;$i<count($arrPath);$i++){
$path = $arrPath[$i];
$imgPath = trim( $path );
if ( $imgPath != "" ){
$files[] = $imgPath;
if( substr($imgPath,0,7) == 'http://'){
//绝对链接,不加前缀
}else{
// $imgPath = $absolutePath.$imgPath;
$imgPath = public_path($imgPath);
}
$images[] = $imgPath;
}
}
}
$mht->AddContents("tmp.html",$mht->GetMimeType("tmp.html"),$content);
for ( $i=0;$i<count($images);$i++){
$image = $images[$i];
info($image);
if ( @fopen($image , 'r') ){
$imgcontent = @file_get_contents( $image );
if ( $content )
$mht->AddContents($files[$i],$mht->GetMimeType($image),$imgcontent);
}else{
return ;//echo "file:".$image." not exist!<br />";
}
}
return $mht->GetFile();
}
步骤3.类MhtFileMaker
<?php
namespace App\Services;
/**
*@author
*@version 1.0
*/
class MhtFileMaker{
var $config = array();
var $headers = array();
var $headers_exists = array();
var $files = array();
var $boundary;
var $dir_base;
var $page_first;
function MhtFile($config = array()){
}
function SetHeader($header){
$this->headers[] = $header;
$key = strtolower(substr($header, 0, strpos($header, ':')));
$this->headers_exists[$key] = TRUE;
}
function SetFrom($from){
$this->SetHeader("From: $from");
}
function SetSubject($subject){
$this->SetHeader("Subject: $subject");
}
function SetDate($date = NULL, $istimestamp = FALSE){
if ($date == NULL) {
$date = time();
}
if ($istimestamp == TRUE) {
$date = date('D, d M Y H:i:s O', $date);
}
$this->SetHeader("Date: $date");
}
function SetBoundary($boundary = NULL){
if ($boundary == NULL) {
$this->boundary = '--' . strtoupper(md5(mt_rand())) . '_MULTIPART_MIXED';
} else {
$this->boundary = $boundary;
}
}
function SetBaseDir($dir){
$this->dir_base = str_replace("\\", "/", realpath($dir));
}
function SetFirstPage($filename){
$this->page_first = str_replace("\\", "/", realpath("{$this->dir_base}/$filename"));
}
function AutoAddFiles(){
if (!isset($this->page_first)) {
exit ('Not set the first page.');
}
$filepath = str_replace($this->dir_base, '', $this->page_first);
$filepath = 'http://mhtfile' . $filepath;
$this->AddFile($this->page_first, $filepath, NULL);
$this->AddDir($this->dir_base);
}
function AddDir($dir){
$handle_dir = opendir($dir);
while ($filename = readdir($handle_dir)) {
if (($filename!='.') && ($filename!='..') && ("$dir/$filename"!=$this->page_first)) {
if (is_dir("$dir/$filename")) {
$this->AddDir("$dir/$filename");
} elseif (is_file("$dir/$filename")) {
$filepath = str_replace($this->dir_base, '', "$dir/$filename");
$filepath = 'http://mhtfile' . $filepath;
$this->AddFile("$dir/$filename", $filepath, NULL);
}
}
}
closedir($handle_dir);
}
function AddFile($filename, $filepath = NULL, $encoding = NULL){
if ($filepath == NULL) {
$filepath = $filename;
}
$mimetype = $this->GetMimeType($filename);
$filecont = file_get_contents($filename);
$this->AddContents($filepath, $mimetype, $filecont, $encoding);
}
function AddContents($filepath, $mimetype, $filecont, $encoding = NULL){
if ($encoding == NULL) {
$filecont = chunk_split(base64_encode($filecont), 76);
$encoding = 'base64';
}
info($filecont);
$this->files[] = array('filepath' => $filepath,
'mimetype' => $mimetype,
'filecont' => $filecont,
'encoding' => $encoding);
}
function CheckHeaders(){
if (!array_key_exists('date', $this->headers_exists)) {
$this->SetDate(NULL, TRUE);
}
if ($this->boundary == NULL) {
$this->SetBoundary();
}
}
function CheckFiles(){
if (count($this->files) == 0) {
return FALSE;
} else {
return TRUE;
}
}
function GetFile(){
$this->CheckHeaders();
if (!$this->CheckFiles()) {
exit ('No file was added.');
} //www.jb51.net
$contents = implode("\r\n", $this->headers);
$contents .= "\r\n";
$contents .= "MIME-Version: 1.0\r\n";
$contents .= "Content-Type: multipart/related;\r\n";
$contents .= "\tboundary=\"{$this->boundary}\";\r\n";
$contents .= "\ttype=\"" . $this->files[0]['mimetype'] . "\"\r\n";
$contents .= "X-MimeOLE: Produced By Mht File Maker v1.0 beta\r\n";
$contents .= "\r\n";
$contents .= "This is a multi-part message in MIME format.\r\n";
$contents .= "\r\n";
foreach ($this->files as $file) {
$contents .= "--{$this->boundary}\r\n";
$contents .= "Content-Type: $file[mimetype]\r\n";
$contents .= "Content-Transfer-Encoding: $file[encoding]\r\n";
$contents .= "Content-Location: $file[filepath]\r\n";
$contents .= "\r\n";
$contents .= $file['filecont'];
$contents .= "\r\n";
}
$contents .= "--{$this->boundary}--\r\n";
return $contents;
}
function MakeFile($filename){
$contents = $this->GetFile();
$fp = fopen($filename, 'w');
fwrite($fp, $contents);
fclose($fp);
}
function GetMimeType($filename){
$pathinfo = pathinfo($filename);
switch ($pathinfo['extension']) {
case 'htm': $mimetype = 'text/html'; break;
case 'html': $mimetype = 'text/html'; break;
case 'txt': $mimetype = 'text/plain'; break;
case 'cgi': $mimetype = 'text/plain'; break;
case 'php': $mimetype = 'text/plain'; break;
case 'css': $mimetype = 'text/css'; break;
case 'jpg': $mimetype = 'image/jpeg'; break;
case 'jpeg': $mimetype = 'image/jpeg'; break;
case 'jpe': $mimetype = 'image/jpeg'; break;
case 'gif': $mimetype = 'image/gif'; break;
case 'png': $mimetype = 'image/png'; break;
default: $mimetype = 'application/octet-stream'; break;
}
return $mimetype;
}
}
步骤4.将处理好的mht文件保存或者下载
我们有两种方法将文件发送给客户端:
一种是先在服务器端生成一个doc文档,然后将这个doc文档的地址记录下来,最后让客户端下载这个doc。
还有一种是直接发送html请求,修改HTML协议的header部分,直接将文件内容发送给客户端,也可以让客户端下载到这个doc文档。
例如:直接下载到客户端:
$filename = $oUser->truename?$oUser->truename."的简历":"简历";
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
header("Accept-Length: ".strlen($content));
header('Content-Type: application/octet-stream');
$filename=iconv("utf-8","gb2312",$filename);
header('Content-Disposition: attachment; filename='.$filename.'.doc');
header("Pragma:no-cache");
header("Expires:0");
echo $content;
结束
还有另外的方法,那就是使用PHPword扩展,下一篇再来记录