目录(?)[+]

  1. 多种多样的pdf开发库
  2. WKHTMLTOPDF
    1. 2FPDF
    2. 3TCPDF
  3. 中文问题
 

做了这么多年项目,以前只是在别人的项目中了解过PHP生成pdf文件,知道并不难,但是涉及到了pdf开发库,首先介绍pdf库。

多种多样的pdf开发库

 

1.WKHTMLTOPDF

wkhtmltopdf是一个很好的解决方案,基本上可以原样输出html页面中的内容,包括:图片/代码高亮部分css/页头/页尾等。有php和命令行方式,大概思路如下: 1) 先获取所有的远程html,然后生成wkhtmltopdf的shell脚本 2) 在php中执行此shell脚本文件批量生成pdf(当然是采用定时任务) 3) 前端页面中检查当前页面是否存在此pdf,如果存在则显示下载链接
  1. <span style="font-family: Arial; font-size: 14px;"><?php
  2. $domain = "http://wiki.eoe.cn";
  3. $htmlUrl = $domain . "/show/html/slug/$slug";
  4. $_binpath = '/usr/local/bin/';
  5. $_binname = 'wkhtmltopdf';
  6. $savePath = "/User/Xia/eoecn/pdf/";
  7. if (!is_dir($savePath)) {
  8. //需要自己编写mkdirs函数
  9. @mkdirs($savePath);
  10. }
  11. //由于生成中文目录会乱码,这里过滤掉
  12. if (preg_match("/[x7f-xff]/", $slug)) {
  13. $filename = "wiki-slug-$id";
  14. }else {
  15. $filename = $slug;
  16. }
  17. $saveFile = $savePath . $filename . '.pdf';
  18. //判断是否已经存在
  19. if (file_exists($saveFile)) {
  20. die($saveFile);
  21. }
  22. $header = $domain . "/pdf/header";
  23. $command = $_binpath . $_binname
  24. . ' -T 15mm --header-spacing 5 --header-html ' . $header
  25. . ' --footer-right "[page]/[toPage]"  ' . $htmlUrl . ' '
  26. . $saveFile;
  27. if ($exec) {
  28. exec($command, $output, $var);
  29. }
  30. ?></span>
<?php
$domain = "http://wiki.eoe.cn";
$htmlUrl = $domain . "/show/html/slug/$slug";
$_binpath = '/usr/local/bin/';
$_binname = 'wkhtmltopdf';
$savePath = "/User/Xia/eoecn/pdf/";
if (!is_dir($savePath)) {
//需要自己编写mkdirs函数
@mkdirs($savePath);
}
//由于生成中文目录会乱码,这里过滤掉
if (preg_match("/[x7f-xff]/", $slug)) {
$filename = "wiki-slug-$id";
}else {
$filename = $slug;
}
$saveFile = $savePath . $filename . '.pdf';
//判断是否已经存在
if (file_exists($saveFile)) {
die($saveFile);
}
$header = $domain . "/pdf/header";
$command = $_binpath . $_binname
. ' -T 15mm --header-spacing 5 --header-html ' . $header
. ' --footer-right "[page]/[toPage]" ' . $htmlUrl . ' '
. $saveFile;
if ($exec) {
exec($command, $output, $var);
}
?>

代码托管在:https://code.google.com/p/wkhtmltopdf/

Linux和mac os等其它平台安装文档:http://www.tecmint.com/install-wkhtmltopdf-html-page-to-pdf-converter-in-rhel-centos-fedora/

要想完好支持html中的url和其它,参考:http://www.cnblogs.com/timelyxyz/archive/2012/12/24/2831523.html

说明文档: http://madalgo.au.dk/~jakobt/wkhtmltoxdoc/wkhtmltopdf-0.9.9-doc.html

wkhtmltopdf安装包

php使用方法: http://mikehaertl.github.com/phpwkhtmltopdf/

