iT邦幫忙

0

dompdf 範例程式碼問題

Rach 2019-08-25 22:51:152207 瀏覽
  • 分享至 

  • xImage

嗨各位,我是個剛接觸php沒多久的菜鳥,而我為了將php轉為pdf,所以上了這個套件照著他的步驟執行了範例程式碼,但在一番折磨後,程式碼可以執行了,產生出來的pdf卻都是損毀的,請問有過來人有這個問題過嗎?

// reference the Dompdf namespace
use Dompdf\Dompdf;

// instantiate and use the dompdf class
$dompdf = new Dompdf();
$dompdf->loadHtml('hello world');

// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');

// Render the HTML as PDF
$dompdf->render();

// Output the generated PDF to Browser
$dompdf->stream();

我爬文過,嘗試在stream前加上了ob_end_clean,但我載入的是一串文字,怎麼樣想也不太可能是buffer的問題,真的是遇到大瓶頸,網路上貌似都是有使用到壓縮才開始遇到問題,怎麼我的開頭特別煎熬...而我使用的環境為php7與apache,現在這謝謝大家。

---28/8/19 Updated---

我現在的問題,是在woocommercewoocommerce_thankyou這個hook上,在多加上一個action,在檢查那些損毀的pdf檔案中,裏頭的內容是半張網頁的程式碼,看來是buffer在作怪,但是這個hook裏頭只要ob_clean後,整個動作就會直接終止,這一點我還想不清楚,所以我以其他的方式來做存取。

//將stream,用output來取代
//$dompdf->stream();

$file = 'tmp1'
$output->$dompdf->output();
file_put_contents(__DIR__.'/'.$file.'.pdf', $output);

位址的關係,我並沒有寫在plugins的根目錄,而是另外製作了一個資料夾產生的method來存放這些暫存的檔案,有著實體的檔案也可以使用下載的方式來取代stream或者是用header來自動下載。

$File = __DIR__.'/'.$file.'.pdf';
header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");
header("Content-Type: application/octet-stream");
header("Content-Length: " . filesize($File));
header("Connection: close");
ccutmis iT邦高手 2 級 ‧ 2019-08-26 09:16:38 檢舉
https://github.com/dompdf/dompdf/releases/tag/v0.8.3
去研究一下它的Requirements 看看是否少了什麼

思路: 能產出pdf表示程式有運作,但是在render時期出了什麼問題
可能是有些Requirements要求的項目沒有安裝導致 我沒有用這個套件 所以只是猜的
Rach iT邦新手 4 級 ‧ 2019-08-26 23:34:45 檢舉
@ccutmis 大大你好,我每一項require都有去檢查過了,不過依舊沒辦法。
倒是找到了一個與我一樣遇到同樣問題的人
dompdf creates defective pdf on wordpress

https://stackoverflow.com/questions/39222153/dompdf-creates-defective-pdf-on-wordpress
Rach iT邦新手 4 級 ‧ 2019-08-27 22:19:12 檢舉
ccstmis 你好,果然是render出了問題,將整個buffer塞進去,只好找另外的hook。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答