create PDF with emoji utf-8 character using php - php

I am trying to create pdf with text including emoji character.
using PHP > 7 and mysql
'char_set' => utf8mb4
'dbcollat' => utf8mb4_unicode_ci
I have create PDF from html, is echo html text all emoji shown good. but if its create pdf its not convert.
Please help to solve this problem
exampple : "One \ud83d\ude02"
thanks
Here is more explanation for simplify my question.
$fileName = $source_path.'example.pdf';
//using php codeignitor 3.1.2
$htmlContent = $this->load->view('view/view_pdf', $data, TRUE);
$htmlContent = <<<EOD
$htmlContent
EOD;
// call pdf create function
$this->createPDF($fileName, $htmlContent);
// these character working correct as echo output on browser and send in email subject n body.
echo decodeEmoticons("One \ud83d\ude02");
echo "One \u{1F602}";
/*******************************/
// helper functions
function checkJson($title){
if (json_decode($title, true) !== null) {
$title = str_replace('"', '', json_decode($title));
}else{
$title = str_replace('"', '', $title);
}
return $title;
}
function decodeEmoticons($src) {
$replaced = preg_replace("/\\\\u([0-9A-F]{1,4})/i", "&#x$1;", $src);
$result = mb_convert_encoding($replaced, "UTF-16", "HTML-ENTITIES");
$result = mb_convert_encoding($result, 'utf-8', 'utf-16');
$result = checkJson($result);
return $result;
}
/*******************************/
$htmlContent output html code as follows
<div class="row">
<div class="col-lg-12">
<table class="table dataTable" border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td colspan="3"> </td>
</tr>
<tr>
<td width="60%"><b>Event Name:</b> <?php echo decodeEmoticons("One \ud83d\ude02"); ?> </td>
<td width="60%"><b>Event Name:</b> <?php echo "One \u{1F602}"; ?> </td>
<td><b>Start Time:</b> <?php echo date('F j, Y, g:i A', time()); ?></td>
</tr>
<tr>
<td colspan="3"></td>
</tr>
</tbody>
</table>
</div>
</div>
here is my php function call TCpdf library
public function createPDF($fileName, $htmlContent) {
/*
http://www.tcpdf.org
// File name : tcpdf.php
// Version : 6.2.13
// Begin : 2002-08-03
// Last Update : 2015-06-18
*/
ob_start();
// Include the main TCPDF library (search for installation path).
$this->load->library(array('Tcpdf'));
// create new PDF document
$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
//$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, false, 'ISO-8859-1', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('auth');
$pdf->SetTitle('Event ');
$pdf->SetSubject('Event ');
$pdf->SetKeywords('Event ');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
$pdf->SetPrintHeader(false);
$pdf->SetPrintFooter(false);
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, 10, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(10);
$pdf->SetFooterMargin(30);
// set auto page breaks
//$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$pdf->SetAutoPageBreak(TRUE, 30);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (#file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
$pdf->SetFont('dejavusans', '', 10);
//$pdf->SetFont('halvatica', '', 10); // this is also trying but fail
// add a page
$pdf->AddPage();
//$htmlContent = utf8_encode($htmlContent);// this is also trying but fail
// output the HTML content
$pdf->writeHTML($htmlContent, true, false, true, false, '');
// reset pointer to the last pagend output PDF document
$pdf->lastPage();
ob_end_clean();
//Close and output PDF document
$pdf->Output($fileName, 'F');
}
pdf output not showing correct with emoji character.

Related

how to store Datamatrix QR code in mysql Database?