例子:

  1. <span style="font-family: Arial;"><?php
  2. require_once('WkHtmlToPdf.php');
  3. $pdf = new WkHtmlToPdf;
  4. // Add a HTML file, a HTML string or a page from a URL
  5. $pdf->addPage('/home/eoe/page.html');
  6. $pdf->addPage('<html>....</html>');
  7. $pdf->addPage('http://google.com');
  8. // Add a cover (same sources as above are possible)
  9. $pdf->addCover('mycover.pdf');
  10. // Add a Table of contents
  11. $pdf->addToc();
  12. // Save the PDF
  13. $pdf->saveAs('/tmp/new.pdf');
  14. // ... or send to client for inline display
  15. $pdf->send();
  16. // ... or send to client as file download
  17. $pdf->send('test.pdf');</span>
<?php
require_once('WkHtmlToPdf.php'); $pdf = new WkHtmlToPdf; // Add a HTML file, a HTML string or a page from a URL
$pdf->addPage('/home/eoe/page.html');
$pdf->addPage('<html>....</html>');
$pdf->addPage('http://google.com'); // Add a cover (same sources as above are possible)
$pdf->addCover('mycover.pdf'); // Add a Table of contents
$pdf->addToc(); // Save the PDF
$pdf->saveAs('/tmp/new.pdf'); // ... or send to client for inline display
$pdf->send(); // ... or send to client as file download
$pdf->send('test.pdf');

2.FPDF

FPDF是一个纯粹的通过PHP类来生成PDF文档的方法,需要生成的内容直接在PHP代码中来指定,生成文字,图片,线条等等,都有自己的方法。不足的是utf8和中文支持很差,分别需要调用chinese-unicode.php和chinese.php等扩展文件,附上一个简单的例子:

  1. <span style="font-family: Arial;"><?php
  2. require('chinese-unicode.php');
  3. $pdf=new PDF_Unicode();
  4. $pdf->Open();
  5. $pdf->AddPage();
  6. $pdf->AddUniCNShwFont('uni');
  7. $pdf->SetFont('uni','',20);
  8. $pdf->Write(10, "eoe移动开发者社区");
  9. $pdf->Ln();
  10. $pdf->MultiCell (120, 10, "开发者社区");
  11. $pdf->Cell (240, 10, "本文是用utf8编码格式");
  12. $pdf->Ln();
  13. $pdf->Output();
  14. ?></span>
<?php
require('chinese-unicode.php'); $pdf=new PDF_Unicode(); $pdf->Open();
$pdf->AddPage(); $pdf->AddUniCNShwFont('uni');
$pdf->SetFont('uni','',20); $pdf->Write(10, "eoe移动开发者社区");
$pdf->Ln();
$pdf->MultiCell (120, 10, "开发者社区");
$pdf->Cell (240, 10, "本文是用utf8编码格式");
$pdf->Ln(); $pdf->Output(); ?>

3.TCPDF

TCPDF是一个用于快速生成PDF文件的PHP5函数包。TCPDF基于FPDF进行扩展和改进。支持UTF-8,Unicode,HTML和 XHTML。但是文件很多很大,配置起来比较复杂。相对而言对复杂的css渲染效果不好,而且不能支持html中太多的css文件,用php转换效率很慢。
不过官方的文档很多,例子也很多,也能够生成很漂亮的pdf文件。官方网址为:http://www.tcpdf.org/

本人使用的就是这个工具包,所以着重给大家介绍一下,个人认为TCPDF还是很好用的,足以满足大多数pdf应用,官方提供了丰富的文档以及例子,各种特性都提供了详细的例子,上手极快。

以下为TCPDF目录结构:


本人使用的是CI框架,在将这个库集成进来的时候,对这个包做了一些改动。

1.所有的基础配置信息都在tcpdf根目录“examples/include/tcpdf_config_alt.php”中,我们为了简化配置,也使用了它原生的配置文件,以简化在开发过程中的配置,将该文件的内容拷贝至CI框架application/conf/pdf_config.php中,找到“K_PATH_IMAGES”配置项,将其值修改为你项目中图片所在的位置,到时候在省城pdf时,所用到的图片资源,将从这里查找。

