cannot generate pdf with tcpdf - php

on my site a user can print (in pdf) the nda he accepted
for some reason i cannot display the pdf
here the logic
first rewrite the rule
.htaccess
RewriteRule ^nda/?$ ndapdf.php?useSessionUser=1 [L]
then the php
<?php
$html = file_get_contents("/lib/nda.txt");
$html = str_replace("##user##", $_SESSION["currentUser"]);
$html = str_replace("##date##", date("Y-m-d h:i:s"));
require("/lib/web/tcpdf/config/lang/eng.php");
require("/lib/web/tcpdf/tcpdf.php");
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, "UTF-8", false);
$pdf->SetCreator("mysite");
$pdf->SetAuthor("author_name");
$pdf->SetTitle("NDA");
$pdf->SetSubject("Accepted NDA");
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, "", PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, "", PDF_FONT_SIZE_DATA));
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$pdf->setLanguageArray(array("w_page" => ""));
$fontname = $p->addTTFfont("/fonts/AveriaSans-light.ttf", "TrueTypeUnicode", "", 32);
$pdf->SetFont("arial", "", 10);
$pdf->AddPage();
$pdf->writeHTML($html, true, false, true, false, "");
$pdf->lastPage();
$pdf->Output("/home/comp/pdf/nda/$currentUser.pdf", "F");
header("Content-Type: application/pdf\n");
read("/home/comp/pdf/nda/$currentUser.pdf");
i get:
"TCPDF ERROR: Could not include font definition file: AveriaSans-light"
the font is: ll /fonts/
-rw-r--r-- 1 root root 85084 2011-11-02 17:51 AveriaSans-Light.ttf
thanks

I think the problem is, that the directories cache and fonts of TCPDF (residing in the folder which path is stored in the constant K_PATH_MAIN, by default this is the TCPDF-directory) are not writeable by your webserver. Don't confuse your own fonts-directory with the one used by TCPDF internally.
The fonts directory has to be writeable because addTTFfont first converts the TTF-file and writes the output of the conversion in to the fonts directory. If later on SetFont is used with "AveriaSans-light" it tries to include those files and fails with "Could not include font definition file" if they are not found.

vstm is right but also maybe because you have
-rw-r--r-- 1 root root 85084 2011-11-02 17:51 AveriaSans-Light.ttf
with capital L and in your code is lowercase l

Related

Tcpdf by using Separate management file

I am using TCPDF to generate the PDF.
I have two files.The contents of the first file are the invoice contents (table, photo, etc..../without code TCPDF)
The contents of the second file are the following code(Coded by my colleague).
$_factorUrl = PathAllocator::getBaseUrlByPath(__FILE__)."modules/printer/views_pdf/".$billName.".php?order_id=".$orderId;
ob_start();
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
//Before Write
// set some language dependent data:
$lg = Array();
$lg['a_meta_charset'] = 'UTF-8';
$lg['a_meta_dir'] = 'rtl';
$lg['a_meta_language'] = 'fa';
$lg['w_page'] = 'page';
// set some language-dependent strings (optional)
$pdf->setLanguageArray($lg);
//After Write
$pdf->setRTL(true);
// set font
$pdf->SetFont('dejavusans', '', 12);
// add a page
$pdf->AddPage();
// Persian content
$pdf->WriteHTML(execute($_factorUrl), true, 0, true, 0);
//Close and output PDF document
//$pdf->Output("factor.pdf");
ob_end_clean();
$pdfFileName = $billName."-".$orderId.md5(rand(1,1000).microtime().UserAuth::getCustomerId().$billName.$orderId);
$_fullFilePath = $sourcePath."modules/printer/dl/".$pdfFileName.".pdf";
$pdf->Output($_fullFilePath, 'FI');
header("location: ".PathAllocator::getBaseUrlByPath(__FILE__)."modules/printer/dl/".$pdfFileName.".pdf");
Now I have the output(second image), But no style is applied, the tables do not look good and ...
when I add any tcpdf statement to first file, I have no output.
for example I add to the first file :
<?php
$html = '<h1>Example of HTML text flow</h1>';
?>
first image is Invoice appearance on web page
second image is Invoice pdf
you have to use tcpdf image for background image
https://tcpdf.org/examples/example_009/
and you need to use tcpdf table
https://tcpdf.org/examples/example_045/

Saving HTML content generated by PHP as a PDF file

