2016-05-03 103 views
1

我使用wkhtmltopdf與PHP,它運作良好。 現在,我想添加一些變量從PHP文件到HTML的,但我沒有找到一個解決方案。wkhtmltopdf在html文件中傳遞變量

PHP文件:

<?php 
    require '/path/vendor/autoload.php'; 
    use mikehaertl\wkhtmlto\Pdf; 
    $pdf = new Pdf(array(
     'no-outline', 
     'margin-top' => 0, 
     'margin-right' => 0, 
     'margin-bottom' => 0, 
     'margin-left' => 0, 

     // Default page options 
     'disable-smart-shrinking', 
)); 
if($_GET['file'] == 'public'){ 
    $pdf = new Pdf('template_public.html'); 
}else{ 
    $pdf = new Pdf('template_pro.html'); 
} 
    $pdf->send(); 
?> 

HTML文件:

<html> 
    <head> 
     <title>Generated PDF file</title> 
     <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> 
    </head> 
    <body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"> 
     <div> 
      {title} 
     </div> 
    </body> 
</html> 

我如何可以替換HTML文件的標題{}?

回答

1

這應該用參數數組替換html文件中的所有{variables}。

$params = ["title"=>"title_val", "content" => "something", "key" => "value"]; 
$pdf = new Pdf(); 
$html = file_get_contents($templateFile);  
foreach($params as $key=>$value) { 
    $html = str_replace("{".$key."}", $value, $html); 
} 

//Renders the pdf directly from the html string, instead of loading the file directly 
$pdf->addPage($html); 
$pdf->send(); 
+0

我不確定這會做 –

+0

工作一直忘記params和返回值。否則,爲什麼不呢?好的,現在應該是一個完整的例子。 – overburn

+0

儘管此代碼可能回答此問題,但提供 有關_why_和/或_how_的其他上下文,它將回答 該問題將顯着改善其長期值 的值。請[編輯]你的答案,添加一些解釋。 –

0

我的任務是將真正的客戶端ip值傳遞給pdf。當我讀取IP爲$ ENV {REMOTE_ADDR}時,我得到服務器IP,而不是客戶端IP。

我使用此代碼來解決這個問題:

wkhtmltopdf --cookie remote_addr $IP 

它通過IP變量爲PDF。然後,我的html頁面可以讀取cookie值並在文本中顯示它們。