2015-06-10 24 views
-1

我正在生成要生成PDF文件的項目。 我已經使用Google Chart API來生成不同的圖表。我正在使用TCPDF庫將它們轉換爲PDF,但我無法將這些生成的圖嵌入到PDF中。我認爲TCPDF不接受寫在腳本標記中的內容。我怎樣才能克服這個問題?使用TCPDF庫在PDF中嵌入圖表

+0

顯示您腳本,請。 – Masiorama

回答

0

我遇到了同樣的問題,除了我正在使用FPDF。 在一天結束時,一個PDF文件包含靜態內容,所以不幸的是JavaScript不可能。最後我做什麼:

我準備圖表HTML +的Javascript像往常一樣,並把它寫在我的臨時目錄中的HTML文件。然後我使用PhantomJS(http://phantomjs.org/)創建頁面的屏幕截圖,然後將其包含在我的PDF中(或任何地方,真的)。

偉大的事情:它適用於任何本地HTML頁面。如果您只有一個URL,請使用file_get_contents()或cURL來檢索其內容並首先將其寫入本地HTML文件。

的膽量:

首先,下載並解壓phantomjs.exe到一個目錄應用程序可以訪問。我的例子使用版本1.9.8,我複製到我的應用程序根目錄中的lib/phantomjs。

我有一個不接受作爲參數的HTML文件的路徑和一組PhantomJS選項的功能。我建議將它添加到助手類。

function getHTMLImage($page, $options = array(), $js = null) { 
    // Prepare the PhantomJS directory that contains phantomjs.exe, e.g. lib or vendor 
    $phantomDir = $_SERVER['DOCUMENT_ROOT'] . '/lib/phantomjs/'; 
    // Add the PhantomJS directory to the PATH 
    $origPath = str_replace('"', '', getenv('PATH')); 
    if (!in_array($phantomDir, explode('/', $origPath))) 
      putenv('PATH=' . $origPath . '/' . $phantomDir); 

    // PhantomJS requires a Javascript file to process the request. In case no Javascript processing file is given, use the default 
    if (is_null($js)) $js = $phantomDir . 'phantom.js'; 

    // Prepare the PhantomJS call 
    $exec = 'phantomjs --ignore-ssl-errors=yes ' . $js . ' ' . escapeshellarg($page); 
    // Prepare the PhantomJS options, e.g. width and height 
    foreach ($options as $option) { 
     $exec .= ' ' . escapeshellarg($option); 
    } 

    // Call PhantomJS. To catch errors, call exec($exec . ' 2>&1', $output, $errorMsg); 
    exec($exec, $output); 

    // Decode and return the image data 
    return ($output ? base64_decode(reset($output)) : false); 
} 

JavaScript文件(我稱爲phantom.js並放置在同一個目錄中phantomjs.exe):

args = require('system').args; 
page = require('webpage').create(); 

// In this case, I expect these indexes to be the width and height of the chart 
if (typeof args[2] !== undefined) { 
    page.viewportSize = { 
     width: args[2], 
     height: (typeof args[3] === undefined ? args[2] : args[3]) 
    }; 
} 

page.open(args[1], function() { 
    var base64 = page.renderBase64('png'); 
    console.log(base64); 
    phantom.exit(); 
}); 

這樣稱呼它:

// Make sure $width and $height are set, or exclude them altogether 
$output = getHTMLImage($htmlPath, array($width, $height)); 
// Example output, you want to save the image and include it in your PDF file 
header('Content-Type: image/png'); 
exit($output); 
+0

getHtmlImage()的代碼顯示的錯誤是: - –

+0

調用未定義的函數addpage(); –

+0

我的不好,我是指一個本地定義的函數。我編輯了我的答案,請再試一次。 – RuubW