I'm trying to save HTML content generated by PHP as a PDF file.
To do this I found FPDF.
My script is as follows:
if(isset($_POST['content_to_save']) && isset($_POST['name_to_save'])){
$file_name = $_POST['name_to_save'];
$file_content = $_POST['content_to_save'];
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Helvetica','',12);
$pdf->Cell(40,10,$file_content);
$content = $pdf->Output('../my_folder/'.$file_name.'.pdf','F');
}
My two variables ($file_name & $file_content) are set as I want them with no issues and it creates the PDF in the correct location with the correct file name, however the actual content is the HTML in text format rather than the actual rendered HTML.
Edit
I have now started trying to use TCPDF
My code now is as follows:
if(isset($_POST['po_content_to_save']) && isset($_POST['po_name_to_save'])){
$file_name = $_POST['po_name_to_save'];
$file_content = $_POST['po_content_to_save'];
require('TCPDF/tcpdf.php');
$pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf->SetFont('helvetica', '', 12);
$pdf->AddPage();
$pdf->writeHTML($file_content);
$pdf->Output('../my_folder/'.$file_name.'.pdf', 'I');
}
However, now I get the following error:
TCPDF ERROR: Some data has already been output, can't send PDF file
So after alot of trial and error with a few different libraries I finally found Dompdf
The following code now does what I was trying to achieve:
require '../vendor/autoload.php';
use Dompdf\Dompdf;
if(isset($_POST['po_content_to_save']) && isset($_POST['po_name_to_save'])){
$file_name = $_POST['po_name_to_save'];
$file_content = $_POST['po_content_to_save'];
$document = new Dompdf();
$document->loadHtml($file_content);
$document->setPaper('A4', 'portrait');
$document->render();
$output = $document->output();
file_put_contents('../my_folder/'.$file_name.'.pdf', $output);
}

TCPDF_import is not bringing in an existing file

