I'm using the tcpdf library to generate the pdf document. I'm using smarty template engine to hold the data. Below is the script to put in the header data:
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, 'PQR',
'XYZ');
I want to put HTML table content of smarty template in place of XYZ, the table content is going to be dynamic(meaning the data in table may vary for each PDF document).
As #vinzcoco says, you must extend TCPDF to achieve what you want. Here is a simple improvement that I think it could be useful for you:
class MyTCPDF extends TCPDF {
var $htmlHeader;
public function setHtmlHeader($htmlHeader) {
$this->htmlHeader = $htmlHeader;
}
public function Header() {
$this->writeHTMLCell(
$w = 0, $h = 0, $x = '', $y = '',
$this->htmlHeader, $border = 0, $ln = 1, $fill = 0,
$reseth = true, $align = 'top', $autopadding = true);
}
}
Now, once you've got your MyTCPDF object available, you just need to do this to set the HTML header content:
$mytcpdfObject->setHtmlHeader('<table>...</table>');
and the HTML content won't be hardcoded into the Header() method (more flexible for you).
I used the following method to set header
$PDF_HEADER_LOGO = "logo.png";//any image file. check correct path.
$PDF_HEADER_LOGO_WIDTH = "20";
$PDF_HEADER_TITLE = "This is my Title";
$PDF_HEADER_STRING = "Tel 1234567896 Fax 987654321\n"
. "E abc#gmail.com\n"
. "www.abc.com";
$pdf->SetHeaderData($PDF_HEADER_LOGO, $PDF_HEADER_LOGO_WIDTH, $PDF_HEADER_TITLE, $PDF_HEADER_STRING);
This is work for me.
You must instance your PDF class and extend the TCPDF class.
After your PDF class should look like this:
class MyTCPDF extends TCPDF{
public function Header(){
$html = '<table>...</table>';
$this->writeHTMLCell($w = 0, $h = 0, $x = '', $y = '', $html, $border = 0, $ln = 1, $fill = 0, $reseth = true, $align = 'top', $autopadding = true);
}
}
You must adapt this to your own project.
Related
I am trying to get a document generated on a php site. It is all working well but the last thing is to add a header to the top of every page after the title page. I have tried so many things and the closest I can get to what I want is the following (stripped down) code.
ob_start();
$mpdf = new Mpdf();
$mpdf->SetDisplayMode('fullpage');
$mpdf->bleedMargin = 0;
$mdpf->crossMarkMargin = 0;
$mpdf->cropMarkMargin = 0;
$mpdf->nonPrintMargin = 0;
// Home page and headers...
$html_header = 'Some Code here';
$mpdf->DefHTMLHeaderByName('PgHeader', $html_header);
$mpdf->AddPage();
$mpdf->Image('cover.jpg', 0, 0, 210, 297, 'jpg', '', true, false);
// Get the content of any pages we have
if($pdf_pages) {
foreach($pdf_pages as $key=>$pg) {
$mpdf->AddPageByArray(array(
'mgt' => '40',
'odd-header-name' => 'PgHeader'
));
$html .= 'the content from the loop';
// Write some HTML code:
$custom_sheet = file_get_contents('/custom.css');
$mpdf->WriteHTML($custom_sheet, 1);
$mpdf->WriteHTML($html, 2);
}
}
// Output a PDF file directly to the browser
$mpdf->Output('Name.pdf', 'I');
ob_end_flush();
I have tried changing the odd-header-name to html_PgHeader based on the documentation but in either case, I get the margin, all the content but the header never shows up. Why? Why is it not being assigned so I can call it in the AddPageByArray?
According to the documentation you need to prefix header/footer names with 'html_'
Try changing;
'odd-header-name' => 'PgHeader',
to;
'odd-header-name' => 'html_PgHeader',
reference here
To show header, you need to add odd-header-value option to AddPageByArray method with value 1.
ob_start();
$mpdf = new Mpdf();
$mpdf->SetDisplayMode('fullpage');
$mpdf->bleedMargin = 0;
$mdpf->crossMarkMargin = 0;
$mpdf->cropMarkMargin = 0;
$mpdf->nonPrintMargin = 0;
// Home page and headers...
$html_header = 'Some Code here';
$mpdf->DefHTMLHeaderByName('PgHeader', $html_header);
$mpdf->AddPage();
$mpdf->Image('cover.jpg', 0, 0, 210, 297, 'jpg', '', true, false);
$pdf_pages = array('key' => 'val');
// Get the content of any pages we have
if($pdf_pages) {
foreach($pdf_pages as $key=>$pg) {
$mpdf->AddPageByArray(array(
'mgt' => '40',
'odd-header-name' => 'PgHeader',
'odd-header-value' => 1,
));
$html .= 'the content from the loop';
// Write some HTML code:
$custom_sheet = file_get_contents('/custom.css');
$mpdf->WriteHTML($custom_sheet, 1);
$mpdf->WriteHTML($html, 2);
}
}
// Output a PDF file directly to the browser
$mpdf->Output('Name.pdf', 'I');
ob_end_flush();
Pt.II
If this, don't help, then try this scenario:
Open console and go to site's root path.
Create index.php file
Run composer require mpdf/mpdf (install composer, if you don't have it).
Paste this code to the index.php
<?php
require_once __DIR__ . '/vendor/autoload.php';
ob_start();
$mpdf = new \Mpdf\Mpdf();
/** same code from previous example here, except Mpdf init **/
Try something like this
#page {
header: header_name;
footer: footer_name;
}
It might help you.
Url: https://mpdf.github.io/headers-footers/headers-footers.html
I am using HTML2pDf convertor to generate pdf my code looks like this
require_once(app_path().'/libs/html2pdf/html2pdf.class.php') ;
$html2pdf = new HTML2PDF('P','A4','en',true,'UTF-8',array(0, 0, 0, 0));
$html2pdf->pdf->SetDisplayMode('fullpage');
$html2pdf->WriteHTML($html22);
$html2pdf->Output($username.'_questionnaire.pdf');
I am getting following error
TCPDF ERROR: Some data has already been output, can't send PDF file
The function where I have this script looks like this
public function postExporttopdf(){
$validator = Validator::make(Input::all(),array('delid'=>'required'));
$event = Session::get('tempevenname');
if($validator->passes()){
$uid1 = Input::get('delid');
$username = User::find(Input::get('delid'))->name;
$page1data = Question::where('event','=',$event)->where('page','=',1)->orderBy('order')->with('choices')
->with(array('answers'=>function($query){
$query->where('user_id','=',Input::get('delid'));
}))->get();
$page2data = Question::where('event','=',$event)->where('page','=',2)->orderBy('order')->with('choices')
->with(array('answers'=>function($query){
$query->where('user_id','=',Input::get('delid'));
}))->get();
$page3data = Question::where('event','=',$event)->where('page','=',3)->orderBy('order')->with('choices')
->with(array('answers'=>function($query){
$query->where('user_id','=',Input::get('delid'));
}))->get();
$page4data = Question::where('event','=',$event)->where('page','=',4)->orderBy('order')->with('choices')
->with(array('answers'=>function($query){
$query->where('user_id','=',Input::get('delid'));
}))->get();
$html22 = View::make('reviewsendpdf')->with(array(
'page1data'=>$page1data,
'page2data'=>$page2data,
'page3data'=>$page3data,
'page4data'=>$page4data
));
require_once(app_path().'/libs/html2pdf/html2pdf.class.php') ;
$html2pdf = new HTML2PDF('P','A4','en',true,'UTF-8',array(0, 0, 0, 0));
$html2pdf->pdf->SetDisplayMode('fullpage');
$html2pdf->WriteHTML($html22);
$html2pdf->Output($username.'_questionnaire.pdf');
} else {
return Redirect::to('admin/exporttopdf')->with('message','Select a user and event');
}
}
Probably something has already been written to the output buffer prior to streaming the pdf content.
Try to use ob_end_clean() to clean the output buffer just before the method invocation:
require_once(app_path().'/libs/html2pdf/html2pdf.class.php') ;
$html2pdf = new HTML2PDF('P','A4','en',true,'UTF-8',array(0, 0, 0, 0));
$html2pdf->pdf->SetDisplayMode('fullpage');
$html2pdf->WriteHTML($html22);
ob_end_clean();
$html2pdf->Output($username.'_questionnaire.pdf');
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.
I've created a simple wrapper class for a TCPDF example I got off the web.
My aim is to call the methods in the class in succession, then output a pdf file to a directory in my project.
The code worked fine when I had a version of it in one blob and calling it from a page. After putting it into a class it seems to hang/do nothing around the call to Output(). I cannot step into it when debugging in netbeans, and no error appears to be thrown.
In case it was a folder permissions issue I've run chmod on the output directory in question.
Here is the class:
<?php
define('IMAGE_DIR', '/home/user/NetBeansProjects/PDF_Quote/img/');
require_once('lib/tcpdf/tcpdf.php');
class PDF_Test extends TCPDF {
function __construct() {
parent::__construct(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
}
public function set_document_info($creator = '', $author = '', $title = '', $subject = '', $keywords = '')
{
$creator = PDF_CREATOR;
$author = 'Author';
$title = 'Title Example';
$subject = 'Subject Example';
$keywords = 'TCPDF, PDF, example, test, guide';
// set document information
$this->SetCreator($creator);
$this->SetAuthor($author);
$this->SetTitle($title);
$this->SetSubject($subject);
$this->SetKeywords($keywords);
}
public function header($logo_img = '', $title_text = '', $addit_text = '')
{
$logo_img = IMAGE_DIR . 'headerimg.png';
$title_text = 'the title';
$addit_text = 'additional text';
$this->SetHeaderData($logo_img, PDF_HEADER_LOGO_WIDTH, $title_text.' 001', $addit_text, array(0,64,255), array(0,64,128));
$this->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
}
public function footer($logo_img = '', $text = '')
{
$this->setFooterData(array(0,64,0), array(0,64,128));
$this->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
}
public function set_default_monospaced_font($font = '')
{
if (strlen($font) === 0) { $font = 'courier'; }
$this->SetDefaultMonospacedFont($font);
}
public function set_margins($margin_left = '', $margin_top = '', $margin_right = '', $margin_header = '', $margin_footer = '')
{
$margin_left = PDF_MARGIN_LEFT; $margin_top = PDF_MARGIN_TOP; $margin_right = PDF_MARGIN_RIGHT;
$margin_header = PDF_MARGIN_HEADER; $margin_foot = PDF_MARGIN_FOOTER;
$this->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$this->SetHeaderMargin(PDF_MARGIN_HEADER);
$this->SetFooterMargin(PDF_MARGIN_FOOTER);
}
public function set_auto_page_break($set = True, $margin = '')
{
$set = True;
$margin = PDF_MARGIN_BOTTOM;
$this->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
}
public function set_image_scale($img_scale_ratio = '')
{
$img_scale_ratio = PDF_IMAGE_SCALE_RATIO;
$this->setImageScale(PDF_IMAGE_SCALE_RATIO);
}
public function set_language_array()
{
if (#file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$this->setLanguageArray($l);
}
}
public function set_font_subsetting($set = True)
{
$set = True;
$this->setFontSubsetting($set);
}
public function set_font($family = '', $style = '', $size = '', $fontfile = '', $subset = '', $out = True)
{
$family = 'dejavusans'; $size = '14';
$this->SetFont($family, $style, $size, '', $out);
}
public function add_page()
{
$this->AddPage();
}
// Can be html or just plain text
public function add_text_blob($html = '')
{
$html = '<h1>This is some stuff</h1><p style="background-color: green;">This is some content adhjdjasjd</p>';
$this->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
}
public function output($path, $file_name)
{
$path = dirname(__FILE__) . '/pdfcache/'; //'/home/user/NetBeansProjects/PDF_Quote/pdfcache/';
$file_name = 'file_' . date('Y_m_d_H_i_s') . '.pdf';
try
{
$fp = $path . 'example1.pdf'; //. $file_name; //'/home/user/NetBeansProjects/PDF_Quote/pdfcache/example_001.pdf';
$this->Output($fp, 'F');
}
catch (exception $ex)
{
return $ex;
}
return $path . $file_name;
}
}
?>
Here is the code that calls the class in another php file:
require_once('PDF_Test.php');
$pdf = new PDF_Test();
$pdf->set_document_info();
$pdf->header();
$pdf->footer();
$pdf->set_default_monospaced_font();
$pdf->set_margins();
$pdf->set_auto_page_break();
$pdf->set_image_scale();
$pdf->set_language_array();
$pdf->set_font_subsetting();
$pdf->set_font();
$pdf->add_page();
$pdf->add_text_blob();
$pdf->output();
I haven't managed to find any similar issues in my googling, but I'm new to PHP, so I'm not sure if I'm overlooking anything glaringly obvious either.
I would recommend using the Output method in a way that it returns the PDF as binary string, so you can do whatever you want with it. This would be $pdfdoc = $pdf->Output('', 'S').
This way, you can still put the file to a path of your choice, but also dump it directly to the client, or attach it to an e-mail … and you can do a better error handling, because you have control over what TCPDF produces.
By the way, when you override a method in PHP, and you want to call the parent method, then you must use parent::METHOD(). Because you're actually overriding the header, footer, and output methods of TCPDF with yours (even if yours are lowercased).
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.