friendsofcake/cakepdf 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

friendsofcake/cakepdf

Composer 安装命令:

composer require friendsofcake/cakepdf

包简介

CakePHP plugin for creating and/or rendering Pdfs, several Pdf engines supported.

README 文档

README

Build Status Total Downloads License

Plugin containing CakePdf lib which will use a PDF engine to convert HTML to PDF.

Engines included in the plugin:

  • DomPdf (^3.0)
  • Mpdf (^8.0.4)
  • TcLibPdf (^8) - successor of the deprecated Tcpdf engine
  • Tcpdf (^6.3) - deprecated, the underlying tecnickcom/tcpdf package is deprecated upstream; use TcLibPdf instead
  • WeasyPrint (Recommended if you have the privileges to install something on your server)
  • WkHtmlToPdf (project no longer maintained but binaries still available for various environments)

Community maintained engines:

Requirements

Installation

Using Composer:

composer require friendsofcake/cakepdf

CakePdf does not include any of the supported PDF engines, you need to install the ones you intend to use yourself.

Check WeasyPrint's installation guide to install it on your system. DomPdf, Mpdf, TcLibPdf and Tcpdf can be installed via composer using one of the following commands:

composer require dompdf/dompdf
composer require tecnickcom/tc-lib-pdf
composer require tecnickcom/tcpdf
composer require mpdf/mpdf

TcLibPdf font setup

Unlike the deprecated Tcpdf engine, tecnickcom/tc-lib-pdf does not bundle any fonts. It loads fonts from generated *.json font files located in a directory referenced by the K_PATH_FONTS constant. Define it once during your application bootstrap, before any PDF is rendered:

define('K_PATH_FONTS', '/absolute/path/to/your/fonts');

The directory must contain at least the core fonts you reference (e.g. helvetica.json). See the tc-lib-pdf-font documentation for how to generate font files.

Setup

Loading the plugin using CakePHP's console:

./bin/cake plugin load CakePdf

If you plan to use the PDF view functionality that automatically renders and returns the PDF for sending it to the browser, you should also register the pdf extension in your config/routes.php file:

$routes->scope('/', function (\Cake\Routing\RouteBuilder $routes) {
    $routes->setExtensions(['pdf']);
    // ...
});

Further setup information can be found in the usage section.

Configuration

Use Configure::write('CakePdf', $config); or in controller use view builder to set view option named pdfConfig (only when used with PdfView). You need to define at least $config['engine']. When using CakePdf directly you can also pass the config array to constructor. The value for engine should have the Plugin.ClassName format without the Engine suffix.

Configuration options:

  • engine: Engine to be used (required), or an array of engine config options
    • className: Engine class to use
    • binary: Binary file to use (Only for weasyprint/wkhtmltopdf)
    • cwd: current working directory (Only for weasyprint/wkhtmltopdf)
    • options: Engine specific options. Currently used for following engine:
      • WkHtmlToPdfEngine: The options are passed as CLI arguments
      • WeasyPrintEngine: The options are passed as CLI arguments
      • TexToPdfEngine: The options are passed as CLI arguments
      • DomPdfEngine: The options are passed to constructor of Dompdf class
      • MpdfEngine: The options are passed to constructor of Mpdf class
      • TcLibPdfEngine: Supports unit, unicode, subsetFont, compress, mode, font (['family', 'style', 'size']), margins (['left', 'top', 'right', 'bottom']) and metadata (['author', 'creator', 'subject', 'keywords'])
  • crypto: Crypto engine to be used, or an array of crypto config options
    • className: Crypto class to use
    • binary: Binary file to use
  • pageSize: Change the default size, defaults to A4 (Needs to be set via CSS for WeasyPrint)
  • orientation: Change the default orientation, defaults to portrait (Needs to be set via CSS for WeasyPrint)
  • margin: Array or margins with the keys: bottom, left, right, top and their values (Needs to be set via CSS for WeasyPrint)
  • title: Title of the document (Needs to be set via CSS for WeasyPrint)
  • delay: A delay in milliseconds to wait before rendering the pdf (wkhtmltopdf only)
  • windowStatus: The required window status before rendering the pdf (wkhtmltopdf only)
  • encoding: Change the encoding, defaults to UTF-8
  • download: Set to true to force a download, only when using PdfView
  • filename: Filename for the document when using forced download

Example:

Configure::write('CakePdf', [
    'engine' => 'CakePdf.WeasyPrint',
    'download' => true,
]);
use CakePdf\View\PdfView;

class InvoicesController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();

        // https://book.cakephp.org/5.x/controllers.html#content-type-negotiation
        $this->addViewClasses([PdfView::class]);
    }

    // In your Invoices controller you could set additional configs,
    // or override the global ones:
    public function view($id = null): void
    {
        $invoice = $this->Invoice->get($id);
        $this->viewBuilder()->setOption(
            'pdfConfig',
            [
                'orientation' => 'portrait',
                'filename' => 'Invoice_' . $id,
            ]
        );
        $this->set('invoice', $invoice);
    }
}

The engine and crypto config options can also be arrays with configuration options for the relevant class. For example:

