Set/Add Background Image in PDF using Symfony Framework - php

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/

Related

create PDF with emoji utf-8 character using 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.

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);

TCPDF expects parameter 2 to be string, object given

Good day, I'm trying to create PDF with TCPDF But i got an error.
Here is my script
function print_do($kode)
{
$this->load->library('Pdf');
$obj_pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$obj_pdf->SetCreator(PDF_CREATOR);
$title = "PDF Report";
$obj_pdf->SetTitle($title);
$obj_pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, $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->SetHeaderMargin(PDF_MARGIN_HEADER);
$obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
$obj_pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$obj_pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$obj_pdf->SetFont('helvetica', '', 9);
$obj_pdf->setFontSubsetting(false);
$obj_pdf->AddPage();
$data=array();
$data['header'] = $this->modelmodel->showsingle("select * from deliveryorder where TransactionNo = '".$kode."' ");
$rslt = $data['header'];
$data['detail'] = $this->modelmodel->showdata("select a.*,b.ItemName from DeliveryOrderDetail a
left join item b on a.ItemCode = b.ItemCode
where DeliveryOrderTransNo = '".$rslt->TransactionNo."' ");
$data['Title'] = "Do Mutasi";
$data['Title_Description'] = "Form Input Do Mutasi";
$data['type'] = $this->db->query("SELECT * FROM DeliveryOrderCategory")->result();
$data['outlet'] = $this->modelmodel->showsingle("select OutletCode from
employee where nip = '".$this->input->cookie('cookie_posweb_user')."' ");
$data['tipeitem'] = $this->modelmodel->showsingle("select TOP 1 ItemType from DeliveryOrderDetail a
left join Item b on a.ItemCode = b.ItemCode
where DeliveryOrderTransNo = '".$rslt->TransactionNo."'");
$content = $this->load->view('do_mutasi/print_view',$data);
$obj_pdf->writeHTML($content, true, false, true, false, '');
$obj_pdf->Output($kode, 'S');
}
I got multiple error.
preg_match_all() expects parameter 2 to be string, object given
Object of class CI_Loader could not be converted to string
and then in the end of page(After the error ). My view is showing up. I cant speak well or write well in english. So i think it's my best explanation.
And I'm trying to change
$obj_pdf->Output($kode, 'S');
to
$obj_pdf->Output($kode, 'I');
My view at the end of page is missing.

PDF is not generated in codeigniter and display blank

I am working in codeigniter.I have downloaded TCPDF for creating pdf. I have followed all step for generating pdf in codeigniter.
My controller is:
function list_branch_report()
{
if($this->input->post('submit'))
{
$this->load->library('Pdf');
$pdf = new Pdf('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetTitle('Pdf Example');
$pdf->SetHeaderMargin(30);
$pdf->SetTopMargin(20);
$pdf->setFooterMargin(20);
$pdf->SetAutoPageBreak(true);
$pdf->SetAuthor('Author');
$pdf->SetDisplayMode('real', 'default');
$pdf->Write(5, 'CodeIgniter TCPDF Integration');
$pdf->AddPage();
$pdf->Output('pdfexample.pdf', 'I');
$branch_id = $this->input->post('br_name');
$branch_code = $this->input->post('branch_code');
$query1 = $this->db->query("select * from branch_bal where branch_id = '$branch_id'");
$result1 = $query1->result();
$query2 = $this->db->query("select * from cash_depo where bid = '$branch_id'");
$result2 = $query2->result();
$this->load->view("admin/list_branch_report",array('br_result'=>$result1,'cash_result'=>$result2,'b_code'=>$branch_code));
}
And my view page is:
<div style="float:left;width:100%">
<center><h1> Branch Report </h1></center>
</div>
When I try to generate pdf then it will display blank.
where are you writing HTML to PDF I haven't work on tcpdf but as my experience with mpdf as far as i know
there should a function like
$pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
please refer tcpdf documentation for writeHTML() or writeHTMLCell() functions
http://www.tcpdf.org/doc/code/classTCPDF.html
or refer examples
http://www.tcpdf.org/examples.php
you have to assign codeigniter view to variable for that give last attribute as true
$html= $this->load->view("admin/list_branch_report",array('br_result'=>$result1,'cash_result'=>$result2,'b_code'=>$branch_code),true);
and then assign this to
$pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
I have written ob_start(); before the load view page.Then i have written
$html = $this->load->view("admin/list_branch_report",array('br_result'=>$result1,'cash_result'=>$result2,'b_code'=>$branch_code),true);
$pdf->writeHTML($html, true, false, true, false, '');
ob_clean();
$pdf->Output();
this code.
So it works perfect.
Thanks to all.
use mpdf instead of tpdf and send html that you want to convert in pdf.

TCPDF - weird issue with footers

Check out the source code here:
http://www.savvissl.com/demo1/showcode.php
check out the script here
http://www.savvissl.com/demo1/testPDF.php
Here is the issue... the footer prints fine on every page except for the last page. The last page never has a footer. If there is only one page in the document the footer will not print at all.
OK I couldn't figure it out, but i was able to copy a co-workers example that worked. If anyone wants the source code here it is:
<?php
require_once('tcpdf/config/lang/eng.php');
require_once('tcpdf/tcpdf.php');
define('PDF_FOOTER_TEXT','800 Vinial St. Pittsburgh, PA 15212 | phone: 412.321.7006 | fax: 412.321.7005 | www.savvior.com');
$PDF_LINE_COLOR=array(255,255,0);
define('PDF_FOOTER_TEXT_COLOR',170);
class MYPDF extends TCPDF
{
//Page header
public function Header()
{
global $PDF_LINE_COLOR;
$image_file = K_PATH_IMAGES.'image.jpg';
$this->Image($image_file, 160, 0, 30, '', 'JPG', '', 'T', false, 300, '', false, false, 0, false, false, false);
$this->SetFont('helvetica', 'B', 20);
$this->Cell(0, 15, '', 0, false, 'C', 0, '', 0, false, 'M', 'M');
$this->line(10,27,200,27,array('width' => 0.5, 'cap' => 'butt', 'join' => 'miter', 'solid' => 4, 'color' => $PDF_LINE_COLOR));
}
public function Footer()
{
global $PDF_LINE_COLOR;
$cur_y = $this->GetY();
$ormargins = $this->getOriginalMargins();
$this->SetTextColor(PDF_FOOTER_TEXT_COLOR, PDF_FOOTER_TEXT_COLOR, PDF_FOOTER_TEXT_COLOR);
$this->SetY($cur_y);
$this->line(10,400,200,400,array('width' => 0.5, 'cap' => 'butt', 'join' => 'miter', 'solid' => 4, 'color' => $PDF_LINE_COLOR));
$this->Cell(0,11,"Page ". $this->getAliasNumPage().'/'.$this->getAliasNbPages(),'T',0,'L');
$this->Cell(0,11,PDF_FOOTER_TEXT,'T',0,'R');
}
}
ob_start();
?><h1>Content Is Needed For This Page...</h1>
...
<?
$html=ob_get_clean();
function makePDFFile($fileName,$html)
{
$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Savvior Project Manager');
$pdf->SetTitle('Auto Generated PDF');
$pdf->SetSubject('Auto Generated PDF');
$pdf->SetKeywords('TCPDF');
// 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));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
//set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP+5, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
//set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
//set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
//set some language-dependent strings
$pdf->setLanguageArray($l);
// set font
$pdf->SetFont('helvetica', '', 12);
// add a page
$pdf->AddPage();
$pdf->writeHTML($html, true, false, true, false, '');
$doc=$pdf->Output(dirname(__FILE__)."/cache/{$fileName}", 'F');
return $fileName;
}
$file=makePDFFile('poo-poo-platter.pdf',$html);
header("location: cache/{$file}");
?>
Comparing this new code to my old reveals no insight into why this works... in fact the example in the TCPDF examples folder exhibits the same issue, however if you run it from their website the footer is displayed correctly. Well anyway hope this helps someone
I know nothing about TCPDF save what I just learned going through their docs.
It looks like Footer() is only called for you when you explicitly call AddPage(), at which point it is added to the PREVIOUS PAGE. The rest of the time I believe you have to call it yourself.
There's also this whole StartPage()/EndPage() thing that sounds like an alternative to AddPage().
You might want to: "start page, header, draw text, footer, end page" instead. It looks like Write() calls AddPage() for you, which is why the headers and footers on all-but-the-last-page are present.
Bottom Line: Just call Footer() after you call Write() in this example. Real world examples will almost certainly be a bit more complex.

Categories