“PDF_HEADER_LOGO”用于配置pdf中header中logo图片,如需要的话设置成你自己的

还有其他一些常用的配置,如配置Top margin、Bottom margin、Left margin、Default main font name

中文问题

使用tcpdf时中文问题是比较常见,在新版的tcpdf中,已经支持中文了,在fonts目录下有个cid0cs.php和stsonstdlight.php文件,只要直接使用即可

  1. <span style="font-family: Arial;">$pdf->SetFont('cid0cs', '', 10);</span>
$pdf->SetFont('cid0cs', '', 10);
  1. <span style="font-family: Arial;">$pdf->SetFont('stsongstdlight','', 10);</span>
$pdf->SetFont('stsongstdlight','', 10);

但是经过本人的实践,使用这两种字体,的确是支持中文,但是英文的显示并不是太好,这种方式生成的PDF文件的优点是:文件体积小,生成快速。但也有缺点是,没有嵌入中文字体,只限于安装了Adobe Reader之后才能正常显示。那万一用户使用的是FoxIt Reader或者是Linux操作系统呢?显示效果就不一样了。因此,为了保证生成的PDF文件在任何环境下都有同样的显示效果,嵌入字体是必需的。 Windows下有很多中文字体,但是我们要用在TCPDF中的中文字体有下面几个要求: · 支持Unicode,因为TCPDF支持的是Unicode; · 体积越小越好; · 最好是也支持繁体中文; 将下载后的DroidSansFallback.ttf字体文件复制到tcpdf目录下的fonts目录,并保证web服务器对该目录有读写的权限,否则在生成tcpdf字体是会出错。DroidSansFallback.ttf下载地址

在你的代码中添加如下代码:

  1. <span style="font-family: Arial; font-size: 14px;">$fontname = $this->tcpdf->addTTFfont('dist/font/Droid_Sans_Fallback.ttf', 'TrueTypeUnicode', '', 32);</span>
$fontname = $this->tcpdf->addTTFfont('dist/font/Droid_Sans_Fallback.ttf', 'TrueTypeUnicode', '', 32);
  1. <span style="font-family: Arial; font-size: 14px;">$this->tcpdf->SetFont($fontname, '', 10);  </span>
$this->tcpdf->SetFont($fontname, '', 10);  

这句代码将你下载的ttf字体自动转化为tcpdf使用的字体,将在font目录下增加这几个文件“droid_sans_fallback.ctg.z,droid_sans_fallback.php,droid_sans_fallback.z”,生成之后,以后就可以直接使用这种字体了。

以下为完整的代码:

  1. <span style="font-family: Arial; font-size: 14px;">//加载配置文件以及pdf类
  2. require_once(APPPATH . 'config/pdf_config.php');
  3. $this->load->library('tcpdf/tcpdf');
  4. // set document information
  5. $this->tcpdf->SetCreator(PDF_CREATOR);
  6. $this->tcpdf->SetAuthor('aaron');
  7. $this->tcpdf->SetTitle($cur_order['title']);
  8. $this->tcpdf->SetSubject('lvpad');
  9. $this->tcpdf->SetKeywords('lvpad, china tour, guide');
  10. // set default header data
  11. $this->tcpdf->SetHeaderData('logo.png', PDF_HEADER_LOGO_WIDTH, 'lvpad order', '');
  12. // set header and footer fonts
  13. $this->tcpdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
  14. $this->tcpdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
  15. // set default monospaced font
  16. $this->tcpdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
  17. // set margins
  18. $this->tcpdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
  19. $this->tcpdf->SetHeaderMargin(PDF_MARGIN_HEADER);
  20. $this->tcpdf->SetFooterMargin(PDF_MARGIN_FOOTER);
  21. // set auto page breaks
  22. $this->tcpdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
  23. // set image scale factor
  24. $this->tcpdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  25. //set some language-dependent strings (optional)
  26. $l['a_meta_charset'] = 'UTF-8';
  27. $l['a_meta_dir'] = 'ltr';
  28. $l['a_meta_language'] = 'cn';
  29. // TRANSLATIONS --------------------------------------
  30. $l['w_page'] = 'page';
  31. $this->tcpdf->setLanguageArray($l);
  32. // 设置字体,如果要支持中文 则选择支持中文的字体
  33. $fontname = $this->tcpdf->addTTFfont('dist/font/Droid_Sans_Fallback.ttf', 'TrueTypeUnicode', '', 32);
  34. $this->tcpdf->SetFont($fontname, '', 10);
  35. // add a page
  36. $this->tcpdf->AddPage();
  37. $this->tcpdf->setJPEGQuality(75);
  38. // Image example with resizing
  39. $this->tcpdf->Image('images/pdf.jpg', 10, 20, 190, 60, 'JPG', 'http://lvpad.com', '', false, 150, '', false, false, 1, false, false, false);
  40. // output the HTML content
  41. $this->tcpdf->writeHTML($html_content, true, false, true, false, '');
  42. // reset pointer to the last page
  43. $this->tcpdf->lastPage();
  44. //Close and output PDF document
  45. $this->tcpdf->Output($cur_order['title'] . '.pdf', 'I');  </span>