I have a PDF of a blank certificate, I want to fill in two lines when the user completes a course of study, and display the PDF so they can print or download it.
I am using TCPDF to write the two lines on an existing PDF.
Per suggestions in a previous post ( using PHP to fill in a PDF ), I am using TCPDF_IMPORT to bring an existing PDF into the object, and writing on top of it.
However, the original PDF does NOT show on the screen, I am left with a blank document, with only the lines of text I created.
Below is what I have to this point - it yields ONLY the line "This is my test text."
<?php
// Include the main TCPDF library (search for installation path).
require_once( '../tcpdf_import.php' );
// create new PDF document
$pdf = new TCPDF_IMPORT( '1_cert.pdf' );
// set document information
$pdf->SetCreator( 'aaa.com' );
$pdf->SetAuthor( 'aaa.com' );
$pdf->SetTitle( 'Certificate Test' );
$pdf->SetSubject( 'In completion of x-module' );
$pdf->SetKeywords( '' );
// set default monospaced font
$pdf->SetDefaultMonospacedFont( PDF_FONT_MONOSPACED );
// set font
$pdf->SetFont( 'times', 'B', 30 );
// display
$pdf->SetDisplayMode( 'fullpage', 'SinglePage', 'UseNone' );
// set margins
$pdf->SetMargins( 10, PDF_MARGIN_TOP, 10 );
// 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 );
}
// -------------------------------------------------------------
// stuff i believe should write test over an existing PDF
// -------------------------------------------------------------
$pdf->StartPage( 'L', '', false );
$pdf->SetY( 50 );
$pdf->Cell( 0, 0, 'test text', 0, 1, 'C' );
$pdf->EndPage( false );
// -------------------------------------------------------------
// end of stuff i believe should write test over an existing PDF
// -------------------------------------------------------------
//Close and output PDF document
$pdf->Output( 'aTest.pdf', 'I' );
?>
Well, not as eloquent as I wanted, but I found something that works....
<?php
require_once "tcpdf/tcpdf.php";
require_once "FPDI/fpdi.php";
$pdf = new FPDI( 'L', 'mm', 'LETTER' ); //FPDI extends TCPDF
$pdf->AddPage();
$pages = $pdf->setSourceFile( 'test.pdf' );
$page = $pdf->ImportPage( 1 );
$pdf->useTemplate( $page, 0, 0 );
$pdf->Output( 'newTest.pdf', 'F' );
?>
Thanks to Simon who posted in http://sourceforge.net/p/tcpdf/discussion/435311/thread/66272894/
I was able to modify this - it entails running two libraries - but it works.
Create a file and call it pdfConcat.php and paste:
<?php
require_once("tcpdf/tcpdf.php");
require_once("fpdi/fpdi.php");
class concat_pdf extends FPDI {
var $files = array();
function setFiles($files) {
$this->files = $files;
}
function concat() {
foreach($this->files AS $file) {
$pagecount = $this->setSourceFile($file);
for ($i = 1; $i <= $pagecount; $i++) {
$tplidx = $this->ImportPage($i);
$s = $this->getTemplatesize($tplidx);
$this->AddPage('P', array($s['w'], $s['h']));
$this->useTemplate($tplidx);
}
}
}
}
?>
Usage:
include_once("pdfConcat.php");
$pdf =& new concat_pdf();
$pdf->setFiles(array("doc.pdf","pauta.pdf", "4bp.pdf", "5bp.pdf"));
$pdf->concat();
$pdf->Output("newpdf.pdf", "I");
http://garridodiaz.com/concatenate-pdf-in-php/
Olè!!!
As stated in TCPDF_IMPORT documentation page at this time (2020-04-16)
TCPDF_IMPORT !!! THIS CLASS IS UNDER DEVELOPMENT !!!
Futhermore the free version of FPDI supports PDF up to version 1.4
If someone else is looking for something that works easily with TCPDF, I used TCPDI from https://github.com/pauln/tcpdi. You can find some fork ready for composer too.
The usage is quite simple and similar to FPDI. Here a snipped from my code. I have a privacy policy (a static PDF file) and want to save a copy with user name and agreement date in the footer of each page.
// Create new PDF document
$pdf = new TCPDI(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
...
// Add the pages from the source file.
$pagecount = $pdf->setSourceFile($localPrivacy);
for ($i = 1; $i <= $pagecount; $i++) {
$tplidx = $pdf->importPage($i);
$pdf->AddPage();
$pdf->useTemplate($tplidx);
// Add agreement text in document footer
$pdf->SetXY(15,282);
$pdf->Cell(180, 5, "Documento approvato da {$fullName} il {$date}", 0, 0, 'C');
}
// Send PDF on output
$pdf->Output(FOLDER_PATH . DIRECTORY_SEPARATOR . "{$userId}.pdf", 'F');

combining tfpdf and fpdi

I am using following code
<?php
$hd1 = $_POST["hd1"];
require_once('fpdi.php');
require_once('fpdf.php');
require('tfpdf.php');
$pdf =& new FPDI();
$pagecount = $pdf->setSourceFile('template.pdf');
$tplIdx = $pdf->importPage(1);
$s = $pdf->getTemplatesize($tplIdx);
$pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L', array($s['w'], $s['h']));
$pdf->useTemplate($tplIdx,0, 0, 0, 0, true);
$pdf->AddFont('DejaVu','','DejaVuSansCondensed.ttf',true);
$pdf->AddFont('DejaVu', 'B', 'DejaVuSansCondensed-Bold.ttf', true);
$pdf->SetFont('DejaVu', '', 14);
$pdf->Cell(50,10,$hd1,0,1);
// Select a standard font (uses windows-1252)
$pdf->SetFont('Arial', '', 14);
$pdf->Ln(10);
$pdf->Write(5, 'The file uses font subsetting.');
$pdf->Output('doc.pdf', 'I');
?>
I am getting error:
Fatal error: Class 'FPDF' not found in C:\xampp\htdocs\san\ak-form\pdf\fpdi_bridge.php on line 33
When I use following code from http://www.setasign.com/products/fpdi/demos/tfpdf-demo/
<?php
$hd1 = $_POST["hd1"];
// require tFPDF
require_once('tfpdf.php');
// map FPDF to tFPDF so FPDF_TPL can extend it
class FPDF extends tFPDF
{
/**
* "Remembers" the template id of the imported page
*/
protected $_tplIdx;
/**
* Draw an imported PDF logo on every page
*/
public function Header()
{
if (is_null($this->_tplIdx)) {
$this->setSourceFile("template.pdf");
$this->_tplIdx = $this->importPage(1);
}
$size = $this->useTemplate($this->_tplIdx, 130, 5, 60);
$this->SetFont('DejaVu', 'B', 16);
$this->SetTextColor(0);
$this->SetXY($this->lMargin, 5);
$text = 'tFPDF (v' . tFPDF_VERSION . ') and FPDI (v'
. FPDI::VERSION . ')';
$this->Cell(0, $size['h'], $text);
$this->Ln();
}
}
// just require FPDI afterwards
require_once('fpdi.php');
// initiate PDF
$pdf = new FPDI();
// Add some Unicode font (uses UTF-8)
$pdf->AddFont('DejaVu', '', 'DejaVuSansCondensed.ttf', true);
$pdf->AddFont('DejaVu', 'B', 'DejaVuSansCondensed-Bold.ttf', true);
// add a page
$pdf->AddPage();
$pdf->SetFont('DejaVu', '', 14);
// Select a standard font (uses windows-1252)
$pdf->SetFont('Arial', '', 14);
$pdf->Ln(10);
$pdf->Write(5, 'The file uses font subsetting.');
$pdf->Output('doc.pdf', 'I');
?>
And getting following error:
Warning: fopen(/home/content/w/i/s/wiseinmotion/html/test3/pdf/font/unifont/DejaVuSansCondensed.ttf): failed to open stream: No such file or directory in C:\xampp\htdocs\san\ak-form\pdf\font\unifont\ttfonts.php on line 496
Can't open file /home/content/w/i/s/wiseinmotion/html/test3/pdf/font/unifont/DejaVuSansCondensed.ttf
What is the correct way so that I can use exiting pdf and can use utf-8 font?
You're asking two different questions here:
why isn't FPDF defined in the first code sample, and
why can't it load my font in the second code sample.
I'm going to answer #2 first, because it's easy: the font file is not being found. Check your path and make sure the code is looking for the font in the right place.
Regarding #1: I suspect the issue comes down to your require_once statements. Specifically, you're requiring fpdf.php in your code when the example code does not. My guess is that there's a conflict there somewhere.
Rather than spending a lot of time looking around the libraries for a problem, I would start with the example code (which comes from the developer's website, so we're pretty sure it works - maybe not, but let's assume it does until proven otherwise). Assuming that code works (and all you need to do there is fix the path to your font), start with that and modify it to do what you want.

TCPDF Save file to folder?

I'm using TCPDF to print a receipt and then send it to customer with phpMailer, but I have a problem:
I have no idea how to save the file into a pdf.
I've tried this:
// reset pointer to the last page
$pdf->lastPage();
//Close and output PDF document
$pdf->Output('kuitti'.$ordernumber.'.pdf', 'I');
$this->Output("kuitit");
try this
$pdf->Output('kuitti'.$ordernumber.'.pdf', 'F');
this stores the generated pdf file in your custom folder of your project
$filename= "{$membership->id}.pdf";
$filelocation = "D:\\wamp\\www\\project\\custom";//windows
$filelocation = "/var/www/project/custom"; //Linux
$fileNL = $filelocation."\\".$filename;//Windows
$fileNL = $filelocation."/".$filename; //Linux
$this->pdf->Output($fileNL, 'F');
$pdf->Output() takes a second parameter $dest, which accepts a single character. The default, $dest='I' opens the PDF in the browser.
Use F to save to file
$pdf->Output('/path/to/file.pdf', 'F')
Only thing that worked for me:
// save file
$pdf->Output(__DIR__ . '/example_001.pdf', 'F');
exit();
For who is having difficulties storing the file, the path has to be all the way through root. For example, mine was:
$pdf->Output('/home/username/public_html/app/admin/pdfs/filename.pdf', 'F');
TCPDF uses fopen() to save files.
Any paths passed to TCPDF's Output() function should thus be an absolute path.
If you would like to save to a relative path, use e.g. the __DIR__ global constant (see this answer).
If you still get
TCPDF ERROR: Unable to create output file: myfile.pdf
you can avoid TCPDF's file saving logic by putting PDF data to a variable and saving this string to a file:
$pdf_string = $pdf->Output('pseudo.pdf', 'S');
file_put_contents('./mydir/myfile.pdf', $pdf_string);
nick's example saves it to your localhost.
But you can also save it to your local drive.
if you use doublebackslashes:
$filename= "Invoice.pdf";
$filelocation = "C:\\invoices";
$fileNL = $filelocation."\\".$filename;
$pdf->Output($fileNL,'F');
$pdf->Output($filename,'D'); // you cannot add file location here
P.S. In Firefox (optional) Tools> Options > General tab> Download >Always ask me where to save files
$pdf->Output( "myfile.pdf", "F");
TCPDF ERROR: Unable to create output file: myfile.pdf
In the include/tcpdf_static.php file about 2435 line in the static function fopenLocal if I delete the complete 'if statement' it works fine.
public static function fopenLocal($filename, $mode) {
/*if (strpos($filename, '://') === false) {
$filename = 'file://'.$filename;
} elseif (strpos($filename, 'file://') !== 0) {
return false;
}*/
return fopen($filename, $mode);
}
require __DIR__ . '/vendor/autoload.php';
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$html = '<h2>Welcome toTcpdf</h2>';
$html.= '<p>Welcome toTcpdf</p>';
//$pdf->writeHTML($tbl, true, false, true, false, '');
$pdf->writeHTML($html, true, false, false, false, '');
$time = time();
$sFilePath = __DIR__ . '/upload/'.$time.'.pdf' ;
$pdf->Output( $sFilePath , 'F'); // Save to folder
//$pdf->Output( $sFilePath , 'I'); // view to browser
//$pdf->Output( $sFilePath , 'D'); // Download instant
this is working
You may try;
$this->Output(/path/to/file);
So for you, it will be like;
$this->Output(/kuitit/); //or try ("/kuitit/")
This worked for me, saving to child dir(temp_pdf) under the root:
$sFilePath = $_SERVER['DOCUMENT_ROOT'] . '//temp_pdf/file.pdf' ;
$pdf->Output( $sFilePath , 'F');
Remember to make the dir writeable.

Categories