Configure::write('CakePdf', [
    'engine' => [
        'className' => 'CakePdf.WeasyPrint',
        // Options usable depend on the engine used.
        'options' => [
            'dpi' => 96,
        ],

        /**
         * For Mac OS X / Linux by default the `weasyprint` binary should
         * be available through environment path or you can specify location as:
         */
        // 'binary' => '/usr/local/bin/weasyprint',

        /**
         * On Windows the engine uses the path shown below as default.
         * You NEED to use the path like old fashioned MS-DOS Paths,
         * otherwise you will get error like:
         * "weasyprint didn't return any data"
         */
        // 'binary' => 'C:/Progra~1/WeasyPrint/bin/weasyprint.exe',
    ],
]);

Usage

You can use CakePdf in two ways, read carefully which one you actually need. Many people mix both ways and don't get the expected results.

1: Render as PDF (including forced download) in the browser with PdfView

You can create PDF template and layout files for your controller actions and have them automatically rendered. Place the templates in a pdf subdir, for instance templates/Invoices/pdf/view.php, layouts will be in templates/layout/pdf/default.php.

Then for e.g. accessing the URL http://localhost/invoices/view/1.pdf would give you the generated PDF.

Additionally you can map resources by adding Router::mapResources(['Invoices']); to your routes file and you can access the same document at http://localhost/invoices/1.pdf.

In case you don't want to use the pdf extension in your URLs, you can omit registering it in your routes configuration. You can then set the Accept request header to application/pdf to make CakePHP automatically switch to PdfView (required the viewClasses() method to be set as shown above), or explicity switch the view class in your controller action:

$this->viewBuilder()->setClassName('CakePdf.Pdf');

Instead of having the pdf rendered in the browser itself, you can force it to be downloaded by using download option. Additionally you can specify custom filename using filename options.

$this->viewBuilder()->setOption(
    'pdfConfig',
    [
        'download' => true, // This can be omitted if "filename" is specified.
        'filename' => 'Invoice_' . $id, // This can be omitted if you want a file name based on URL.
    ]
);

2: Create PDF for email attachment, file storage etc.

You can use CakePdf to create raw PDF data with a view template. The view file path would look like templates/pdf/newsletter.php. Layout file path would be like templates/layout/pdf/default.php Note that layouts for both usage types are within same directory, but the view templates use different file paths Optionally you can also write the raw data to file.

Example:

$CakePdf = new \CakePdf\Pdf\CakePdf();
$CakePdf->template('newsletter', 'default');
$CakePdf->viewVars(['key' => 'value']);
// Get the PDF string returned
$pdf = $CakePdf->output();
// Or write it to file directly
$pdf = $CakePdf->write(APP . 'files' . DS . 'newsletter.pdf');

Encryption

You can optionally encrypt the PDF with permissions

To use encryption you first need to select a crypto engine. Currently we support the following crypto engines:

  • Pdftk

Usage

Add the following in your bootstrap.

Configure::write('CakePdf.crypto', 'CakePdf.Pdftk');

Options in pdfConfig:

  • protect: Set to true to enable encryption
  • userPassword (optional): Set a password to open the PDF file
  • ownerPassword (optional): Set the password to unlock the locked permissions
  • one of the above must be present, either userPassword or ownerPassword
  • permissions (optional): Define the permissions

Permissions:

By default, we deny all permissions.

To allow all permissions:

Set 'permission' to true

To allow specific permissions:

Set 'permissions' to an array with a combination of the following available permissions:

  • print
  • degraded_print
  • modify,
  • assembly,
  • copy_contents,
  • screen_readers,
  • annotate,
  • fill_in

How to

Ensure css, images etc. are loaded in PDF

Use absolute URLs for static assets in your view templates for PDFs. If you use HtmlHelper::image(), or HtmlHelper::css() make sure you have set fullBase option to true.

For example

echo $this->Html->image('logo.png', ['fullBase' => true]);
echo $this->Html->css('bootstrap.css', ['fullBase' => true]);

If you are enable to get URLs for assets working properly, you can try using file system paths instead for the assets.

<img src="<?= WWW_ROOT ?>img/logo.png" />

Note: Since v0.12.16 wkhtmltopdf requires the option enable-local-file-access to be able to use local filesytem paths for assets. You can enable it by setting 'enable-local-file-access' => true in the engine config array.

Get header and footer on all pages

Here are a couple of CSS based solutions you can refer to for easily getting header footer on all PDF pages.

friendsofcake/cakepdf 适用场景与选型建议

friendsofcake/cakepdf 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 2.25M 次下载、GitHub Stars 达 375, 最近一次更新时间为 2014 年 09 月 19 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 friendsofcake/cakepdf 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 friendsofcake/cakepdf 我们能提供哪些服务?
定制开发 / 二次开发

基于 friendsofcake/cakepdf 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 2.25M
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 382
  • 点击次数: 24
  • 依赖项目数: 8
  • 推荐数: 0

GitHub 信息

  • Stars: 375
  • Watchers: 36
  • Forks: 178
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2014-09-19