มาใส่ font awesome ใน mpdf กัน
พอดีมีงานที่ต้องใช้ mpdf แล้วก็มันมีบางส่วนที่ต้องแสดงไอคอนเล็กๆบางจุด จะทำเป็นรูปภาพก็ลำบากในการปรับขนาดอีก ก็นึกถึง font awesome ก็เลยลองเอามาใส่ดูก็โอเคนะ แต่ตอนใส่ก็มีปัญหาบ้าง สุดท้ายก็เจอวิธีแก้ใน stack overflow เลยมาเขียนบล็อกเตือนความจำไว้
ขอข้ามขั้นตอนติดตั้งไปเลยแล้วกัน หลังจากโหลด ทั้ง mpdf แล้วก็ font awesome มาแล้ว
- copy font-awesome/fonts/fontawesome-webfont.ttf ไปยัง mpdf/ttfonts/
- เปิดไฟล์ mpdf/config_fonts.php
- ค้นหาบรรทัดที่กำหนดค่าให้ fontdata แล้วก็เพิ่มต่อท้ายไปThis file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
<?php // some code $this->fontdata = array( //font1, //font2, // เพิ่ม fontawesome ต่อท้าย // key แนะนำให้เป็นตัวเล็กหมด หรือคั่นด้วย '-' ไม่แนะนำตัวใหญ่เพราะมันจะหาไม่เจอ 'fontawesome' => array( 'R' => 'fontawesome-webfont.ttf' ) ); - จากนั้นมาลองเขียนใช้งานง่ายๆดูThis file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
<?php include 'mpdf60/mpdf.php'; $css = '<style>'.file_get_contents(getcwd().'/css/font-awesome.min.css').'</style>'; $pdf = new mPDF(); $pdf->WriteHtml($css); $pdf->WriteHTML('<i class="fa fa-heart"></i>'); $pdf->Output();
ผลลัพธ์ที่ได้คือ ความว่างเปล่า
ทำไมมันถึงว่างเปล่า มาดูในไฟล์ font-awesome.css กัน
ใน font-awesome ใช้ before Selector ซึ่ง mpdf ไม่รองรับ แล้วทำไงดี?
เห็นตรง content ในรูปไหม?
content แต่ละตัวก็คือ HTML Symbols ซึ่งเราสามารถ copy ไปใช้ได้เลย ก็ลองเปลี่ยน โค้ดนิดหน่อยจากในไฟล์ css มันจะเป็นแบบนี้ "\f004" ก็เขียนเป็นแบบนี้ซะ "" ถ้าถามว่าทำไมต้องเป็นแบบนี้ก็ไปอ่าน HTML Symbols ซะ
ทีนี้แก้นิดหน่อยแล้วลองใหม่
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
include 'mpdf60/mpdf.php'; | |
$css = '<style>'.file_get_contents(getcwd().'/css/font-awesome.min.css').'</style>'; | |
$pdf = new mPDF(); | |
$pdf->WriteHtml($css); | |
$pdf->WriteHtml('<style>.fa{font-family:"fontawesome";}</style>'); | |
$pdf->WriteHTML('<i class="fa"></i>'); | |
$pdf->WriteHTML('<i class="fa fa-lg"></i>'); | |
$pdf->Output(); |
เท่านี้ก็จะสามารถแสดงผลได้แล้วการปรับขนาดก็ทำได้โดยการปรับขนาดฟอนต์
ในส่วนของ บรรทัดนี้
$pdf->WriteHtml('<style>.fa{font-family:"fontawesome";}</style>');
ชื่อฟอนต์ต้องกำหนดให้เหมือนกับในไฟล์ config_fonts.php นะ นี่เขียน style ทับอันเดิมเพราะไม่อยากไปแก้ในไฟล์ css เดิม ก็ประมาณนี้แหละ
* ที่ภาพมันมืดเพราะเวลา capture หน้าจอใน mac ยังหาวิธีปิด shadow ไม่ได้
* mpdf ที่ใช้ในบล็อกนี้เป็น version 6
References