Yii HTML2PDF (ePdf) Impossible de charger l'image /images/big-logo.png - php

Im using Yii framework, and Im using EYiiPdf extension.
I have to view an image in Pdf output file but I got this Error:
ERREUR n°6 : Impossible de charger l'image /images/big-logo.png
in
/protected/vendor/html2pdf/html2pdf.class.php(1319)
this is mu code :
in controller:
$html2pdf = Yii::app()->ePdf->HTML2PDF();
$html2pdf->WriteHTML($this->renderPartial('index', true));
$html2pdf->Output();
and this the image tag in view
<img src="/images/big-logo.png" alt="logo" style="width: 190px; height: 70px">
the image folder and image exist.
this is my folder structure
images
js
css
protected
--->controoler
--->views
--------->pdf
------------->index.php
and the same image tag with same image path working in any other view file but if use the HTML2PDF it return that error
Thank

I solved my problem by:
in html2pdf.class.php file at line 5602. by adding the server Document Root to image source.
protected function _tag_open_IMG($param)
{
$src = str_replace('&', '&', $param['src']);
$documentRoot = $_SERVER['DOCUMENT_ROOT']; // get server document root
$src = $documentRoot. '/' . $src; //aapend server document root to the image soure
$this->parsingCss->save();
$this->parsingCss->value['width'] = 0;
$this->parsingCss->value['height'] = 0;
$this->parsingCss->value['border'] = array('type' => 'none', 'width' => 0, 'color' => array(0, 0, 0));
$this->parsingCss->value['background'] = array('color' => null, 'image' => null, 'position' => null, 'repeat' => null);
$this->parsingCss->analyse('img', $param);
$this->parsingCss->setPosition();
$this->parsingCss->fontSet();
$res = $this->_drawImage($src, isset($param['sub_li']));
if (!$res) return $res;
$this->parsingCss->load();
$this->parsingCss->fontSet();
$this->_maxE++;
return true;
}

In this case html2pdf.class.php just take the image path instead of url, actually you dont need to change the library code, just need...
<img src="<?=Yii::getPathOfAlias('webroot').'/images/big-logo.png'?>">
for background image...
<div style="background-image: url(<?=Yii::getPathOfAlias('webroot').'/images/big-logo.png'?>)">
...
</div>

Related

html font size not working as expected with mpdf

$pdf_html variable are holding html content to add on each pdf pages. The problem is the inline font size not working. If i change it to any large font size number nothing working rather taking a default font size always. please check the below codes.
Is there anything wrong on my html deceleration? any suggestion?
Note: I have to write each html tag as absolute position which is defined on stylesheet but not inline.
$defaultConfig = (new \Mpdf\Config\ConfigVariables())->getDefaults();
$defaultFontConfig = (new \Mpdf\Config\FontVariables())->getDefaults();
$storage_path = storage_path();
$stylesheet = file_get_contents($storage_path.'/fonts/style_pdf_custom.css');
$mpdf = new \Mpdf\Mpdf([
'dpi' => 144,
'tempDir' => $storage_path . '/app/public/documents/completed/pages',
'fontDir' => array_merge($defaultConfig['fontDir'], [
$storage_path . '/fonts'
]),
'fontdata' => $defaultFontConfig['fontdata'] + [
'greatvibes' => [
'R' => 'GreatVibes-Regular.ttf',
],
'montezregular' => [
'R' => 'Montez-Regular.ttf',
],
'sacramentoregular' => [
'R' => 'Sacramento-Regular.ttf',
]]
]);
$mpdf->WriteHTML($stylesheet,1);
foreach($available_documents as $key => $doc){
$pages = $this->appRepo->getDocumentPages($doc->id, $doc->envelope_id);
$sourceFilename = $doc->filename_system_generated;
$mpdf->SetSourceFile($storage_path . "/app/public/documents/" . $sourceFilename);
foreach($pages as $k => $page){
$elements = json_decode($page->elements);
$mpdf->AddPage();
$importedPage = $mpdf->importPage($page->page_no);
$mpdf->useTemplate($importedPage, ['adjustPageSize' => true]);
$pdf_html = '<div class="common-block" style="width:203px; left:158px;top:243px;height:28px;justify-content: left;color:black;font-size:22px;font-weight: bold; "> Mr. Admin</div><div class="common-block" style="width:247px; left:739px;top:365px;height:40px;justify-content: left;color:black;font-size:24px; ">Checking Font Size</div>';
$mpdf->WriteHTML($pdf_html, \Mpdf\HTMLParserMode::HTML_BODY);
}
}
$tempname = time().$filename;
$mpdf->Output($storage_path. "/app/public/documents/temp/" . $tempname, "F");
After doing research last couple of days i can figure out the problem why the font size not working properly inside a div with absolute position.
When your html content have absolute position and you have set a fixed height, width then what ever font-size you set it will not exceed the div and mpdf auto adjust the font-size but while on relative position any font-size always works as it define.
So finally i have adjust the div width and height then i found the actual font-size changes are working well on a div with position:absolute

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...

How can I serve an SVG image from Google Cloud Storage?

