quazardous/pdf-labels

另一个PDF标签类

dev-master / 1.0.x-dev 2016-06-23 20:32 UTC

This package is auto-updated.

Last update: 2024-09-20 10:54:37 UTC


README

另一个PDF标签类

它受到了https://github.com/madvik/kiwi-label的轻微启发。

安装

composer require quazardous/pdf-labels

概念

PDF Labels被设计成易于扩展。

接口

我已经将PDF Labels拆分成许多简单的组件/接口。你可以通过实现所需的接口来编写自己的组件。

引擎

这是顶层/外壳类

  • 进行一些验证
  • 交叉确认布局和编写器
  • 从数据提供组件获取数据
  • 根据布局组件计算放置位置
  • 通过编写器组件触发渲染

布局

接口: LabelLayoutInterface

实现布局的类负责计算标签布局/网格,考虑页面尺寸、标签尺寸、边距等。

数据提供者

接口: LabelDataProviderInterface

负责获取标签数据。

编写器

接口: LabelWriterInterface

负责将标签渲染到PDF或其他格式。

当前实现

当前实现提供

  • 一个简单的引擎
  • 2个数据提供者(数组或回调)
  • 一个'智能'布局,尝试猜测缺失的内容
  • 一个TCPDF编写器

每个组件可以有不同的内部长度单位(毫米、点、英寸)。

使用方法

这里有一个注释示例。

// A fluid label layout trying to auto fit 50mm x 30mm labels
// See SimpleFluidLabelLayout for more options.
// You can create your own layout with LabelLayoutInterface.
$options = [
    // the bare minimum is label dimensions
    'label_width' => 50,
    'label_height' => 30,
];
$layout = new SimpleFluidLabelLayout($options);

// Some simple labels data. Each row is passed to the render label callback.
// You can create your own data providers with LabelDataProviderInterface.
// see CallbackLabelDataProvider: a callback based data provider usefull to save memory (DB to PDF).
$labels = [
    ['Foo', 'Bar'],
    ['One', 'Two'],
    ['Isaac', 'Asimov'],
    ['Black', 'White'],
...
];

// The main class.
$engine = new LabelEngine($layout, $labels);

// create a TCPDF label writer.
$pdf = new TcPdfLabelWriter();
// add standard TCPDF attributes
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetAuthor('quazardous');

// set the render label callback
// the engine calculate the correct $x and $y
$pdf->setRenderLabelCallback(function ($x, $y, $data) use ($pdf) {
    $aff_border = 0;
    $pdf->SetFont("helvetica");
    $pdf->setX($x);
    $pdf->setY($y, false);
    $pdf->Cell(0 , 0, $data[0], $aff_border, 1, 'L', 0);
    $pdf->setX($x);
    $pdf->setY($y + 6, false);
    $pdf->Cell(0 , 0, $data[1], $aff_border, 1, 'L', 0);
});

// register the label writer with the engine
$engine->setWriter($pdf);

// main loop:
// fetch data row/label and for each we trigger the render label callback.
$engine->populate();

// standard TCPDF generation
$pdf->Output(__DIR__ . "/gen/example1.pdf", "F");

测试

将文件tests/config-dist.php复制并修改为tests/config.php,然后运行

composer install
phpunit

tests/gen中生成一个示例PDF文件。