I want store Data-matrix library generate QR code Image into mysql database using php. i am trying this by using jpgraph library.
please provide solution..
<?php
require_once('jpgraph/datamatrix/datamatrix.inc.php');
$data = '1234567890';
$shape = DMAT_AUTO;
$encoding = ENCODING_AUTO;
$modulewidth = 3;
$quietzone = 10;
$color1 = 'black';
$color0 = 'white';
$colorq = 'white';
$outputfile = '';
// Create and set parameters for the encoder
$encoder = DatamatrixFactory::Create($shape);
$encoder->SetEncoding($encoding);
// Create the image backend (default)
$backend = DatamatrixBackendFactory::Create($encoder);
// By default the module width is 2 pixel so we increase it a bit
$backend->SetModuleWidth($modulewidth);
// Set Quiet zone
$backend->SetQuietZone($quietzone);
// Set other than default colors (one, zero, quiet zone/background)
$backend->SetColor($color1, $color0, $colorq);
// Create the barcode from the given data string and write to output file
try {
$backend->Stroke($data,$outputfile);
} catch (Exception $e) {
$errstr = $e->GetMessage();
echo "Datamatrix error message: $errstr\n";
}
?>
$data = '123456789';
$pdf = new Pdf(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetTitle('ECOMAL ');
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->SetMargins(2,2,2);
$pdf->SetHeaderMargin(0);
$pdf->SetFooterMargin(0);
$pdf->SetAutoPageBreak(TRUE, 0);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
if (#file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
$pdf->SetFont('helvetica', 'B', 18);
$pdf->SetFont('helvetica', '', 15);
$style = array(
'fgcolor' => array(0,0,0),
'bgcolor' => false,
);
foreach ($data as $value) {
$tbl = '<table border="1" cellpadding="1">
<tr><td>
<table cellpadding="1" cellspacing="6" nobr="true">
<tr><td colspan="3"><h1> Vishy Intertechnology Inc.</h1></td></tr>
<tr><td colspan="3"><hr></td></tr>
<tr><td>Customer PN</td><td colspan="2" ><b>'. $value["customer_pin"].'</b></td></tr>
<tr><td>Customer PO</td><td colspan="2" ><b>'. $value["customer_po"] .'</b></td></tr>
<tr><td>Manfacture PN</td><td colspan="2" >'. $value["manufacture_pin"] .' </td></tr>
<tr><td>Quantity</td><td>'.$value["quantity"].'</td><td rowspan="4" width="35%"></td></tr>
<tr><td>Date Code</td><td>'.$value["date_of_code"] .'</td></tr>
<tr><td>Lot No</td><td>'.$value["lot_no"] .'</td></tr>
<tr><td>Serial No</td><td>'. $value["serial_no"].' </td></tr>
<tr><td>MSL</td><td>'.$value["msl"].'</td><td><br></td></tr>
</table>
</td></tr>
</table><br><br>
';
$pdf->AddPage('L','A6');
//$pdf->SetY(50);
$pdf->writeHTML($tbl, true, false, false, false, '');
$pdf->write2DBarcode($value['code_string'], 'DATAMATRIX', 105, 48, 35, 35, $style, 'N');
}
//ob_clean();
//Close and output PDF document
//$rand = rand();
$pdf->Output($_SERVER['DOCUMENT_ROOT']."/alcon/assets/ecomal.pdf", 'F');
$pdf->Output("ecomal.pdf", 'I');

how to solve this error of geting undefined offset 0 using TCPDF in PHP

this is the part that I declare to generate pdf from table. I have watch the tutorial in youtube and followed all the steps and I still got error. Im new in programming field and this is one of my mini project.
the error that i got is :
Notice: Undefined offset: 0 in C:\xampp\htdocs\tcpdff\tcpdf.php on line 17162
function fetch_data()
{
$output ='';
$conn = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
$query = "SELECT * FROM borang_permohonan";
$results = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($results))
{
$output .='
<tr>
<td>'.$row["fullname"].' </td>
<td>'.$row["ic_no"].'</td>
<td>'.$row["email"].' </td>
</tr>
';
}
return $output;
}
if(isset($_POST["create_pdf"]))
{
require_once('tcpdf.php');
$obj_pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$obj_pdf->SetCreator(PDF_CREATOR);
$obj_pdf->SetTitle("Export HTML Table data to pdf using TCPDF in PHP");
$obj_pdf->SetHeaderData('', '', PDF_HEADER_TITLE, PDF_HEADER_STRING);
$obj_pdf->SetHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$obj_pdf->SetFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
$obj_pdf->SetDefaultMonospacedFont('helvetica');
$obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
$obj_pdf->SetMargins(PDF_MARGIN_LEFT, '5', PDF_MARGIN_RIGHT);
$obj_pdf->setPrintHeader(false);
$obj_pdf->setPrintFooter(false); //or true
$obj_pdf->SetAutoPAgeBreak(TRUE, 10);
$obj_pdf->SetFont('helvetica', '', 12);
$content = '';
$content .= '
<center><h2 >GSM 2019</h2></center>
<table align="center" border="1">
<thead>
<tr>
<th>fullname</th>
<th>ic no</th>
<th>email</th>
</tr>
</thead>
';
$content .= fetch_data();
$content .= '</table>';
$obj_pdf->writeHTML($content);
$obj_pdf->Output("sample.pdf", "I");
}
?>
Any answer will be appreciated! Thank you!
You need to call the AddPage method before you start your WriteHtml
Good spot would probably be, right after SetFont
$obj_pdf->SetFont('helvetica', '', 12);
$obj_pdf->AddPage();
Instead of:
$obj_pdf->writeHTML($content);
Use this:
$obj_pdf->writeHTMLCell(0, 0 , '' , '' , $content);

PDF generation with Japanese fonts in Codeigniter using TCPDF

I am facing problem to generate japanese text based pdf using TCPDF. Previously I was working in raw php, html and css and tcpdf was working just fine with the following code:
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
if (#file_exists(APPPATH . 'libraries/tcpdf/examples/lang/eng.php')) {
require_once(APPPATH . 'libraries/tcpdf/examples/lang/eng.php');
$pdf->setLanguageArray($l);
}
if (#file_exists(APPPATH . 'libraries/tcpdf/examples/lang/jpn.php')) {
require_once(APPPATH . 'libraries/tcpdf/examples/lang/jpn.php');
$pdf->setLanguageArray($l);
}
$pdf->setLanguageArray($l);
$pdf->setPrintHeader(false);
$pdf->setFontSubsetting(true);
$pdf->SetFont('cid0jp', '', 11);
$pdf->AddPage();
$pdf->writeHTML($html, true, false, true, false, '');
$pdf->Output('result.pdf', 'I');
which can generate my desired pdf with japanese text.
氏名
(全角・名字と名前の間に字スペー
ス)
Name
(Last Name/First name)
But when I tried to include this in codeigniter controller, the japanese texts are showing question marks in the generated pdf:
require_once(APPPATH . 'libraries/tcpdf/tcpdf.php');
The pdf output becomes like the following:
??
(?????????????????)
Name
(Last Name/First name)
What I am missing? Can anybody give me a solution? I will greatly appreciate a help here.
You can try any one from listed (because I'm not sure which one works for you):-
1) $pdf->SetFont('kozgopromedium', '', 11);
2) $pdf->SetFont('kozminproregular', '', 11);
3) $pdf->SetFont('cid0jp', '', 11);
4) $pdf->SetFont('arialunicid0', '', 11);
5) $pdf->SetFont('arialuni', '', 12);
If you have font file(.ttf) in your system, then you can give path also like :-
$pdf->addTTFfont('path/myfont.ttf', '', '', 11);

