gpt4 book ai didi

php - 如何在现有 PDF 之上覆盖 HTML 生成的 PDF?

转载 作者:行者123 更新时间:2023-12-03 20:34:04 25 4
gpt4 key购买 nike

我希望从一个包含图形和文本的初始 PDF 文件开始,然后采用一些具有某些用户输入动态值的 html 代码,将其生成为 PDF,希望要么使用初始 PDF 作为背景,或者之后以某种方式运行 PHP 脚本以“合并”两个 PDF,其中一个充当另一个的背景。

我有一些代码可以呈现 HTML 格式的 PDF:(使用 DOMPDF)

$initialpdf = file_get_contents('file_html.html');

$initialpdf = str_replace(array(
'%replaceText1%',
'%replaceText2%'
), array (
$replaceText1,
$replaceText2,
), $initialpdf);

$fp = fopen('file_html_new.html','w');
file_put_contents('file_html_new.html', $initialpdf);

require_once("dompdf/dompdf_config.inc.php");
spl_autoload_register('DOMPDF_autoload');
function pdf_create($html, $filename, $paper, $orientation, $stream=TRUE)
{
$dompdf = new DOMPDF();
$dompdf->set_paper($paper,$orientation);
$dompdf->load_html($html);
$dompdf->render();
$pdf = $dompdf->output();
@file_put_contents($filename . ".pdf", $pdf);
}
$filename = 'HTML_Generated_pdf';
$dompdf = new DOMPDF();
$html = file_get_contents('file_html_new.html');
pdf_create($html,$filename,'Letter','landscape');

上面的代码采用 html 文件“file_html.html”并使用用户输入值进行字符串替换,将其呈现为名为“file_html_new.html”的新 HTML 文件,然后将其呈现为 PDF。

我还有其他 PHP 代码通过将 PDF 作为初始源来呈现 PDF:(使用 FPDF)
<?php
ob_clean();
ini_set("session.auto_start", 0);
define('FPDF_FONTPATH','font/');
define('FPDI_FONTPATH','font/');
require('fpdf.php');
require('fpdi.php');

$pdf = new FPDI();
$pdf->setSourceFile("/home/user/public_html/wp-content/myPDF.pdf");
$tplIdx = $pdf->importPage(1);
$specs = $pdf->getTemplateSize($tplIdx);
$pdf->addPage($specs['h'] > $specs['w'] ? 'P' : 'L', 'Letter');
$pdf->useTemplate($tplIdx, 0, 0);

$pdf->SetFont('helvetica');
$pdf->SetXY(30, 30);
$pdf->Write(0, $replaceText1);
ob_end_clean();
$pdf->Output('New_Generated_PDF.pdf', 'F');
?>

这需要一个已经存在的 PDF,“myPDF.pdf”,并将其用作背景,将一些传递的值写入文档,并保存新生成的文档。

虽然这基本上是我想要做的,但我需要使用 html,因为文本的确切格式变得严格并且几乎不可能仅通过手动绘制来完成。

我愿意使用 DOMPDF、FPDF、FPDI、TCPDF 或任何其他 PHP 资源来完成此任务。

有没有办法融合我上面的两种方式?

最佳答案

当然,您也可以将不同的现有 PDF 文档与 FPDI 一起使用。这段代码应该向您展示这个概念(实际上我猜所有页面格式都是 A4 纵向):

<?php

$pdf = new FPDI();

// let's get an id for the background template
$pdf->setSourceFile('myPDF.pdf');
$backId = $pdf->importPage(1);

// iterate over all pages of HTML_Generated_pdf.pdf and import them
$pageCount = $pdf->setSourceFile('HTML_Generated_pdf.pdf');
for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
// add a page
$pdf->AddPage();
// add the background
$pdf->useTemplate($backId);
// import the content page
$pageId = $pdf->importPage($pageNo);
// add it
$pdf->useTemplate($pageId);
}

$pdf->Output();

关于php - 如何在现有 PDF 之上覆盖 HTML 生成的 PDF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36752092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com