CaiWuXiTong/app/Support/PdfSigningPositions.php

47 lines
1.5 KiB
PHP

<?php
namespace App\Support;
use Barryvdh\DomPDF\PDF;
use DOMElement;
final class PdfSigningPositions
{
/** Measure the stamp boxes on the same pages that are sent for signing. */
public static function render(PDF $pdf, string $attribute, string $value): array
{
$positions = [];
$dompdf = $pdf->getDomPDF();
$callbacks = [];
foreach ($dompdf->getCallbacks() as $event => $handlers) {
foreach ($handlers as $handler) {
$callbacks[] = ['event' => $event, 'f' => $handler];
}
}
$dompdf->setCallbacks([...$callbacks, [
'event' => 'end_frame',
'f' => static function ($frame, $canvas) use (&$positions, $attribute, $value): void {
$node = $frame->get_node();
if (! $node instanceof DOMElement || $node->getAttribute($attribute) !== $value) {
return;
}
$box = $frame->get_position();
$positions[] = [
'positionPage' => (string) $canvas->get_page_number(),
'positionX' => round($box['x'] + $frame->get_margin_width() / 2, 2),
'positionY' => round($canvas->get_height() - $box['y'] - $frame->get_margin_height() / 2, 2),
];
},
]]);
try {
$bytes = $pdf->output();
return ['bytes' => $bytes, 'signing_positions' => $positions];
} finally {
$dompdf->setCallbacks($callbacks);
}
}
}