I am trying to generate PDFs using TCPDF library. So far, I am able to generate the PDF files using PHP code. Although it does not render external CSS and result becomes useless as without CSS the document is not readable.
Following is my code in the controller:
public function generate_pdf() {
$this->load->model('rosters', 'roster');
$data = array();
$data['start_date'] = isset($_POST['fortnightStartDate']) ?
date("Y-m-d", strtotime(getFortnightStartDate($_POST['fortnightStartDate']))) :
getFortnightStartDate();
$cid = $_POST['cid'];
$wno = $_POST['wno'];
$data['no']=$wno;
$startDate = strtotime($data['start_date']);
$data['schedule'] = $this->roster->getShifts($cid, $data);
$data['startDate'] = $startDate;
$listing = $this->load->view('roster/roster_pdf', $data, true);
/**
* Creates an example PDF TEST document using TCPDF
* #package com.tecnick.tcpdf
* #abstract TCPDF - Example: XHTML + CSS
* #author Nicola Asuni
* #since 2010-05-25
*/
// Include the main TCPDF library (search for installation path).
require_once(APPPATH.'libraries/tcpdf/tcpdf.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 061');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 061', 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, 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 (optional)
if (#file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// set font
$pdf->SetFont('helvetica', '', 10);
// add a page
$pdf->AddPage();
$pdf->writeHTML($listing, true, false, true, false, '');
//Close and output PDF document
$pdf->Output('TEST.pdf', 'F');
}
I am passing the $listing variable which holds the data that needs to be included in the PDF. The data is printing fine but without CSS. If I try to include the external CSS it pops up the error.
Code to include external css
$listing. = '<style>'.file_get_contents(base_url("styles/style.css")).'</style>';
I try to include this line of code below the $listing variable but it generates following error:
A PHP Error was encountered
Severity: Warning
Message: array_merge(): Argument #2 is not an array
Filename: tcpdf/tcpdf.php
Line Number: 16375
Is there any other way I can load the external CSS ??
Any help will be highly appreciated.
After researching here and there, I come to know that TCPDF library has few limitations including CSS limitation and does not support many CSS properties. Then, I looked into dompdf library and found it useful. Surprisingly, it solved all my problem with almost similar code and also it is way easy to use than TCPDF. Following is my piece of code i wrote to solve my problem (The code is similar until the $listing variable then i simply change the library code.)
$listing .= '<style>'.file_get_contents(base_url("styles/style.css")).'</style>';
require_once(APPPATH.'libraries/dompdf/dompdf_config.inc.php');
$dompdf = new DOMPDF();
$dompdf->load_html($listing);
$dompdf->set_paper('a4', 'landscape');
$dompdf->render();
file_put_contents('my_pdf_test.pdf', $dompdf->output());
//$dompdf->stream("dompdf_out.pdf", array("Attachment" => true));
exit(0);
Related
I'm using TCPDF in combination with FPDI. All working good except the Footer (want to add Page Numbers there).
My Code:
// Extend the TCPDF class to create custom Header and Footer
class MYPDF extends FPDI {
// Page footer
public function Footer() {
// Position at 15 mm from bottom
$this->SetY(-15);
// Set font
$this->SetFont('helvetica', 'I', 8);
// Page number
$this->Cell(0, 5, 'Page '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
}
}
// add external PDF with FPDI
$pdf = new FPDI(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', true);
// remove default header/footer
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
//set margins
$pdf->SetMargins(1, 4, 1, 1, true);
//set auto page breaks
$pdf->SetAutoPageBreak(TRUE, 3);
... this footer hook is working fine if I'm not suing FPDI. What do I miss here?
You are initiating an instance of FPDI and not of MYPDF. For sure the Footer() method will not be invoked that way.
IIRC you also have to leave setPrintFooter() to true.
I am trying to add a cell to an existing PDF, but unfortunately the document is a scan, which interprets it as one layer - a photo - I think so.
When adding a cell to such a file, I only have borderless text and no cell fill color on the visible layer of the document.
Am I in any way controlling the layers of the file in such a way that the cell being added is always the top layer and is fully visible?
Method to get existing PDF:
protected function getOldPDF()
{
$pdf = new Fpdi();
$pdf->SetCreator('Test');
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetMargins(0, 0);
$numPages = $pdf->setSourceFile($this->filePath);
for($pageNum = 1; $pageNum <= $numPages; $pageNum++) {
$tpl = $pdf->importPage($pageNum);
$pdf->AddPage();
$pdf->useTemplate($tpl);
}
return $pdf;
}
I add cells with TCPDF::MultiCell()
I am using TCPDF to create PDF documents. I want to use small caps in my header, but I failed.
Here is my header code:
Version 1
<?php
require_once('tcpdf/tcpdf.php');
class MYPDF extends TCPDF {
//Page header
public function Header() {
// Logo
$image_file ='image/pacra.jpg';
$this->Image($image_file, 100, 05, 20);
// Set font
$this->SetFont('times', 15);
// Title
$this->Cell(0,57, 'Trying To Use Small Caps', 0, false, 'C', 0, '', 0, false);
$this->Line(10,32,200,32);
Version 2
<?php
require_once('tcpdf/tcpdf.php');
class MYPDF extends TCPDF {
//Page header
public function Header() {
// Logo
$image_file ='image/pacra.jpg';
$this->Image($image_file, 100, 05, 20);
// Set font
$this->SetFont('times', 15);
$str = 'Trying To Use Small Caps';
$str = preg_replace("/([a-z]+)/e","strtoupper('<small>\\1</small>')",$str);
$str= $this->writeHTML($str);
This code is working but I want to set XY axis of text.
Yahooo....!!!
I Solved my issue.
<?php
require_once('tcpdf/tcpdf.php');
class MYPDF extends TCPDF {
//Page header
public function Header() {
// Logo
$image_file ='image/pacra.jpg';
$this->Image($image_file, 100, 05, 20);
// Set font
$this->SetFont('times','B');
$this->SetFontSize(16);
//$this->SetTextColor(0,63,127);
$this->SetXY(52,25);
$str = 'Tying to Use Small Caps';
$str = preg_replace("/([a-z]+)/e","strtoupper('<small>\\1</small>')",$str);
$str= $this->writeHTML($str);
To change font you need to add font style.
Follow this for example.
// 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 margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
I have create class to make page by using TCPDF.
I need to convert HTML to pdf, so I using writeHTML and AcceptPageBreak().
The $html is Dynamically changed, could be very long.
class MY_TCPDF extends TCPDF{
public function makePage($html){
$head_image="header.jpg";
$this->SetMargins(PDF_MARGIN_LEFT, 70, PDF_MARGIN_RIGHT);
$this->setPrintHeader(false);
$this->AddPage();
// get the current page break margin
$bMargin = $this->getBreakMargin();
// get current auto-page-break mode
$auto_page_break = $this->getAutoPageBreak();
// disable auto-page-break
$this->SetAutoPageBreak(false, 0);
// set bacground image
$img_file = $head_image;
$this->Image($img_file, 0, 0, 210, 68, '', '', '', false, 300, '', false, false, 0);
// restore auto-page-break status
//$this->SetAutoPageBreak($auto_page_break, PDF_MARGIN_BOTTOM);
// set the starting point for the page content
$this->setPageMark();
$this->writeHTML($html, true, false, true, false, '');
$this->lastPage();
ob_start();
//Close and output PDF document
$this->Output('my.pdf', 'I');
ob_end_flush();
}
public function AcceptPageBreak() {
$this->SetMargins(PDF_MARGIN_LEFT, 10, PDF_MARGIN_RIGHT);
$this->AddPage();
return false;
}
}
The problem is I genenrate PDF, but alway has a extra blank page in the end of the PDF.
I tried use $this->delete($this->getPage()) ,but it only remove last page which has content and the extra blank page remain. this seems writeHTML will create a page break after it.
how to prevent this extra blank page?
Try this deletePage function
$lastPage = $this->getPage();
$this->deletePage($lastPage);
Instead Delete use deletePage
I had the same Problem:
I fixed it with:
class TCPDFextended extends \TCPDF {
public function Output($name = 'doc.pdf', $dest = 'I')
{
$this->tcpdflink = false;
return parent::Output($name, $dest);
}
}
You should check your $html variable.
1) If it could contains any <html />, <head />, <title />, <body /> tag then please remove them and just take html contents after and before <body />.
2) You should avoid any css, js link file within $html content.
3) Finally you should use $html=utf8_encode($html); just before $this->writeHTML($html, true, false, true, false, '');.
4) You may need to adjust your MARGIN_LEFT, MARGIN_TOP, MARGIN_RIGHT and MARGIN_BOTTOM to solve such problems. Please check $this->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); and $this->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);.
Hopefully it can solve your problem.
My answer is similar to #kanti. I think we can set the default to false even before the Output generation.
Background. The extra page we see is basically
"If true print TCPDF meta link".
so by default the TCPDF::$tcpdflink = true , is set true.
All we need is
class My_PDF extends TCPDF {
public function changeTheDefault($tcpdflink) {
$this->tcpdflink = $tcpdflink;
}
}
call your public function later when you need it. ...
$get_pdf = new My_PDF (your_parameters);
$get_pdf->changeTheDefault(false); # changes the default to false
Good Luck.
Check also the height of your enclosing div.
It should not be 100%.
Try to remove any height property from the CSS style of the enclosing div ( I mean the div which encloses all the content).
The problem is the 4th parameter (unicode = true) in your create_pdf.php file. This parameter is passed into tcpdf.php on line 1838
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'ISO-8859-1', false);
change it to false.
AddPage() in tcpdf automatically calls Header and Footer. How do I eliminate/override this?
Use the SetPrintHeader(false) and SetPrintFooter(false) methods before calling AddPage(). Like this:
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, 'LETTER', true, 'UTF-8', false);
$pdf->SetPrintHeader(false);
$pdf->SetPrintFooter(false);
$pdf->AddPage();
A nice easy way to have control over when to show the header - or bits of the header - is by extending the TCPDF class and creating your own header function like so:
class YourPDF extends TCPDF {
public function Header() {
if (count($this->pages) === 1) { // Do this only on the first page
$html .= '<p>Your header here</p>';
}
$this->writeHTML($html, true, false, false, false, '');
}
}
Naturally you can use this to return no content as well, if you'd prefer to have no header at all.
Here is an alternative way you can remove the Header and Footer:
// Remove the default header and footer
class PDF extends TCPDF {
public function Header() {
// No Header
}
public function Footer() {
// No Footer
}
}
$pdf = new PDF();
How do I eliminate/override this?
Also, Example 3 in the TCPDF docs shows how to override the header and footer with your own class.
Example:
- First page, no footer
- Second page, has footer, start with page no 1
Structure:
// First page
$pdf->startPageGroup();
$pdf->setPrintFooter(false);
$pdf->addPage();
// ... add page content here
$pdf->endPage();
// Second page
$pdf->startPageGroup();
$pdf->setPrintFooter(true);
$pdf->addPage();
// ... add page content here
$pdf->endPage();
// set default header data
$pdf->SetHeaderData('', PDF_HEADER_LOGO_WIDTH, 'marks', '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));
With the help of above functions you can change header and footer.