TCPDF returning weird characters - php

maybe you can help me. When I try to show a pdf I created I got some weird symbols like this
u\>�'���O���r>c!%�#�R�`YPd+��vv����1��E�'^k-�WD�*+��W^��wy��V Z��dUdJ�B���C�ڳtK����j:c���5����50���D3lgH#�}%���D+������ix����,��-�'\�� �_st^&0�Y���������v�*Ӗ,W����u!H��sNN��0cӝ��`xEk��d��^� �8K9�BL����9�̋"6/�E�|�̛�-�7�P��B�#�T�F���4`����
What I do is transform a html file with this code
$html = $this->load->view('ReporteIngresoView', $data, TRUE);
$pdf = new Pdf('P', 'mm', 'A4', TRUE, 'UTF-8', FALSE);
$pdf->SetTitle('Reporte ingreso');
$pdf->SetHeaderMargin(30);
$pdf->SetTopMargin(40);
$pdf->setFooterMargin(20);
$pdf->SetAutoPageBreak(TRUE);
$pdf->SetAuthor('Pontificia Universidad Católica del Ecuador');
$pdf->SetDisplayMode('real', 'default');
$pdf->AddPage();
$pdf->writeHTML($html, TRUE, 0, TRUE, 0);
$pdf->Output('My-File-Name.pdf', 'I');
On the other side I recieve it like this
Ext.Ajax.request
(
{
method: 'post',
url: '../servidor/archivo/ingreso/getreporte',
success: function(response){
Ext.getCmp('winReporteRegistro').update( response.responseText );
}
}
);
I am using php (server), html (create the page), extjs (interface), ajax (request) and TCPDF to create the pdf.
Any ideas?
Thanks in advance,

You need to convert the response to a Blob (link)
After creating the blob, you can create an URL object (link)
This is how I create a server side generated pdf and display it on the front end.
Adding code snippet:
var blob = new Blob(response.responseText, {type: 'application/pdf'});
var objectURL = URL.createObjectURL(blob);

Returning the location of the file and open that in another web page was the answer, the code is:
Server:
$html = $this->load->view('ReporteCajaView', $data, TRUE);
$pdf = new Pdf('P', 'mm', 'A4', TRUE, 'UTF-8', FALSE);
$pdf->SetTitle('Reporte item');
$pdf->SetHeaderMargin(30);
$pdf->SetTopMargin(20);
$pdf->setFooterMargin(20);
$pdf->SetMargins(25, 20, 20, true);
$pdf->SetAutoPageBreak(TRUE);
$pdf->SetAuthor('Universidad Católica');
$pdf->SetDisplayMode('real', 'default');
$pdf->setPrintHeader(FALSE);
$pdf->setPrintFooter(FALSE);
$pdf->AddPage();
$id = uniqid();
$pdf->writeHTML($html, TRUE, 0, TRUE, 0);
$pathservidor = 'c:/wamp64/www/Archivo/pdf/';
$pdf->Output($pathservidor . 'Reporte de caja' . '.pdf', 'F');
echo 'c:/wamp64/www/Archivo/pdf/'.'Reporte de caja'.'.pdf';
Client:
Ext.Ajax.request
(
{
method: 'post',
url: '../servidor/archivo/item/getreporte',
success: function(response){
window.open(response.responseText);
}
}
);
Thanks!

Sorry for the late answer but I broke my teeth on this yesterday and this morning I had an illumination :-)
You need to support the mime-type so simply add this in your .htaccess:
AddType application/pdf .pdf

Related

Codeigniter TCPDF - Load Multiple PDF