//加载配置文件以及pdf类
require_once(APPPATH . 'config/pdf_config.php');
$this->load->library('tcpdf/tcpdf'); // set document information
$this->tcpdf->SetCreator(PDF_CREATOR);
$this->tcpdf->SetAuthor('aaron');
$this->tcpdf->SetTitle($cur_order['title']);
$this->tcpdf->SetSubject('lvpad');
$this->tcpdf->SetKeywords('lvpad, china tour, guide'); // set default header data
$this->tcpdf->SetHeaderData('logo.png', PDF_HEADER_LOGO_WIDTH, 'lvpad order', ''); // set header and footer fonts
$this->tcpdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$this->tcpdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA)); // set default monospaced font
$this->tcpdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$this->tcpdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$this->tcpdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$this->tcpdf->SetFooterMargin(PDF_MARGIN_FOOTER); // set auto page breaks
$this->tcpdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); // set image scale factor
$this->tcpdf->setImageScale(PDF_IMAGE_SCALE_RATIO); //set some language-dependent strings (optional)
$l['a_meta_charset'] = 'UTF-8';
$l['a_meta_dir'] = 'ltr';
$l['a_meta_language'] = 'cn'; // TRANSLATIONS --------------------------------------
$l['w_page'] = 'page'; $this->tcpdf->setLanguageArray($l);
// 设置字体,如果要支持中文 则选择支持中文的字体
$fontname = $this->tcpdf->addTTFfont('dist/font/Droid_Sans_Fallback.ttf', 'TrueTypeUnicode', '', 32); $this->tcpdf->SetFont($fontname, '', 10);
// add a page
$this->tcpdf->AddPage();
$this->tcpdf->setJPEGQuality(75);
// Image example with resizing
$this->tcpdf->Image('images/pdf.jpg', 10, 20, 190, 60, 'JPG', 'http://lvpad.com', '', false, 150, '', false, false, 1, false, false, false); // output the HTML content
$this->tcpdf->writeHTML($html_content, true, false, true, false, '');
// reset pointer to the last page
$this->tcpdf->lastPage();
//Close and output PDF document
$this->tcpdf->Output($cur_order['title'] . '.pdf', 'I');

生成的pdf就是这样的:

以上中文问题已经解决,当然,你还可以寻找其他的字体,然后进行尝试。

