我想从一个初始的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资源来实现这一点持开放态度。
有没有办法把我上面的两种方法融合起来?
当然,您也可以使用FPDI使用不同的现有PDF文档。这个代码应该向你展示这个概念(实际上我猜所有的页面格式都是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();