以下是实现的代码:
<html>
<!-- <div id="myhtml">
<p> 这里写了好多html内容~</p>
</div> -->
<a href="javascript:;" id="submit_pdf" >生成pdf</a>
<a href="" id="download_pdf" >打开pdf</a>
<script type="text/javascript">
// var myhtml=$("#submit_pdf").html();
$("#submit_pdf").click(function(){
$.ajax({
type:"post",
data:{"id":id,"name":name},
url:"__URL__/get_pdf.html",
success:function(path){
$("#download_pdf").attr('href',"__PUBLIC__"+path);
},
async: true
})
})
</script>
</html>
<?php
public function get_pdf(){
$strContent ='打印的id:'.$_POST['id'].' name:'.$_POST['name'];
//引入类库
Vendor('mpdf60.mpdf');
//设置中文编码
$mpdf=new \mPDF('zh-cn','A4', 0, '微软雅黑', 0, 0);
$mpdf->SetWatermarkText('hello uzi',0.1);
$mpdf->showWatermarkText = true;
$mpdf->SetHTMLHeader( '头部' );
$mpdf->SetHTMLFooter( '底部' );
$stylesheet =file_get_contents("./Public/home/css/pdf_style.css");
$mpdf->WriteHTML($stylesheet, 1);
$mpdf->WriteHTML($strContent);
//保存ss.pdf文件
// $mpdf->Output('ss.pdf','I');
// //直接浏览器输出pdf
// $mpdf->Output('tmp.pdf',true);
// $mpdf->Output();
$filename="tmp".time().".pdf";
$path="upload/files/".$filename;
$mpdf->Output("./Public/files/".$filename,'f');
echo $path;
}
?>
说明:主要是生成的时候把变量传过去,在get_pdf()里组装打印的内容(strcontent)和样式(stylesheet),生成pdf文件在服务器目录“./Public/files/”下。
其实最便捷的是直接用<div></div>把整个要打印的页面传输到php代码里,应用相关的样式然后直接打印就可以相当于打印当前的页面了。
其他:
- 使用Mpdf先要下载,链接是http://www.mpdf1.com/mpdf/index.php;然后放到Vendor下,我用的是thinkphp框架。
- 其他mpdf的函数参考手册可在这里找到:http://mpdf.github.io/
- $mpdf->Output("./Public/files/".$filename,'f')。除了生成pdf文件,获得文件路径这种方式,还有其他‘I’‘d’‘s’方式。具体看手册里的ouput函数。
 
|