Hindi is not displaying properly in TCPDF

I am trying to generate PDF using TCPDF with Hindi Unicode characters. I tried Mangal, Noto Sans, Arial Unicode fonts but all give the same output. If there is a "Matra" or "Half character" then it does not display properly.
See this output:
<?php
error_reporting(E_ALL);
ini_set("display_errors", "On");
require_once 'vendor/autoload.php';
$hindi_str = "राष्ट्रपति प्रणव मुखर्जी। ";
$hindi_str2 = "देश हमें देता है सब कुछ";
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
//$fontname_kannada = TCPDF_FONTS::addTTFfont('NotoSansKannada-Regular.ttf', 'TrueTypeUnicode', '', 96);
$fontname_hindi1 = TCPDF_FONTS::addTTFfont('NotoSansDevanagari-Regular.ttf', 'TrueTypeUnicode', '', 96);
$fontname_hindi2 = TCPDF_FONTS::addTTFfont('mangal.ttf', 'TrueTypeUnicode', '', 96);
$fontname_hindi3 = TCPDF_FONTS::addTTFfont("ARIALUNI.TTF", 'TrueTypeUnicode', '', 96);
// use the font
$pdf->AddPage();
$pdf->SetFont($fontname_hindi3, '', 14, '', false);
$pdf->writeHTML("<h1>Hindi $hindi_str $hindi_str2</h1>",true, false, true, false, '');
$pdf->Ln();
$pdf->writeHTML("<h1>Kannada ಖುತುಬ್ ಮಿನಾರ್ ಸಮೀಪವಿರುವ ಪ್ರಸಿದ್ಧ ಕಬ್ಬಿಣದ ಕಂಬ ಯಾರಿಗೆ ಸೇರಿದೆ</h1>",true, false, true, false, '');
// output the HTML content
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example.pdf', 'I');
Please help.
I know it's a little late, but I had the same problem for nepali (which also uses devanagari). I solved it like this:
// SOME FONTS DOES NOT SUPPORT DEVANAGARI, BUT FREESANS DOES
$pdf->SetFont('freesans', '', 10);
// MAKE ARRAY WITH UTF LANGUAGE IDENTIFIER
$lg = Array();
$lg['a_meta_charset'] = 'UTF-8';
$lg['a_meta_dir'] = 'ltr';
$lg['a_meta_language'] = 'np'; // I think you can change this to HI or IN for hindi
$lg['w_page'] = 'page';
// CHANGE SETTINGS IN TCPDF
$pdf->setLanguageArray($lg);
// MAKE SURE TO USE WriteHTML() function
$pdf->WriteHTML($yourhtml, true, 0, true, 0);
You can use this if Hindi is not showing on TCPDF
$pdf->SetFont('freesans', '', 10);
$lang = Array();
$lang['a_meta_charset'] = 'UTF-8';
$lang['a_meta_dir'] = 'ltr';
$lang['a_meta_language'] = 'IN';
$lang['w_page'] = 'page';
$pdf->setLanguageArray($lang);
$pdf->WriteHTML($html, true, 0, true, 0);