使用TCPDF插件生成pdf以及pdf的中文处理的更多相关文章

  1. php 基于tcpdf插件生成pdf

    之前在公司做了个项目,,需要导出pdf合同,,在网上找了很久,选择用了tcpdf插件,,具体的插件网上可以搜到,中间遇到了很多的坑,慢慢的填. 先下好插件放到指定文件夹下 然后使用tcpdf插件里ht ...

  2. php生成pdf,php+tcpdf生成pdf, php pdf插件

    插件例子:https://tcpdf.org/examples/ 下载tcpdf插件: demo // Include the main TCPDF library (search for insta ...

  3. C#使用iTextSharp+ZXing.Net+FreeSpire.PDF生成和打印pdf文档

    项目需求(Winform)可以批量打印某个模板,经过百度和摸索,使用iTextSharp+ZXing.Net+FreeSpire.PDF三个类库实现了生成pdf.生成条形码和打印pdf功能. 首先在项 ...

  4. jquery插件导出excel和pdf(解决中文乱码问题)

    参考文件:http://jackyrong.iteye.com/blog/2169683 https://my.oschina.net/aruan/blog/418980 https://segmen ...

  5. 利用PDF.JS插件解决了本地pdf文件在线浏览问题(根据需要隐藏下载功能,只保留打印功能)

    我是在IE11和谷歌上做的测试,都可以显示,把做出的东西记录下来,方便大家还有自己学习! 可以在IIS7服务器上也可以下载Tomcat来做服务器 Tomcat下载地址   http://pan.bai ...

  6. Qt 生成word、pdf文档

    需求:将软件处理的结果保存为一个报告文档,文档中包含表格.图片.文字,格式为word的.doc和.pdf.生成word是为了便于用户编辑. 开发环境:qt4.8.4+vs2010 在qt的官网上对于p ...

  7. 将div的内容生成清晰的PDF、高清PDF

    //需要引入html2canvas.js.jquery.js文件 html: <button type="button" class="btn btn-primar ...

  8. 使用pdfjs插件在线预览PDF文件

    前言 本文介绍在html中使用 pdfjs插件在线预览PDF文件的方法. 实现步骤 下载 pdfjs 并引入项目中 到PDFJS官网 http://mozilla.github.io/pdf.js/g ...

  9. HTML生成横向的PDF

    HTML生成PDF请参照:https://www.cnblogs.com/yunfeiyang-88/p/10984740.html 如要生成横向的PDF:在html模板的style标签里面加入@pa ...

随机推荐

  1. 搭建sonar,推动代码质量管理

    最近比较关注devops相关的文章,尝试搭建sonarqube服务,进行代码质量的分析和管理,先记录下本地环境的搭建和分析过程. 一.sonarqube服务搭建 官网地址:http://www.son ...

  2. dubbo服务自动化测试搭建

    java实现dubbo的消费者服务编写:ruby实现消费者服务的接口测试:通过消费者间接测试dubbo服务接口的逻辑 内容包括:dubbo服务本地调用环境搭建,dubbo服务启动,消费者部署,脚本编写 ...

  3. System.Web.Mvc.dll在各个版本MVC中的文件位置

    the default folder would be like the following: MVC 5 C:\Program Files (x86)\Microsoft ASP.NET\ASP.N ...

  4. canvas ---个性时钟

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name ...

  5. rsync命令详解

    介绍 rsync命令是一个远程数据同步工具,可通过LAN/WAN快速同步多台主机间的文件.rsync使用所谓的“rsync算法”来使本地和远程两个主机之间的文件达到同步,这个算法只传送两个文件的不同部 ...

  6. C# 抽象类abstract

    不能初始化的类被叫做抽象类,它们只提供部分实现,但是另一个类可以继承它并且能创建它们的实例,有未被实现的方法.抽象类不可以new对象. "一个包含一个或多个纯虚函数的类叫抽象类,抽象类不能被 ...

  7. oracle and 和 or

    源地址:https://zhidao.baidu.com/question/350891282.html (FirstName='Thomas' OR FirstName='William') AND ...

  8. Java生成与解析二维码

    1.下载支持二维码的jar包qrcode.jar和qrcode_swetake.jar, 其中qrcode_swetake.jar用于生成二维码,rcode.jar用于解析二维码,jar包下载地址(免 ...

  9. (Array)121. Best Time to Buy and Sell Stock

    Say you have an array for which the ith element is the price of a given stock on day i. If you were ...

  10. java中的运算符

    1.      赋值运算符:  (=) 2.      算术运算符:  (+ ,- , * , /, %) 3.      逻辑运算符:  (&& ,||, !) 4.      关系 ...