如何在PHP的FPDF库中输出变量?
问题:FPDF无法输出变量内容到PDF
我尝试使用FPDF生成PDF文档,但无法将变量内容输出到PDF中。当直接写字符串$pdf->Write(5, "This is some example text");时可以正常输出,但使用变量就不行。请问如何在FPDF生成的PDF中输出变量内容?
以下是我的代码:
<html> <head><title>FPDF</title></head> <body> <?php //I would like to print out the text in the variable echo "Would you like to convert to php?"; $enteredText = "This is some example text"; if ($_GET["action"]=="yes") { ob_start(); require('fpdf.php'); // Instantiate and use the FPDF class $pdf = new FPDF(); //Add a new page $pdf->AddPage(); // Set the font for the text $pdf->SetFont('Arial', 'B', 18); // Prints a cell $pdf->Write(5, $enteredText); // return the generated output $pdf->Output(); ob_end_flush(); } else if ($_GET["action"]=="no") { } ?> <a href = "Trying.php?action=yes"><button>yes</button></a> <a href = "Trying.php?action=no"><button>no</button></a> <form id="form" action="Trying.php" method="POST"> <input type="text" name="text" placeholder="Text"><br /> <input type="submit" value="Enter"><br /> </form> </body> </html>
解决方案
1. 移除多余的输出缓冲函数
FPDF的Output()方法本身会处理HTTP头和输出逻辑,额外的ob_start()和ob_end_flush()可能干扰PDF输出的完整性。直接移除这两个函数,并在输出后终止脚本,避免后续HTML内容混入PDF:
if ($_GET["action"]=="yes") { require('fpdf.php'); $pdf = new FPDF(); $pdf->AddPage(); $pdf->SetFont('Arial', 'B', 18); $pdf->Write(5, $enteredText); $pdf->Output(); exit; // 终止脚本,防止后续HTML破坏PDF格式 }
2. 确认变量值的有效性
在生成PDF前可以先调试变量,确保它确实包含预期内容:
if ($_GET["action"]=="yes") { var_dump($enteredText); // 打印变量内容确认 exit; // 先验证值再执行后续PDF生成逻辑 }
3. 处理表单提交的用户输入
你的表单采用POST提交,但当前代码未处理这部分逻辑。如果需要将用户输入的文本输出到PDF,可以通过Session传递内容:
// 处理表单POST提交 if ($_SERVER['REQUEST_METHOD'] === 'POST') { session_start(); $_SESSION['pdf_text'] = $_POST['text'] ?? '默认文本'; // 接收用户输入,设置默认值 header("Location: Trying.php?action=yes"); // 跳转到生成PDF的页面 exit; } // 生成PDF时读取Session中的内容 if ($_GET["action"]=="yes") { session_start(); $enteredText = $_SESSION['pdf_text'] ?? 'This is some example text'; // 优先使用用户输入,无输入则用默认值 require('fpdf.php'); $pdf = new FPDF(); $pdf->AddPage(); $pdf->SetFont('Arial', 'B', 18); $pdf->Write(5, $enteredText); $pdf->Output(); exit; }
4. 解决编码问题(针对非ASCII字符)
如果变量包含中文或其他非ASCII字符,FPDF原生不支持UTF-8编码,需要先转换编码:
$pdf->Write(5, utf8_decode($enteredText));
或者使用支持UTF-8的FPDF衍生版本(如TCPDF)来简化多语言字符处理。
内容的提问来源于stack exchange,提问作者user21013509
相关产品推荐
相关产品推荐