Right now I'm working on allowing user image uploads to my site using the Google Cloud Storage. Uploading regular image files such as jpg, png, gif, and webp works fine. However, SVG images do not work. They get uploaded ok but when I have the PHP code echo the URL as an image source, all browsers just display the missing image icon. However, it does appear as if the image is downloading in the network tab of the code inspector. Not only that, pasting the link into it's own tab causes the file to download. This makes me think that the server is telling the browser to download the file rather than serve it as an image. Here is the code that I am using:
include 'GDS/GDS.php';
//create datastore
$obj_store = new GDS\Store('HomeImages');
$bucket = CloudStorageTools::getDefaultGoogleStorageBucketName();
$root_path = 'gs://' . $bucket . '/' . $_SERVER["REQUEST_ID_HASH"] . '/';
$public_urls = [];
//loop through all files that are images
foreach($_FILES['images']['name'] as $idx => $name) {
if ($_FILES['images']['type'][$idx] === 'image/jpeg' || $_FILES['images']['type'][$idx] === 'image/png' || $_FILES['images']['type'][$idx] === 'image/gif' || $_FILES['images']['type'][$idx] === 'image/webp' || $_FILES['images']['type'][$idx] === 'image/svg+xml') {
//path where the file should be moved to
$original = $root_path . 'original/' . $name;
//move the file
move_uploaded_file($_FILES['images']['tmp_name'][$idx], $original);
//don't use the getImageServingUrl function on SVG files because they aren't really images
if($_FILES['images']['type'][$idx] === 'image/svg+xml')
$public_urls[] = [
'name' => $name,
'original' => CloudStorageTools::getPublicUrl($original, true),
'thumb' => CloudStorageTools::getPublicUrl($original, true),
'location' => $original
];
else
$public_urls[] = [
'name' => $name,
'original' => CloudStorageTools::getImageServingUrl($original, ['size' => 1263, 'secure_url' => true]),
'thumb' => CloudStorageTools::getImageServingUrl($original, ['size' => 150, 'secure_url' => true]),
'location' => $original
];
}
}
//store image location and name in the datastore
foreach($public_urls as $urls){
$image = new GDS\Entity();
$image->URL = $urls['original'];
$image->thumbURL = $urls['thumb'];
$image->name = $urls['name'];
$image->location = $urls['location'];
$obj_store->upsert($image);
}
//redirect back to the admin page
header('Location: /admin/homeimages');
Having run into this issue just now, I found a solution. It turns out that every file in a bucket has metadata attached and stored as key-value pairs. The key we're after is 'Content-Type', and the value isn't always correct for SVG. the value needs to be 'image/svg+xml'. I don't know how to set that programmatically, but if you only have a few objects, then it's easy to do in the file's ellipses menu in the online interface for the bucket.

I want to set header and footer in PDF using mpdf

I have generated a PDF using mpdf library in CodeIgniter. I want to attach header image and footer image with proper margin, I have created one code but header and footer get overlapped.
//controller
$this->load->library('m_pdf');
$param = '"","A4","","",0,0,100,0,6,3,"L"';
$pdf = $this->m_pdf->load($param);
// $pdf->useOddEven = true;
$pdf->SetHTMLHeader('<img src="' . base_url() . 'custom/Hederinvoice.jpg"/>');
$pdf->SetHTMLFooter('<img src="' . base_url() . 'custom/footarinvoice.jpg"/>');
$wm = base_url() . 'custom/Watermark.jpg';
$pdf->SetWatermarkImage($wm);
$pdf->showWatermarkImage = true;
$data['main_content'] = 'dwnld';
$this->load->view('template', $data);
$html = $this->load->view('template_pdf', $data, true);
$this->load->view('template_pdf', $data, true);
$pdf->WriteHTML($html);
$pdf->page = 0;
$pdf->state = 0;
$pdf->Output($pdfFilePath, "D");
$pdf->SetHTMLHeader('<img src="' . base_url() . 'custom/Hederinvoice.jpg"/>');
$pdf->SetHTMLFooter('<img src="' . base_url() . 'custom/footarinvoice.jpg"/>');
$wm = base_url() . 'custom/Watermark.png';
$data['main_content'] = 'dwnld';
//$this->load->view('template', $data);
$html = $this->load->view('template_pdf', $data, true);
$this->load->view('template_pdf', $data, true);
$pdf->AddPage('', // L - landscape, P - portrait
'', '', '', '',
5, // margin_left
5, // margin right
60, // margin top
30, // margin bottom
0, // margin header
0); // margin footer
$pdf->WriteHTML($html);
$pdf->Output($pdfFilePath, "D");
Addpage for to creating page in mpdf and pass parameters of margin top,bottom then we get proper output
You can set custom HTMl Header for first page and Other page as below:
Just add the below snippet above all html content. You can add Inline CSS for it using tags above al html
<htmlpageheader name="firstpage" style="display:none">
<div style="text-align:center"><img src="'.'logo.png"/></div>
</htmlpageheader><sethtmlpageheader name="firstpage" value="on" show-this-page="1" />
<htmlpageheader name="otherpages" style="display:none">
<div style="text-align:center">{PAGENO}</div>
</htmlpageheader><sethtmlpageheader name="otherpages" value="off" />';
Or can use https://mpdf.github.io/headers-footers/headers-footers.html as refrence to use HTML header function
To Set footer one can use:
// Footer Configuration for all pages, can be changed for odd and even pages accordingly
$oddEvenConfiguration =
[
'L' => [ // L for Left part of the header
'content' => 'Your Content',
'font-size' => 10,
'font-family' => 'sans-serif',
'color'=>'#000000'
],
'C' => [ // C for Center part of the header
'content' => '',
],
'R' => [
'content' => '{PAGENO}',
],
'line' => 0, // That's the relevant parameter to remove line style in footer
];
$headerFooterConfiguration = [
'odd' => $oddEvenConfiguration,
'even' => $oddEvenConfiguration
];

Categories