目录(?)[+]

  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>
  1. <?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. ?>

代码托管在: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>
  1. <?php
  2. require_once('WkHtmlToPdf.php');
  3.  
  4. $pdf = new WkHtmlToPdf;
  5.  
  6. // Add a HTML file, a HTML string or a page from a URL
  7. $pdf->addPage('/home/eoe/page.html');
  8. $pdf->addPage('<html>....</html>');
  9. $pdf->addPage('http://google.com');
  10.  
  11. // Add a cover (same sources as above are possible)
  12. $pdf->addCover('mycover.pdf');
  13.  
  14. // Add a Table of contents
  15. $pdf->addToc();
  16.  
  17. // Save the PDF
  18. $pdf->saveAs('/tmp/new.pdf');
  19.  
  20. // ... or send to client for inline display
  21. $pdf->send();
  22.  
  23. // ... or send to client as file download
  24. $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>
  1. <?php
  2. require('chinese-unicode.php');
  3.  
  4. $pdf=new PDF_Unicode();
  5.  
  6. $pdf->Open();
  7. $pdf->AddPage();
  8.  
  9. $pdf->AddUniCNShwFont('uni');
  10. $pdf->SetFont('uni','',20);
  11.  
  12. $pdf->Write(10, "eoe移动开发者社区");
  13. $pdf->Ln();
  14. $pdf->MultiCell (120, 10, "开发者社区");
  15. $pdf->Cell (240, 10, "本文是用utf8编码格式");
  16. $pdf->Ln();
  17.  
  18. $pdf->Output();
  19.  
  20. ?>

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

    Python与PHP通过XMLRPC进行通信:服务器端用Python,客户端用PHP. 服务器端:xmlrpc_server.py #!/usr/bin/python # coding: UTF-8 ...

  2. onreadystatechange()事件

    onreadystatechange(): 存储函数(或函数名),当 readyState 改变时,就会触发 onreadystatechange()  事件. xmlhttp.onreadystat ...

  3. Net操作Excel(终极方法NPOI)

    NPOI 待学习 http://www.cnblogs.com/stone_w/archive/2012/08/02/2620528.html

  4. maven 项目无法发布,无法编译的解决办法

    1 Web Deployment Assembly信息都合理2 重新clear项目,让JAVA代码重新生成.class文件在target目录中

  5. createjs easal.js制作了一个很简单的链路图

    <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...

  6. Mac下安装nginx

    试图折腾了一下手动安装,太多依赖,繁琐的要死.只好装了一个homebrew , 具体安装homebrew的教程网上查吧,就是一句话(ruby -e "$(curl -fsSL https:/ ...

  7. Java性能调优

    一.JVM内存模型及垃圾收集算法 1.根据Java虚拟机规范,JVM将内存划分为: New(年轻代) Tenured(年老代) 永久代(Perm) 其中New和Tenured属于堆内存,堆内存会从JV ...

  8. C#封装好的Win32API

    Kernel.cs using System; using System.Runtime.InteropServices; using System.Text; using HANDLE = Syst ...

  9. 从jQuery源码阅读看 dom load

    最近两天不忙的时候再回过来研究一下jquery的源码,看到$(document).ready()时,深入的研究了一下dom的加载问题. 我们都知道,window.onload可以解决我们的js执行时机 ...

  10. c#摄像头编程实例 (转)

    c#摄像头编程实例 摄像头编程 安装摄像头后,一般可以找到一个avicap32.dll文件 这是一个关于设想头的类 using  system;using  System.Runtime.Intero ...