Set/Add Background Image in PDF using Symfony Framework

I'm making an HTML PDF template and I'm about to set the background image.
Here's my code below:
<?php
class pdfAction extends sfAction{
public function execute($request){
$id = $request->getParameter('id');
if(!$id){
return $this->forward404();
}
$testTemplate = Doctrine_Core::getTable('PrintManual')->findOneById($id);
if(!$testTemplate){
return $this->forward404();
}
$config = sfTCPDFPluginConfigHandler::loadConfig('my_config');
sfTCPDFPluginConfigHandler::includeLangFile($this->getUser()->getCulture());
$pdf = new sfTCPDF();
$pdf->SetTitle('Precena Biz - Test Template');
$pdf->SetSubject('Precena Biz - Test Template');
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
$content = myTools::loadTemplate('pdfTpl',array('test'=>$testTemplate), sfConfig::get('sf_root_dir') . '/apps/AdmSys/modules/test/templates');
$pdf->AddPage();
$pdf->SetFont('kochiminchosubst', "", 13);
$pdf->writeHTML($content, true, 0);
//$pdf->AddI();
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->Output('test.pdf', 'I');
throw new sfStopException();
return $this->renderText('');
}
}
How will I add or set the image into background ?
I would suggest to use wkhtmltopdf
tool. https://code.google.com/p/wkhtmltopdf/

Categories