Hiyas,
I'm trying to print to an older duplex printer, and paper size is about letter-size wide, but only a half letter-size tall, so I'm trying to define a custom page output like so. I've tried many things, but this is where I'm at right now, probably not all necessary, but nothing seems to be working.
$width = '300';
$height = '150';
$pageLayout = array($width, $height); // or array($height, $width)
$pdf = new TCPDF('P', 'mm', $pageLayout, true, 'UTF-8', false);
// set array for viewer preferences
$preferences = array(
'FitWindow' => false,
'NonFullScreenPageMode' => 'UseNone', // UseNone, UseOutlines, UseThumbs, UseOC
'ViewArea' => 'MediaBox', // CropBox, BleedBox, TrimBox, ArtBox
'ViewClip' => 'MediaBox', // CropBox, BleedBox, TrimBox, ArtBox
'PrintArea' => 'MediaBox', // CropBox, BleedBox, TrimBox, ArtBox
'PrintClip' => 'MediaBox', // CropBox, BleedBox, TrimBox, ArtBox
'PrintScaling' => 'AppDefault', // None, AppDefault
'Duplex' => 'DuplexFlipLongEdge', // Simplex, DuplexFlipShortEdge, DuplexFlipLongEdge
'PickTrayByPDFSize' => false
);
$pdf->setViewerPreferences($preferences);
$pdf->AddPage('P', $pageLayout, false, false);
But the output of this is:
Anytime I try to change the height, it seems to affect the width. If I change the width, it still affects the width, and other sizes just don't come out as you would expect.
Anyone have a suggestion, or know if I'm doing something wrong?
Related
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.
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' );
?>
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...
Hello my task is to certify pdf with digital Signature Certification and release it in pdf/a format. I tried using tcpdf, but i couldn't import existing pages. So I added fpdi, kind of mixing them:
require_once('./tcpdf/tcpdf.php');
require_once('./tcpdf/fpdi.php');
$pdf = new FPDI( );
//$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false, true);
$file = realpath("484.pdf");
$pagecount = $pdf->setSourceFile($file);
for($i = 1 ; $i <= $pagecount ; $i++){
$tpl = $pdf->importPage($i);
$size = $pdf->getTemplateSize($tpl);
$orientation = $size['h'] > $size['w'] ? 'P':'L';
$pdf->AddPage($orientation);
$pdf->useTemplate($tpl, null, null, $size['w'], $size['h'], true);
}
$pdf->SetCreator("Creator");
$pdf->SetTitle('123Titel');
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$certificate = 'file://123.crt';
$info = array(
'Name' => '123test',
'Location' => 'place',
'Reason' => '123',
'ContactInfo' => '123',
);
$pdf->setSignature($certificate, $certificate, '123', '', 2, $info);
$pdf->SetFont('helvetica', '', 12);
$pdf->addEmptySignatureAppearance(0, 0, 0, 0);
$pdf->Output('test.pdf', 'F');
Alright, so I can put signature in alright with this, but i cant make it pdf/a.
What decides pdf/a format is
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false, true);
The last "true". But I cant use this tcpdf function, or i get:
Call to undefined method TCPDF::setSourceFile() in...
So im forced to use $pdf = new FPDI( );, which can't save pdf in pdf/a format
Surely someone knows something that im missing and im running out of ideas on what to do.
-Can I import existing pdf with only tcpdf and if yes HOW?
-Is there any other way to make file format pdf/a (i coudlnt find any)
-Any tips whatsoever
It appears that I can extend tcpdf with fpdi. Somehow it didnt work until i changed fpdi_bridge to always extend tcpdf and changed
new FPDI();
to
new FPDI(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false, true);
Check out the source code here:
http://www.savvissl.com/demo1/showcode.php
check out the script here
http://www.savvissl.com/demo1/testPDF.php
Here is the issue... the footer prints fine on every page except for the last page. The last page never has a footer. If there is only one page in the document the footer will not print at all.
OK I couldn't figure it out, but i was able to copy a co-workers example that worked. If anyone wants the source code here it is:
<?php
require_once('tcpdf/config/lang/eng.php');
require_once('tcpdf/tcpdf.php');
define('PDF_FOOTER_TEXT','800 Vinial St. Pittsburgh, PA 15212 | phone: 412.321.7006 | fax: 412.321.7005 | www.savvior.com');
$PDF_LINE_COLOR=array(255,255,0);
define('PDF_FOOTER_TEXT_COLOR',170);
class MYPDF extends TCPDF
{
//Page header
public function Header()
{
global $PDF_LINE_COLOR;
$image_file = K_PATH_IMAGES.'image.jpg';
$this->Image($image_file, 160, 0, 30, '', 'JPG', '', 'T', false, 300, '', false, false, 0, false, false, false);
$this->SetFont('helvetica', 'B', 20);
$this->Cell(0, 15, '', 0, false, 'C', 0, '', 0, false, 'M', 'M');
$this->line(10,27,200,27,array('width' => 0.5, 'cap' => 'butt', 'join' => 'miter', 'solid' => 4, 'color' => $PDF_LINE_COLOR));
}
public function Footer()
{
global $PDF_LINE_COLOR;
$cur_y = $this->GetY();
$ormargins = $this->getOriginalMargins();
$this->SetTextColor(PDF_FOOTER_TEXT_COLOR, PDF_FOOTER_TEXT_COLOR, PDF_FOOTER_TEXT_COLOR);
$this->SetY($cur_y);
$this->line(10,400,200,400,array('width' => 0.5, 'cap' => 'butt', 'join' => 'miter', 'solid' => 4, 'color' => $PDF_LINE_COLOR));
$this->Cell(0,11,"Page ". $this->getAliasNumPage().'/'.$this->getAliasNbPages(),'T',0,'L');
$this->Cell(0,11,PDF_FOOTER_TEXT,'T',0,'R');
}
}
ob_start();
?><h1>Content Is Needed For This Page...</h1>
...
<?
$html=ob_get_clean();
function makePDFFile($fileName,$html)
{
$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Savvior Project Manager');
$pdf->SetTitle('Auto Generated PDF');
$pdf->SetSubject('Auto Generated PDF');
$pdf->SetKeywords('TCPDF');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, 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+5, 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
$pdf->setLanguageArray($l);
// set font
$pdf->SetFont('helvetica', '', 12);
// add a page
$pdf->AddPage();
$pdf->writeHTML($html, true, false, true, false, '');
$doc=$pdf->Output(dirname(__FILE__)."/cache/{$fileName}", 'F');
return $fileName;
}
$file=makePDFFile('poo-poo-platter.pdf',$html);
header("location: cache/{$file}");
?>
Comparing this new code to my old reveals no insight into why this works... in fact the example in the TCPDF examples folder exhibits the same issue, however if you run it from their website the footer is displayed correctly. Well anyway hope this helps someone
I know nothing about TCPDF save what I just learned going through their docs.
It looks like Footer() is only called for you when you explicitly call AddPage(), at which point it is added to the PREVIOUS PAGE. The rest of the time I believe you have to call it yourself.
There's also this whole StartPage()/EndPage() thing that sounds like an alternative to AddPage().
You might want to: "start page, header, draw text, footer, end page" instead. It looks like Write() calls AddPage() for you, which is why the headers and footers on all-but-the-last-page are present.
Bottom Line: Just call Footer() after you call Write() in this example. Real world examples will almost certainly be a bit more complex.