gotenberg html转dpf

Quick Start

docker run --rm -p 3000:3000 gotenberg/gotenberg:8

Convert a URL to PDF:

curl \
  --request POST http://localhost:3000/forms/chromium/convert/url \
  --form url=https://sparksuite.github.io/simple-html-invoice-template/ \
  -o invoice.pdf

PHP

/**
* 通过file_get_contents发送HTMLGotenberg转换PDF
*/
private function sendToGotenberg($html)
{
// 先将HTML写入临时文件
$tmpFile = tempnam(sys_get_temp_dir(), 'gtb_');
file_put_contents($tmpFile, $html);

$postFields = [
'files' => new \CURLFile($tmpFile, 'text/html', 'index.html'),
'paperWidth' => '8.27',
'paperHeight' => '11.7',
'marginTop' => '0.4',
'marginBottom' => '0.4',
'marginLeft' => '0.4',
'marginRight' => '0.4',
'waitForExpression' => "document.querySelectorAll('img').length === 0 || Array.from(document.querySelectorAll('img')).every(img => img.complete)",
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, self::GOTENBERG_URL . '/forms/chromium/convert/html');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
$errno = curl_errno($ch);
curl_close($ch);

@unlink($tmpFile);

if ($errno !== 0) {
recordlog("Gotenberg请求失败 [errno={$errno}]: {$error}", 'gotenberg');
return false;
}

if ($httpCode !== 200) {
recordlog("Gotenberg返回异常 HTTP {$httpCode}: " . substr($result, 0, 500), 'gotenberg');
return false;
}

if (empty($result)) {
recordlog("Gotenberg返回空响应", 'gotenberg');
return false;
}

return $result;
}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注