PHP: converting html file to pdf - php

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.

Related

How do disable TCPDF version shown in the browser after PDF generation

When i generate the final PDF the version is being displayed.
Is there any way to hide this information ?
I looked into the package documentation but i could not find anything.
This is information I do not want to share.
I checked if there are any functions but I can't find any.
Here is my code that i use to generate the pdf
$pdf = new \TCPDF('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdfParams = $this->handlePageParamsByCoverSize($coverSize);
$fontSize = $this->calculateFontSizeByCoverSize($coverSize);
$scissorsIconPath = $this->fileLocator->locate('scissors.png');
$pdf->SetFont(
'helvetica',
'',
$fontSize
);
$pdf->AddPage('L', $pdfParams['format'], true, true);
$pdf->Image(
$coverPath,
$pdfParams['cover']['x'],
$pdfParams['cover']['y'],
$pdfParams['cover']['w'],
$pdfParams['cover']['h'],
'',
'',
'',
false,
300,
'',
false,
false,
0
);
$pdf->Image(
$scissorsIconPath,
$pdfParams['scissorsIcon']['x'],
$pdfParams['scissorsIcon']['y'],
$pdfParams['scissorsIcon']['w'],
$pdfParams['scissorsIcon']['h'],
'',
'',
'',
false,
300,
'',
false,
false,
0
);
$filePath = '/covers/' .$coverName . '.pdf';
$absFileName = $rootPath . $filePath;
try {
$pdf->Output($absFileName, 'F');
} catch (\Exception $e) {
//Move on
}
if (file_exists($absFileName)) {
$result = [
'absPath' => $absFileName,
'path' => $filePath,
];
} else {
$result = ['path' => 'error'];
}
return $result;
I am using the following package
"tecnickcom/tcpdf": "^6.4"
EDIT: Add code and more informations
TCPDF seems to have to methods that might help you:
$tcpdf->SetCreator('My PDF-Generator tool');
$tcpdf->SetAuthor('Your name');
I haven't tried it by myself. I just had a look at the examples of the TCPDF documentation.
Well, if you use a free lib it's quite normal that you can't change that. It would be the same case with other products.
But if you search with a tool such as ripgrep in the source code, you'll see that this string is defined in include/tcpdf_static.php at line 127 and is called by tcpdf.php at two places:
rg "getTCPDFProducer"
Output:
include\tcpdf_static.php
127: public static function getTCPDFProducer() {
tcpdf.php
9554: $out .= ' /Producer '.$this->_textstring(TCPDF_STATIC::getTCPDFProducer(), $oid);
9649: $xmp .= "\t\t\t".'<pdf:Producer>'.TCPDF_STATIC::_escapeXML(TCPDF_STATIC::getTCPDFProducer()).'</pdf:Producer>'."\n";
So if you really have to hide that, you should find a way to override that method, eventually apply a home-made patch or alter the generated file during or after generation.

conflict utf-8 tcpdf with cakeph 3

Hi community I'm using plugin CakePdf with the library tcpdf and when generating the pdf it shows me the following error
Error:
Warning: htmlspecialchars() [function.htmlspecialchars]: charset `ASCII' not supported, assuming utf-8 in G:\Trabajos_Web_PHP\diplomas\vendor\cakephp\cakephp\src\Core\functions.php on line 69
Warning: htmlspecialchars() [function.htmlspecialchars]: charset `ASCII' not supported, assuming utf-8 in G:\Trabajos_Web_PHP\diplomas\vendor\cakephp\cakephp\src\Core\functions.php on line 69
Warning: htmlspecialchars() [function.htmlspecialchars]: charset `ASCII' not supported, assuming utf-8 in G:\Trabajos_Web_PHP\diplomas\vendor\cakephp\cakephp\src\Core\functions.php on line 69
Warning: htmlspecialchars() [function.htmlspecialchars]: charset `ASCII' not supported, assuming utf-8 in G:\Trabajos_Web_PHP\diplomas\vendor\cakephp\cakephp\src\Core\functions.php on line 69
Warning: htmlspecialchars() [function.htmlspecialchars]: charset `ASCII' not supported, assuming utf-8 in G:\Trabajos_Web_PHP\diplomas\vendor\cakephp\cakephp\src\Core\functions.php on line 69
Warning (2): htmlspecialchars() [<a href='http://php.net/function.htmlspecialchars'>function.htmlspecialchars</a>]: charset `ASCII' not supported, assuming utf-8 [CORE\src\Core\functions.php, line 69]
my configuration is like this
Plugin::load('CakePdf', ['bootstrap' => true]);
Configure::write('CakePdf', [
'engine' => 'CakePdf.Tcpdf',
'encoding' => 'UTF-8'
'download' => true
]);
within my action which generates the pdf is this way
public function pdfdo($names = null) {
$file = new File(WWW_ROOT.'bd/'.'base_datos_do.json');
$json = $file->read(TRUE,'r');
$config = json_decode($json,TRUE);
$this->set('config',$config);
$persons = explode(',', $names);
$this->set('lastnames',$persons);
$this->viewBuilder()->setLayout('ajax');
$this->viewBuilder()->setTemplate('pdf/pdfdo');
$this->response->withType('application/pdf');
}
inside my template the configuration is this way, also apply the function mb_internal_encoding ('UTF-8'); to reset the enconding but still the error continues
$pdf = new TCPDF('L',PDF_UNIT,PDF_PAGE_FORMAT,TRUE,'UTF-8',FALSE);
$pdf->SetCreator(PDF_CREATOR);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// build my pdf
// finalization of my pdf
mb_internal_encoding('UTF-8');
$pdf->Output('Diplomas-DO.pdf', 'D');
header('Content-Type: application/pdf; charset=utf-8');
please help I go several days with the problem thanks.
I recently made a pdf with TCPDF and had the same problem. It looks like you're building your PDF with the TCPDF engine directly.
This error happens when CakePHP throws an error before the PDF output can begin... for example, it could be a "Trying to get a property of a non-object in...." error or something like that. You should be able to see the specific error message info below the htmlspecialchars() warnings.
I suggest checking to make sure your pdf is working correctly first... instead of your //build my pdf code, make a simple line like
$pdf->setXY(13, 13);
$pdf->Write(5, 'Test Hello');
If that works, then your configuration is working and the error is likely in your variables somewhere, so start building your pdf piece by piece, testing as you go.
I'll also add that I also chose to use the TCPDF engine directly, so I didn't use the CakePDF plugin (which works great but didn't meet my needs for this particular problem). I can provide more info on this if needed.
EDIT:
I'll provide some info on how I used TCPDF directly in my project without CakePDF in case you or anyone finds it helpful.
First, I wanted to use TCPDF engine directly for a few reasons:
Precise control of headers and footers
Able to use the text scaling, FIT CELL functions of TCPDF
more precise absolute positioning of elements
avoid CSS.
So I installed TCPDF directly with composer
composer require tecnickcom/tcpdf
Added this to app/vendor/cakephp-plugins.php
'Tecnickcom/Tcpdf' => $baseDir . '/vendor/tecnickcom/tcpdf/'
Then in app/config/bootstrap.php
Plugin::load('Tecnickcom/Tcpdf', ['bootstrap' => true]);
Then in app/config/routes.php
Router::extensions(['pdf']);
Then in app/src/controller/mycontroller.php, I created the method outputpdf. In that method, I set all the data collections to be used in the pdf, then
$this->viewBuilder()->template('mypdf');
Then in app/src/template/mycontroller/pdf/ i created the mypdf.php. This file contains only this code:
header("Content-type:application/pdf");
$this->layout = 'mypdf';
Then in app/src/template/layout/pdf/ I created the file mypdf.php. In this file I built my PDF with the data from the controller.
header("Content-type:application/pdf");
// Extend the TCPDF class to create custom Header and Footer
class MYPDF extends TCPDF {
//And build the header and footer in here
}
$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
//And make all the body content here
$pdf->Output('mypdf.pdf', 'I');
One downside with this approach is with foreign language fonts, you need to add and use the fonts you need in the app/vendor/tecnickcom/tcpdf/fonts folder, and those are all that are available for your pdf.
Please feel free to critique or advise on improvements to this approach.
I found the error is with the images that I use inside the pdf, one of them I use as the background of the pdf and another one is like a small image.
$pdf = new TCPDF('L',PDF_UNIT,PDF_PAGE_FORMAT,TRUE,'UTF-8',FALSE);
$pdf->SetCreator(PDF_CREATOR);
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$fontname = TCPDF_FONTS::addTTFfont(WWW_ROOT.'font'.DS.'Mada'.DS.'Mada-Regular.ttf', 'TrueTypeUnicode', '', 96);
$tagvs = array(
'div'=> array(
0 => array('h'=>0,'n' => 0),
1 => array('h'=>0,'n' => 0)),
'p'=> array(
0 => array('h'=>0,'n' => 0),
1 => array('h'=>0,'n' => 0)),
'h2' => array(
0 => array('h'=>0,'n' => 0),
1 => array('h'=>0,'n' => 0)),
'img' => array(
0 => array('h'=>0,'n' => 0),
1 => array('h'=>0,'n' => 0)
)
);
//variable that has small image
$imglogo = WWW_ROOT.'logos'.DS.'logoempresa.png';
foreach ($lastnames as $names) {
$pdf->AddPage();
$bMargin = $pdf->getBreakMargin();
$auto_page_break = $pdf->getAutoPageBreak();
$pdf->SetAutoPageBreak(false, 0);
//image for background
$img = WWW_ROOT.'img'.DS.'Diploma_DO.png';
$pdf->Image($img, 0, 0, 300, 210, 'png', '', '', false, 600, '', false, false, 0);
$pdf->SetAutoPageBreak($auto_page_break, $bMargin);
$pdf->setPageMark();
$pdf->setHtmlVSpace($tagvs);
$html_title = '<table cellspacing="0">'
. '<tr style="text-aling:center;line-height:11px">'
. '<td style="font-size: 37pt;font-weight: 600;color: #034bdb;color:#003275">'.$names.'</td>'
. '</tr>'
. '</table>';
$html_text_content = '<div style="text-align: center">'
. '<p style="color:#333;font-size: 16px;text-align: center">Ha completado con éxito el '.$config["Nombre-Taller-Curso"].',</p>'
. '<p style="color:#333;font-size: 16px;text-align: center">efectuada el '.$config["Fecha-Inicio-Fin"].' de '.$config["Mes-Ano"].' con una duración de '.$config["Horas"].' Horas.</p>'
. '</div>';
$html_text_content_bussines = '<div style="text-align: center">'
. '<p style="color:#333;font-size: 16px;text-align: center">Este taller ha sido diseñado especialmente para '.$config["Empresa"].'.</p>'
. '</div>';
$html_text_content_close = '<div style="text-align: center">'
. '<p style="color:#333;font-size: 16px;">'.$config["Fecha-Curso-Ubicacion"].'</p>'
. '</div>';
//img tag that contains the small image
$html_logo_bussines = '<img src="'.$imglogo.'" width="150" height="100">';
$pdf->SetFont($fontname, 'B', 26, '',false);
$pdf->writeHTMLCell(300,0,0,78,$html_title, '', 1, 0, true, 'C',true);
$pdf->SetFont($fontname,'',14,'',false);
$pdf->writeHTMLCell(300, 0, 0, 88, $html_text_content, '', 1, 0, true, 'C', true);
$pdf->writeHTMLCell(300, 0, 0, 109, $html_text_content_bussines, '', 1, 0, true, 'C', true);
$pdf->writeHTMLCell(300,0,0,125,$html_text_content_close,'',1,0,true,'C',true);
//use of the small image
$pdf->writeHTMLCell(300,0,0,155,'<div style="text-align:center">'.$html_logo_bussines.'<div>',0,0,0,true,'C',true);
$pdf->lastPage();
}
the error continues, the error stops showing when I comment the line where the
$pdf->writeHTMLCell(300,0,0,155,'<div style="text-align:center">'.$html_logo_bussines.'<div>',0,0,0,true,'C',true);
I do not know what I'm doing wrong I read the documentation and this function if you accept the img tag.
Can you debug your $imglogo variable to see if the file path is correct?
Or, try displaying the image with the $pdf->Image() function?
Note that TCPDF has a configuration option in vendor\tecnickcom\tcpdf\config\tcpdf_config.php:
define ('K_PATH_IMAGES', 'C:\\windowsfolder\\htdocs\\app\\webroot\\img\\');
So you can call the image in the PDF via:
$image_file = K_PATH_IMAGES.'imagefile.jpg';
See if that works...

DefHTMLHeaderByName doesn't seem to work mpdf

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

Storing FPDF output into variable or new CURLFILE

Wondering how I can store FPDF generated file from form fields in a variable or other for use in CURL request. I am able to upload a file via the file upload e.g input type="file" name="file" manually and post it with CURL but not with the automatically generated pdf file.
Is this possible? See below code:
$noteTitle = (isset($_POST['noteTitle']) ? $_POST['noteTitle'] : null);
$noteBody = (isset($_POST['noteBody']) ? $_POST['noteBody'] : null);
//FPDF
require("fpdf/fpdf.php");
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont("Arial", "B", 16);
$pdf->Cell(0,100, "Note Title: {$noteTitle} \n", 1, 0, 'C');
$pdf->Cell(0,100, "Note Body: {$noteBody}", 1, 0, 'C');
$filename="test.pdf";
$pdf->output($filename,'f');
$cfile = new CURLFILE($_FILES[$pdf]['tmp_name'], $_FILES[$pdf]['type'], $_FILES[$pdf]['name']);
//Post to curl
$data = array();
$data['FILE_ATTACHMENTS'] = $cfile;
//curl code etc
...
First you need to save dynamically generated at server directory then you can use for the upload or any other purpose like send as attachment email.
For Saving the PDF as a file use below method:
$pdf->Output('yourfilename.pdf','F');
If you want to save file at server directory:(make sure you have 777 writing permissions for that folder!):
$pdf->Output('directory/yourfilename.pdf','F');
For more details you can visit tutorial: http://www.phpmysqlquery.com/fpdf-output-methods-for-pdf-files-in-php/

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.

Categories