You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在DOMPDF中使用PHP变量(含Session变量)生成动态PDF?

Fixing Dynamic Data Rendering in DOMPDF

The core issue here is that when you pass an HTML string containing PHP tags directly to loadHtml(), DOMPDF doesn't execute that PHP code—it treats the <?php ... ?> blocks as plain text. That's why your dynamic session variables aren't showing up correctly. Here are a few reliable ways to inject dynamic data before generating the PDF:

1. Use Output Buffering with a Separate PHP Template

This is the most straightforward approach for PHP-based dynamic content. Create a separate PHP file that generates your HTML (with embedded PHP variables), then capture its output and pass it to DOMPDF.

Step 1: Create a Template File (certificate_template.php)

<?php session_start(); ?>
<style>
div.background { background: #ffffff; border: 4px solid black; margin: 10px; }
div.transbox { margin: 3px; background-color: #ffffff; border: 1px solid black; }
div.transbox p { margin: 1%; color: #000000; }
#middle { margin: 5px; background-color: #ffffff; border: 1px solid #fff; }
body{ background-color: #f6f6f6; }
.logowhite{ float: right; }
.logo { clear: right; text-align: center; }
</style>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"/>
<link href="https://vip-organon-us-hcp-com-develop.go-vip.net/nexplanontraining/wp-content/themes/twentytwentyone-child/assets/css/main.min2.css" media="all" type="text/css" rel="stylesheet"/>
<body id="thank-you" class="base"><div id="middle">
<div class="background">
<div class="transbox">
<div class="logowhite">
<img alt="" src="org_logo.jpg" /></div>
<div class="logo">
<img src="nexplanon.jpg" alt="" />
<p style="font-size:1.35rem;color:#00F;text-transform: uppercase;"><?php echo $_SESSION["first_name"]; ?> &nbsp; <?php echo $_SESSION["last_name"]; ?></p>
<p style="font-size: 1.25rem;line-height:25px;">This certificate serves as confirmation of the completion of the Mandatory Training Module<BR> on the updated insertion and removal procedures for NEXPLANON.</p>
<div style="width: 70%;margin: auto;">
<p style="float: left;font-size: 1.25rem;"><B>Training Date:</B> <span style="color: #00F;"><?php echo $_SESSION["mandatory_date"]; ?></span>
</p>
<img style="float:right;" alt="" src="sign.jpg" />
</div>
</div>
<div style="width: 90%;margin: auto;">
<p style="clear: both;margin-bottom: 0%;line-height:18px;"><BR>I attested that I completed the Organon-sponsored Mandatory Training Module on the updated insertion and removal procedures for NEXPLANON in its entirety. I understand that only healthcare providers who have completed the Organon-sponsored Clinical Training Program for NEXPLANON may order, insert, and remove NEXPLANON.<BR><BR>
I certified that I am authorized to perform the procedures entailed in the insertion and removal of NEXPLANON in the jurisdiction where I practice. I attest that if there are specific state requirements in the state where I practice, I have met all appropriate state conditions including but not limited to collaborative or signing agreement with an MD/DO.<BR><BR>
If I am a resident or student in advanced practice training, I understand that I should only administer NEXPLANON under the supervision of an attending healthcare provider who has also been trained on the procedures to insert and remove NEXPLANON.</p>
</div><br/>
<div style="padding-bottom: -2%;">
<p style="font-size: 0.7rem;float: left;">© 2021 Organon group of companies. All rights reserved. ORGANON and the ORGANON Logo are trademarks of the Organon group of companies.</p>
<p style="float: right;font-size: 0.7rem;">US-XPL-115639 12/21</p>
<p style="clear: both;margin-bottom: 0%;">
</p>
</div>
</div>
</div>
</div></body>

Step 2: Modify Your Main PDF Generation Code

<?php
session_start();
// Ensure $mandatory_date, $first_name, $last_name are defined before setting sessions
$_SESSION["mandatory_date"] = $mandatory_date; 
$_SESSION["first_name"] = $first_name; 
$_SESSION["last_name"] = $last_name; 

require_once "./dompdf/autoload.inc.php";
use Dompdf\Dompdf;
use Dompdf\Options;

// Start output buffering to capture the template's rendered HTML
ob_start();
include 'certificate_template.php'; // Executes PHP and generates final HTML
$html = ob_get_clean(); // Get the generated HTML and clear the buffer

$dompdf = new Dompdf();
$dompdf->set_option('isRemoteEnabled', TRUE);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'landscape');
$dompdf->render();
$dompdf->stream("training-certificate", array("Attachments"=>0));
?>

2. Use String Replacement (Inline Template)

If you prefer to keep the HTML in the same file, replace placeholders in your HTML string with actual session values before passing it to DOMPDF:

<?php
session_start();
$_SESSION["mandatory_date"] = $mandatory_date; 
$_SESSION["first_name"] = $first_name; 
$_SESSION["last_name"] = $last_name; 

require_once "./dompdf/autoload.inc.php";
use Dompdf\Dompdf;
use Dompdf\Options;

// Define HTML with placeholders instead of PHP tags
$htmlTemplate = '
<style>
div.background { background: #ffffff; border: 4px solid black; margin: 10px; }
div.transbox { margin: 3px; background-color: #ffffff; border: 1px solid black; }
div.transbox p { margin: 1%; color: #000000; }
#middle { margin: 5px; background-color: #ffffff; border: 1px solid #fff; }
body{ background-color: #f6f6f6; }
.logowhite{ float: right; }
.logo { clear: right; text-align: center; }
</style>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"/>
<link href="https://vip-organon-us-hcp-com-develop.go-vip.net/nexplanontraining/wp-content/themes/twentytwentyone-child/assets/css/main.min2.css" media="all" type="text/css" rel="stylesheet"/>
<body id="thank-you" class="base"><div id="middle">
<div class="background">
<div class="transbox">
<div class="logowhite">
<img alt="" src="org_logo.jpg" /></div>
<div class="logo">
<img src="nexplanon.jpg" alt="" />
<p style="font-size:1.35rem;color:#00F;text-transform: uppercase;">{FIRST_NAME} &nbsp; {LAST_NAME}</p>
<p style="font-size: 1.25rem;line-height:25px;">This certificate serves as confirmation of the completion of the Mandatory Training Module<BR> on the updated insertion and removal procedures for NEXPLANON.</p>
<div style="width: 70%;margin: auto;">
<p style="float: left;font-size: 1.25rem;"><B>Training Date:</B> <span style="color: #00F;">{MANDATORY_DATE}</span>
</p>
<img style="float:right;" alt="" src="sign.jpg" />
</div>
</div>
<div style="width: 90%;margin: auto;">
<p style="clear: both;margin-bottom: 0%;line-height:18px;"><BR>I attested that I completed the Organon-sponsored Mandatory Training Module on the updated insertion and removal procedures for NEXPLANON in its entirety. I understand that only healthcare providers who have completed the Organon-sponsored Clinical Training Program for NEXPLANON may order, insert, and remove NEXPLANON.<BR><BR>
I certified that I am authorized to perform the procedures entailed in the insertion and removal of NEXPLANON in the jurisdiction where I practice. I attest that if there are specific state requirements in the state where I practice, I have met all appropriate state conditions including but not limited to collaborative or signing agreement with an MD/DO.<BR><BR>
If I am a resident or student in advanced practice training, I understand that I should only administer NEXPLANON under the supervision of an attending healthcare provider who has also been trained on the procedures to insert and remove NEXPLANON.</p>
</div><br/>
<div style="padding-bottom: -2%;">
<p style="font-size: 0.7rem;float: left;">© 2021 Organon group of companies. All rights reserved. ORGANON and the ORGANON Logo are trademarks of the Organon group of companies.</p>
<p style="float: right;font-size: 0.7rem;">US-XPL-115639 12/21</p>
<p style="clear: both;margin-bottom: 0%;">
</p>
</div>
</div>
</div>
</div></body>
';

// Replace placeholders with session values
$html = str_replace(
    ['{FIRST_NAME}', '{LAST_NAME}', '{MANDATORY_DATE}'],
    [$_SESSION["first_name"], $_SESSION["last_name"], $_SESSION["mandatory_date"]],
    $htmlTemplate
);

$dompdf = new Dompdf();
$dompdf->set_option('isRemoteEnabled', TRUE);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'landscape');
$dompdf->render();
$dompdf->stream("training-certificate", array("Attachments"=>0));
?>

3. Use a Template Engine (For Complex Projects)

For larger applications, using a template engine like Twig or Blade can simplify managing dynamic HTML. These engines handle variable injection automatically, and you can render the template to a string before passing it to DOMPDF.

Quick Example with Twig:

  1. Install Twig via Composer
  2. Create a Twig template file (certificate.twig) with variables like {{ first_name }}
  3. Render the template to HTML and pass to DOMPDF:
<?php
session_start();
require_once "./dompdf/autoload.inc.php";
require_once './vendor/autoload.php'; // Twig autoloader

$loader = new \Twig\Loader\FilesystemLoader('./templates');
$twig = new \Twig\Environment($loader);

$html = $twig->render('certificate.twig', [
    'first_name' => $_SESSION["first_name"],
    'last_name' => $_SESSION["last_name"],
    'mandatory_date' => $_SESSION["mandatory_date"]
]);

$dompdf = new Dompdf();
$dompdf->set_option('isRemoteEnabled', TRUE);
$dompdf->loadHtml($html);
// ... rest of your PDF generation code
?>

Key Notes:

  • Ensure your session variables are properly initialized and accessible before generating the HTML.
  • For local images, use absolute file paths or base64 encoding to ensure DOMPDF can load them correctly.

内容的提问来源于stack exchange,提问作者Gopal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 16:27:33