首页 > 解决方案 > 将 TCPDF 文档设置为 INFINITE 高度以模拟打印到标签卷纸

问题描述

是否可以在 TCPDF 中设置页面以将其高度设置为 INFINITE?我需要它来模拟打印到带有标签的滚筒打印机,宽度固定为 62 毫米,但高度可以是无限的,直到有数据要打印......所以......不需要分页。

$pdf = new TCPDF('L', 'mm', array('62',$infiniteH), true, 'UTF-8', false);

我不知道是否可以将 $infiniteH 设置为一个值来模拟我的需求

更新:或者可能是一种计算所需高度并更新 TCPDF 选项的方法?

标签: tcpdf

解决方案


您可以使用计算所需高度并使用它的想法来模拟它。

  1. 开始交易。
  2. 添加一个非常高的页面。
  3. 运行渲染并计算必要的高度。
  4. 回滚您的事务。
  5. 添加适当大小的页面。
  6. 重新运行渲染。

我有一些下面这个想法的示例代码。我关闭了自动分页以防止意外分页,但这确实将底部边距设置为 0,因此我在函数中包含了一个额外的底部边距参数。

<?php
function add_roll_segment($pdf, $maxHeight, $render_callback, $extra_bottom_margin = 1) {
  $pdf->startTransaction();
  $pdf->addPage('P', [$pdf->getPageWidth(), $maxHeight]);
  $render_callback($pdf);
  $margins = $pdf->getMargins();
  $newheight = $pdf->GetY()  + $margins['bottom'] + $extra_bottom_margin;
  $pdf->rollbackTransaction(true);
  $pdf->addPage('P', [$pdf->getPageWidth(), $newheight]);
  $render_callback($pdf);
}


class TransactionRenderer {
  protected $details;

  public function __construct() {
    $this->details = [];
  }

  public function add_transaction_detail($item, $price) {
    $this->details[] = ['item' => $item, 'price' => intval($price)];
  }

  public function render($pdf) {
    $margins = $pdf->getMargins();
    $pdf->setFont('courier', 'B', 8);
    $pdf->SetLineStyle([
      'width' => 0.1,
      'dashed' => [0.5,0.2],
      'color' => [0,0,0,100],
    ]);
    $pdf->Cell(0,0,'Begin Transactions for '.date('Y-m-d H:i:s'),0,1);
    $pdf->SetY($pdf->GetY() + 0.6);
    $pdf->Line($margins['left'], $pdf->getY(), $pdf->getPageWidth() - $margins['right'], $pdf->getY());
    $pdf->SetY($pdf->GetY() + 0.6);
    foreach($this->details as $line) {
      $y = $pdf->getY();
      $pdf->Cell(0,0,$line['item'],0,1,'L');
      $pdf->setY($y);
      $pdf->Cell(0,0,sprintf('%d JPY', $line['price']),0,1,'R');
    }
  }
}

//Populate random data.
$pdf = new TCPDF('L', 'mm', array('62',100), true, 'UTF-8', false);
$renderer = new TransactionRenderer();
$words1 = ['Big', 'Fancy', 'Pretty', 'Cool', 'Awesome'];
$words2 = ['Pants', 'Panda Pot', 'Cup', 'Mug', 'Pie', 'Plate'];
$pdf->SetAutoPageBreak(false);
$count = rand(200, 400);
for($i = 0; $i < $count; $i++) {
  shuffle($words1);
  shuffle($words2);
  $renderer->add_transaction_detail("{$words1[0]} {$words2[0]}", rand(10,10000));
}
add_roll_segment($pdf,19000,array($renderer, 'render'), $pdf->getCellHeight(8));
$pdf->Output('test-59859076.pdf','I');

编辑:我忽略了包含结果的屏幕截图:

长pdf截图


推荐阅读