Current Issue:
When i click on "Print PDF" it only show "1" PDF.
What I Have Done:
I have set array on the URI , which means that it able to loop 2 times
using foreach , but problem now is that the PDF is currently showing
"1" time only
What I Need :
Allow TCPDF generate 2 pdf
Create this thread is whated to know the idea, i will try to solve it myself
Code
<?php
foreach($invoice as $row){
$body='HTML
XXXXXXX
Table';
$pdf = new Pdf('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetTitle('Invoice');
$pdf->SetHeaderMargin(10);
$pdf->SetTopMargin(10);
$pdf->setFooterMargin(10);
$pdf->SetAutoPageBreak(true);
$pdf->SetAuthor('Invoice');
$pdf->SetDisplayMode('real', 'default');
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->AddPage();
$pdf->writeHTML($body, true, false, true, false, '');
$pdf->lastPage();
//$pdf->Write(5, $tnc);
$pdf->Output('InvoceOutput'.'\.pdf', 'I' );
}
?>
You're creating and outputting your PDF inside your for loop, so 2 separate PDFs that are 1 page long are being generated. The 2nd PDF is likely overwriting the 1st PDF, leaving you with a single PDF 1 page long.
Configuring and outputting your PDF outside of the for loop should fix your issue:
<?php
$pdf = new Pdf('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetTitle('Invoice');
$pdf->SetHeaderMargin(10);
$pdf->SetTopMargin(10);
$pdf->setFooterMargin(10);
$pdf->SetAutoPageBreak(true);
$pdf->SetAuthor('Invoice');
$pdf->SetDisplayMode('real', 'default');
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
foreach($invoice as $row){
$body='HTML
XXXXXXX
Table';
$pdf->AddPage();
$pdf->writeHTML($body, true, false, true, false, '');
$pdf->lastPage();
//$pdf->Write(5, $tnc);
}
$pdf->Output('InvoceOutput'.'\.pdf', 'I' );
?>

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

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.

Generate PDF using TCPDF on ajax call

I'm using TCPDF class to generate PDF. First I send some data in json format (jquery) then I would like to generate PDF with these data.
Could you tell me if I am right. I should generate pdf, save it on the server and then if ajax call returns success, redirect the user to this pdf. Is a good way?
I have:
$.ajax({
url: '/pdf/fiele_to_generate_pdf.php',
type: 'POST',
contentType: "application/json; charset=utf-8",
data: $.toJSON(jsonObj),
processData: false,
dataType: 'html',
async: false,
success: function(html) {
window.location.href = '/pdf/example.pdf';
}
});
Thanks for any advice.
Edit: So I have sent a request to make the pdf via Ajax to the server, then the pdf file was generated and saved on the server. Then I have used window.location.href to redirect the user to this pdf. Everything works but I would like to avoid saving file on the server. Any ideas?
Ok this script will save the file and also display in the browser
the trick is in using the output method with the 'F' or 'I':
$pdf->Output("your path", 'F'); //save pdf
$pdf->Output('file.pdf', 'I'); // show pdf
CODE
<?php
class PDF extends TCPDF {
public function Header (){
$this->SetFont('dejavusans', '', 14);
$title = utf8_encode('title');
$subtitle = utf8_encode('sub title');
$this->SetHeaderMargin(40);
$this->Line(15,23,405,23);
}
public function Footer() {
$this->SetFont('dejavusans', '', 8);
$this-> Cell (0, 5, 'Pag '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'R', 0, '', 0, false, 'T', 'M');
}
public static function makeHTML ($json){
$html = '<table border="0.5" cellspacing="0" cellpadding="4">
<tr>
<th bgcolor="#DAB926" style="width:3%; text-align:left"><strong>you th</strong></th>
</tr>';
for ($i=0; $i<count($json); $i++)
{
$a= $i+1;
$html .= '<tr>
<td style="width:15%; text-align:left">'.$json[$i]->Name.'</td>
</tr>';
}
$html .= '</table>';
return $html;
}
}
function printReport ($json )
{
set_time_limit(0);
$pdf = new PDF("L", PDF_UNIT, "A3",true, 'UTF-8', false);
$pdf->SetMargins (15, 27, 15, true);
$pdf->SetFont('dejavusans', '', 8);
$pdf->SetAutoPageBreak(TRUE,50);
$pdf->AddPage();
//create html
$html = $pdf->makeHTML($json);
$pdf->writeHTML($html, false, false, false, false, '');
if (!file_exists("your path"))
mkdir("your path");
$pdf->Output("your path", 'F'); //save pdf
$pdf->Output('file.pdf', 'I'); // show pdf
return true;
}
$json = json_decode("your json");
printReport($json);
?>

PHP: converting html file to pdf

I have an html file named welcomemailtemplate.html and I need to convert that file to a PDF.
I first read this file using the following method provided by Yii framework:
$filename = Yii::app()->basePath.'\views\email\welcomemailtemplate.html';
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
$name = $model->name;
fclose($handle);
$message = str_replace ( "[username]", $name, $contents );
Then, to generate the PDF file, the following parameters are set:
Yii::import('application.vendors.*');
require_once('tcpdf/tcpdf.php');
require_once('tcpdf/config/lang/eng.php');
$pdf = new TCPDF();
$pdf->SetCreator("Torget");
$pdf->SetAuthor('test name');
$pdf->SetTitle('Savani Test');
$pdf->SetSubject(' Torget Order Confirmation');
$pdf->SetKeywords(' Torget, Order, Confirmation');
//$pdf->SetHeaderData('', 0, PDF_HEADER_TITLE, '');
$pdf->SetHeaderData('', 0, "Torget Order", '');
$pdf->setHeaderFont(Array('helvetica', '', 8));
$pdf->setFooterFont(Array('helvetica', '', 6));
$pdf->SetMargins(15, 18, 15);
$pdf->SetHeaderMargin(5);
$pdf->SetFooterMargin(10);
$pdf->SetAutoPageBreak(TRUE, 0);
$pdf->SetFont('dejavusans', '', 7);
$pdf->AddPage();
If I pass the content as follows, it creates the PDF:
$pdf->writeHTML("<span>Hello World!</span>", true, false, true, false, '');
But if I pass the read html file content for pdf creating using following method it gives following error:
$pdf->writeHTML($message, true, false, true, false, '');
$pdf->LastPage();
Error message:
Undefined index: thead
Try to validate the file using the w3c validator http://validator.w3.org/.
I've worked with tcpdf before but i gave it up because it didn't seem reliable. You can also try wkhtmltopdf binary (only if your hosting allows you to use proc_open/proc_close). Seems a little more stable to me. It also has a PHP class to help you use it.
CutyCapt seems to be a very good option for you. Its very easy to integrate also.

Categories