其实我是TCPDF的新手。任何人都可以帮我将数据显示为.pdf
文件。我使用以下代码,数据显示为一般网页。我希望以.pdf
格式显示它。
require_once('../config/lang/eng.php')
require_once('../tcpdf.php')
error_reporting(E_ALL) ; ini_set('display_errors', '1');
$con=mysql_connect("localhost","root","");
if(!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ef_kabaadkhana");
$result = mysql_query("SELECT form_id,partner_name FROM ef_form_master_v1");
if (($result))
{
echo "<table width='100%'><tr>";
if (mysql_num_rows($result)>0)
{
$i = 0;
while ($i < mysql_num_fields($result))
{
echo "<th>". mysql_field_name($result, $i) . "</th>";
$i++;
}
echo "</tr>";
while ($rows = mysql_fetch_array($result,MYSQL_ASSOC))
{
echo "<tr>";
foreach ($rows as $data)
{
echo "<td align='center'>". $data . "</td>";
}
}
}else{
echo "<tr><td colspan='" . ($i+1) . "'>No Results found!</td></tr>";
}
echo "</table>";
}else{
echo "Error in running query :". mysql_error();
}
答案 0 :(得分:4)
你也可以这样做:
if if(($ result))之前插入
ob_start();
在php脚本的末尾,插入
$html = ob_get_contents();
ob_end_clean();
这样做是启动输出缓冲区捕获并抓取您回显到屏幕的所有内容,然后将其存储在$ html变量中。
然后,您只需将$ html变量传递给tcpdf中的writeHTML()函数。我相信你可以查看tcpdf的基本pdf创建示例文档。另外,我偏爱mPDF。我认为它有更好的样式支持
答案 1 :(得分:2)
从官方网站上看看演示。 http://www.tcpdf.org/examples.php
你只需要将所有'echo'替换为某个变量,如下所示:
echo "<table width='100%'><tr>"; //old
$html_text .= "<table width='100%'><tr>"; //new
之后就等于TCPDF $ html变量
$html = $html_text;
记住,
之前不应该有输出(打印,回声等)$pdf->Output('example_006.pdf', 'I');
因为您会看到错误。
答案 2 :(得分:1)
更改所有echo语句,而不是将HTML标记放在变量中。然后使用TCPDF中的writeHTML函数将该标记输出到PDF。请注意,tcpdf不能很好地处理所有标记。像你这样的基于表格的布局通常效果很好,但我发现每行中的所有td单元格通常都需要明确的宽度设置才能正常工作。
编辑:
以下是为writeHTML重新编写的代码:
require_once('../config/lang/eng.php')
require_once('../tcpdf.php')
error_reporting(E_ALL) ; ini_set('display_errors', '1');
$con=mysql_connect("localhost","root","");
if(!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ef_kabaadkhana");
$result = mysql_query("SELECT form_id,partner_name FROM ef_form_master_v1");
if (($result))
{
$html = '';
$html .= "<table width='100%'><tr>";
if (mysql_num_rows($result)>0)
{
$i = 0;
while ($i < mysql_num_fields($result))
{
$html .= "<th>". mysql_field_name($result, $i) . "</th>";
$i++;
}
$html .= "</tr>";
while ($rows = mysql_fetch_array($result,MYSQL_ASSOC))
{
$html .= "<tr>";
foreach ($rows as $data)
{
$html .= "<td align='center'>". $data . "</td>";
}
}
}else{
$html .= "<tr><td colspan='" . ($i+1) . "'>No Results found!</td></tr>";
}
$html .= "</table>";
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// Set various pdf options
$pdf->SetAuthor('John Doe');
// etc.
// Now output the html
$pdf->AddPage();
$pdf->writeHTML($html, true, 0);
// Output the PDF to the browser
$pdf->Output('somefile.pdf', 'D'); // the second option D forces the browser to download the PDF. Passing I will tell the browser to show it inline.
}else{
echo "Error in running query :". mysql_error();
}