我使用名为Dompdf
的PHP库将我的HTML文件转换为PDF。
我已成功将单个HTML文件转换为PDF。
现在我有多个报告要将它们转换为PDF文件。
我在这里有一个例子,我从数据库中获取表单,另一个直接从视图中获取表单。
代码:
$result['patients'] = $this->reports_model->get_xray_reports($id); // getting form from database
require_once "dompdf/dompdf_config.inc.php"; // include dompdf
$dompdf = new DOMPDF();
$dompdf->set_paper("A4");
$html = $this->load->view('wilcare/form_set_page_15',"",true);// loading direct from view
//this file is not converting
$html = $this->load->view('wilcare/report1',$result,true);//loading from db
$dompdf->load_html($html)
$dompdf->render();
$dompdf->stream("hello.pdf",array('Attachment'=>0));
它只转换一个文件。
我也试过了:
$html = $this->load->view('wilcare/form_set_page_15',"",true);
$html1 = $this->load->view('wilcare/report1',$result,true);
$dompdf->load_html($html && $html1);
答案 0 :(得分:4)
您想要使用DOMPDF从两个HTML文件创建PDF文件。
这是不可能的。 DOMPDF支持从一个HTML文档创建一个PDF文件。
内部DOMPDF使用 DOMDocument 来表示HTML文档。因此,如果要将两个HTML文件放入DOMPDF,则必须先将它们合并。
测试确实显示你可以连接mutlitple <head>...</head><body>...</body>
部分(这些部分中的每一部分都将在DOMPDF中开始一个新页面)但是它们需要位于相同的<html>
文档元素内(DOMPDF v0.6.1) )。
如果合并<body>
元素内的元素,则会创建一个页面。
如果您依次追加多个<html>
文档(如Simo所建议的那样),则只会将第一个文档放入PDF中。
我添加了两个PHP示例:
<head>...</head><body>...</body>
中,DOMPDF将其呈现为两页(PDF)E.g。您希望将第二个HTML文档的正文内容附加到第一个HTML文档的正文末尾(所有类型为 DOMDocument 的对象)。 :
$doc1 = create_document(1);
$doc2 = create_document(2);
$doc1Body = $doc1->getElementsByTagName('body')->item(0);
$doc2Body = $doc2->getElementsByTagName('body')->item(0);
foreach ($doc2Body->childNodes as $child) {
$import = $doc1->importNode($child, true);
if ($import) {
$doc1Body->appendChild($import);
}
}
$doc1->saveHTMLFile('php://output');
示例性HTML输出(of this full Example Code):
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Document 1</title>
</head>
<body>
<h1>Document 1</h1>
<p>Paragraph 1.1</p>
<p>Paragraph 1.2</p>
<h1>Document 2</h1>
<p>Paragraph 2.1</p>
<p>Paragraph 2.2</p>
</body>
</html>
创建此PDF:http://tinyurl.com/nrv78br(一页)
这是第二个HTML文档中包含新页面的示例:
foreach ($doc2->documentElement->childNodes as $child) {
$import = $doc1->importNode($child, true);
if ($import) {
$doc1->documentElement->appendChild($import);
}
}
$html = $doc1->saveHTML();
示例性HTML输出:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Document 1</title></head><body>
<h1>Document 1</h1>
<p>Paragraph 1.1</p>
<p>Paragraph 1.2</p>
</body><head><title>Document 2</title></head><body>
<h1>Document 2</h1>
<p>Paragraph 2.1</p>
<p>Paragraph 2.2</p>
</body></html>
创建此PDF:http://tinyurl.com/oe4odmy(两页)
根据您对文档的需求,您可能需要执行其他步骤,例如合并标题和CSS规则(希望可移植)。
答案 1 :(得分:1)
您需要合并这两个文件:
//this file is not converting
$html .= $this->load->view('wilcare/report1',$result,true);