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.
Related
I have created a php code to generate a PDF using mPDF. The code works correctly on the local. But on the server this error is shown:
Data has already been sent to output, unable to output PDF file
I searched over net and find these solution all from stackoverflow but non of them works. I tried all these solutions and no one works.
1- There is not output before $pdf->Output() like echo
2- I set ini_set("session.auto_start", 0); before creating PDF
3- I use ob_end_clean with include mPDF library
But when I change output parameter from $pdf->Output('file.pdf','D') to $pdf->Output('file.pdf','F'), the pdf is creating in the directory correctly. (D mean download the file and F means save file in directory)
Why mPDF can create PDF in the server but cannot send to browser and force file to be downloaded? Any suggestion for why file cannot be downloaded by D parameter?
Edit #1: The codes:
<?php
include "/DIR/cost/mpdf/vendor/autoload.php";
if (isset($_POST['hazine'])) {
try{
$mpdf = new \Mpdf\Mpdf();
$rand = rand();
$stylesheet1 = file_get_contents('/DIR/cost/style.css');
$mpdf->WriteHTML($stylesheet1, 1);
ob_start();
include "/DIR/cost/entere_data.php";
include "/DIR/cost/php.php";
ob_end_clean();
include '/DIR/cost/footer.php';
ob_end_clean();
$dir = '/DIR/DCC/DDC' . $rand . '.pdf';
$pdf_file = 'DDC' . $rand . '.pdf';
$mpdf->Output($pdf_file, 'D');
}
} catch(\Mpdf\MpdfException $e){
echo $e->getMessage();
}
}
include "/DIR/cost/form.php";
?>
This 3 includes: include "/DIR/cost/entere_data.php"; , include "/DIR/cost/php.php"; , include '/DIR/cost/footer.php'; are PDF file contents.
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);
}
I am working on a project in which a PDF file is to be generated.
I have used Google Chart API for generating different charts. I am using the TCPDF library for converting them into PDF but I am unable to embed these genearted graphs into the PDFs. I think TCPDF does not accept the contents written in the script tag. How can I overcome this problem?
I ran into the same problem except I was using FPDF.
At the end of the day, a PDF file contains static content, so Javascript is out of the question unfortunately. What I ended up doing:
I prepare the chart HTML + Javascript like always and write it to a HTML file in my temp directory. Then I use PhantomJS (http://phantomjs.org/) to create a screenshot of the page which I then include in my PDF (or anywhere, really).
The great thing: it works with ANY local HTML page. If you only have a URL, use file_get_contents() or cURL to retrieve its contents and write it to a local HTML file first.
The guts:
To start, download and extract phantomjs.exe to a directory your application can access. My example uses version 1.9.8 that I copied to lib/phantomjs in my application root.
I have a function that accepts a HTML file path as parameter and a set of PhantomJS options. I suggest adding it to a helper class.
function getHTMLImage($page, $options = array(), $js = null) {
// Prepare the PhantomJS directory that contains phantomjs.exe, e.g. lib or vendor
$phantomDir = $_SERVER['DOCUMENT_ROOT'] . '/lib/phantomjs/';
// Add the PhantomJS directory to the PATH
$origPath = str_replace('"', '', getenv('PATH'));
if (!in_array($phantomDir, explode('/', $origPath)))
putenv('PATH=' . $origPath . '/' . $phantomDir);
// PhantomJS requires a Javascript file to process the request. In case no Javascript processing file is given, use the default
if (is_null($js)) $js = $phantomDir . 'phantom.js';
// Prepare the PhantomJS call
$exec = 'phantomjs --ignore-ssl-errors=yes ' . $js . ' ' . escapeshellarg($page);
// Prepare the PhantomJS options, e.g. width and height
foreach ($options as $option) {
$exec .= ' ' . escapeshellarg($option);
}
// Call PhantomJS. To catch errors, call exec($exec . ' 2>&1', $output, $errorMsg);
exec($exec, $output);
// Decode and return the image data
return ($output ? base64_decode(reset($output)) : false);
}
The Javascript file (mine is called phantom.js and is placed in the same directory as phantomjs.exe):
args = require('system').args;
page = require('webpage').create();
// In this case, I expect these indexes to be the width and height of the chart
if (typeof args[2] !== undefined) {
page.viewportSize = {
width: args[2],
height: (typeof args[3] === undefined ? args[2] : args[3])
};
}
page.open(args[1], function() {
var base64 = page.renderBase64('png');
console.log(base64);
phantom.exit();
});
Call it like this:
// Make sure $width and $height are set, or exclude them altogether
$output = getHTMLImage($htmlPath, array($width, $height));
// Example output, you want to save the image and include it in your PDF file
header('Content-Type: image/png');
exit($output);
i want to delete my pdf file from server. my controller function looks like
function delete_pdf()
{
$id = (isset($_GET['id']) && $_GET['id']!='')?$_GET['id']:'1';
$user_email = $this->session->userdata('user_email');
$file = site_url('pdf files/'.$user_email.'/pdf #'. $id.'.pdf');
unlink($file);
}
when i echo $file;, it gives url http://localhost/my_site/pdf files/developer_team#gmail.com/pdf #4.pdf but the function not working to delete the pdf file.
I would appreciate for any help where i can delete my pdf files from server. thank you.
we can't delete file using URL. we need absolute path. try this-:
$file = FCPATH.'pdf files/'.$user_email.'/pdf #'. $id.'.pdf';
try to remove space in pdf #4.pdf in your url
http://localhost/my_site/pdf files/developer_team#gmail.com/pdf #4.pdf
You need the absolute path to the file, I mean something like this
/Users/me/..../my_sites/pdf
The path depends of where is your controller. I don't know how codeigniter works.
EDIT
$file = dirname(__FILE__). DIRECTORY_SEPARATOR .'..'. DIRECTORY_SEPARATOR .'..'. DIRECTORY_SEPARATOR .'pdf files/'.$user_email.'/pdf #'. $id.'.pdf';
It will give you this :
C:\xampp\htdocs\my_site\application\controllers\..\..\pdf files\developer_team#gmail.com\pdf #4.pdf
I am trying to upload a picture. I have Form_Zend and I use:
$image = new Zend_Form_Element_File('image');
$image->setLabel('Upload an avatar:')
->setMaxFileSize(8388608)
// ->setDestination('./usersImages')
->setDescription('Click Browse and choose an image');
$image->addValidator('Count', false, 1);
$image->addValidator('Size', false, 8388608);
$image->addValidator('Extension', false, 'jpg,jpeg,png,gif');
$this->addElement($image, 'image');
My controller action code:
if ($form->image->isUploaded()) {
$values = $form->getValues();
$source = $form->image->getFileName();
$extention = substr($source, strrpos($source, '.', -1));
$date = date('mdYhisa', time());
$new_image_name = 'avatar_' . $date . '_' . $idUser . $extention;
$destination = "C:\\xampp\\tmp\\Srututututut.png";
$image_saved = move_uploaded_file($source, $destination);
if ($image_saved) {
$data = array(
'img' => $new_image_name,
);
$userDT->update($data, 'id=' . $idUser);
}
}
}
But this move_uploaded_file is not returning nothing :/
What I have done:
Checked if the file is uploading - yes it is in: C:\xampp\htdocs\Story\public\usersImages (if I set destination in this form element) or
C:\xampp\tmp (if I dont set it)
I was wondering about access to this folders but if it save there this images I think it has rights but I set in the apache:
<Directory "C:/xampp/htdocs/Story/public/usersImages">
Allow from All
</Directory>
I was even tried use this function only in C:\xampp\tmp folder:
$source: C:\xampp\tmp\database.png
$destination: C:\xampp\tmp\Srututututut.png
And still nothing :/
Do You have any suggestions?
I think that the problem is with $source = $form->image->getFileName();. The reason is that it will return a name of the file uploaded rather than where it was uploaded to (i.e. its temporary localization).
Thus, I think your source should be as follows:
$fileInfo = $mainForm->image->getTransferAdapter()->getFileInfo();
$source = $fileInfo['image']['tmp_name'];
// to check if the source really points to the uploaded file.
var_dump(file_exists($source));
Ok,
I have no idea why this function is not working. I have changed my idea to set the $form->image destination first in the controller and then rename it and it is working.
Thanks for help guys ;D