I want to use tFPDF in Laravel 5.5. I added the package with composer and then I tried to output it the according to the docs but nothing worked.
I tried to output it directly to the browser:
Route::get('/test',function(){
$pdfLibrary = new tFPDF\PDF();
$pdfLibrary->AddPage();
$pdfLibrary->AddFont('DejaVuSansCondensed', '', 'DejaVuSansCondensed.ttf', true);
$pdfLibrary->SetFont('DejaVuSansCondensed', '', 14);
$pdfLibrary->Write(8, 'Hallo!');
$pdfLibrary->output();
});
but the sceen was just blank. When I tried return $pdfLibrary->output();
then it just returned
%PDF-1.3 3 0 obj <> endobj 4 0 obj <> stream x�u�� �#S�)>+�p�.......
I also tried to simply save the pdf to a file, but even
$pdfLibrary->output('F', storage_path() . '/test.pdf');
did not work.
How can I save & output the pdfs created by tFPDF ?
I found another package from SetASign which is just want I wanted. Simple tFPDF packge with namespace support. This works out of the box and is amazing.
I would strongly recommend to use the SetASing package over the DocNetUk package, because the DocNetUK package has just to many quirks. Here are some of the issues that I had using the DocNetUK package:
Output returns raw binarys, see below how to work with it
Renaming font names does not work.
method tFPDF was changed to __construct, so you have to call parent::construct in your constructor each time, which was necessary because of the namespacing(see What's difference between __construct and function with same name as class has?)
The variable names have been changed randomly and there are no docs for it:
$this->w =>$this->flt_current_width
$this->h =>$this->flt_current_height
These changes make the version from DocNetUK incompatible with basically all add-ons.
*Outdated answer
I finally realized that the unofficial composer version of tFPDF changed slightly the behavior of the output function. The output functions just returns the pdf content, but cannot save it to a file nor render it directly in the browser.
This is how to display raw binarys as a pdf in Laravel
\Response::make($this->output(), 200, ['content-type'=>'application/pdf', 'Content-Disposition' => 'inline; temp.pdf']);
Saving raw binaries goes like this:
Storage::put('file.pdf', $pdfLibrary->output());
or file_put_contents if one is not using Laravel.
Related
I'm trying to fill a pdf and save it using php. I'm also tried FPDF this script but its throws a error FPDF-Merge Error: Object streams are not supported. After I'm also tried php-pdftk package. I'm using ubuntu 20.04 so there no instruction to found install pdftk server for Ubuntu on there website. I'm install it using method 3 of this web site given Pdftk ubuntu install bleow is my code after configure pdftk
$pdf = new Pdf(public_path().'/test.pdf');
$result = $pdf->fillForm([
'name_field'=>'hello',
])
->flatten()
->saveAs(public_path().'/filled.pdf');
// Always check for errors
$error ='';
if ($result === false) {
$error = $pdf->getError();
}
return response()->json($error, 200);
this result always return false and error message is empty.
Can any one help me to figure this out if I'm done anything wrong or Is there any better solution for fill PDF form?
Thank you.
Change ->flatten() to needAppearances().
Note: When filling in UTF-8 data, you should always add the needAppearances() option. This will make sure, that the PDF reader takes care of using the right fonts for rendering, something that pdftk can't do for you. Also note that flatten() doesn't really work well if you have special characters in your data.
https://github.com/mikehaertl/php-pdftk
I have been trying to find a simple way to create OpenOffice calc files with no success.
I have tried:
openTBS - Seems to work writing an xml and a template file but can't find anything about how the xml file format.
Ods php generator - I tried this one as it provides clear examples, but when I copy the files to my server I always get corrupted files
Php doc writer - Tried an example and got an sxw file. I don't even know what that is
ODS-PHP - No documentation, only one example for creating 4 cells
Everything looks old, stalled and undocumented. ¿Any suggestion?
I have used opentbs successfully.
You can generate both excel and calc files. It also nice that you can "reuse" your html implementation so to speak.
Maybe this thread could get you going http://www.tinybutstrong.com/forum.php?thr=3069
Do the html version first.. then edit for calc/excel
Spout from Box works well enough for me. There are some missing features but it is simple to use, has a fluent API, and has no dependencies (it supports composer but you can use it standalone and its dependency graph has zero depth 😉 ).
Here's my "array of objects to ODS" pipeline, using Spout:
(I'm not using their recommended use import because all this code fits in a much larger file that I didn't want to contaminate and the $factory pattern looks cleaner to me anyway)
$factory = 'Box\Spout\Writer\Common\Creator\WriterEntityFactory';
$factory::createODSWriter()
->openToBrowser('filename.ods')
->addRow($factory::createRow([
$factory::createCell(__('Heading 1')),
$factory::createCell(__('Heading 2')),
$factory::createCell(__('Heading 3')),
]))
->addRows(array_map(function($row) use ($factory) {
return $factory::createRow([
$factory::createCell($row->first_val),
$factory::createCell($row->second_val),
$factory::createCell($row->third_val),
]);
}, loadDataFromSomewhere()))
->close();
I am trying to make a download action that downloads a Word doc generated in the 'download' controller using PHPDOCX. So far PHPDOCX is able to save the desired .docx file in the correct folder, but something goes wrong when I try to download it. Since Media Views were deprecated, I must use the CakeResponse file method as suggested in the CakePHP 2.x Cookbook:
// In the controller:
$this->response->file($file['path'], array('download' => true, 'name' => $filename));
return $this->response;
I was able to use this method for to export an RTF with no problem (the RTF was generated using PHPRTFLite), but when I use the method for a .docx file using PHPDOCX I receive the following error in Firefox:
The character encoding declaration of the HTML document was not found
when prescanning the first 1024 bytes of the file. When viewed in a
differently-configured browser, this page will reload automatically.
The encoding declaration needs to be moved to be within the first 1024
bytes of the file.
I would like to use a document generator that accepts HTML, which is why I chose PHPDOCX. Considering the above error, I set off to define the headers and content-type using the following method:
$this->response->header(array('Content-type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document'));
But I still receive the same error in CakePHP:
The requested file APP/files/info_sheets/filename.docx was not found or not readable
One thing I was thinking is that PHPDOCX sends many errors when it generates the document and this is interfering with the Mime-type or encoding. But according to the 2.x Cookbook:
Headers are not sent when CakeResponse::header() is called either.
They are just buffered until the response is actually sent.
Another idea is that I need to set the character encoding in the header right after the content-type:
$this->response->header(array('Content-type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'));
But this results in garbled text.
Does anyone have any ideas how to resolve this? The "download.ctp" view file is currently blank. Please let me know if you need additional information about this issue.
Thanks!
Chris
First of all, you might try to disable autoRender, otherwise CakePHP might still try to render your view and layout;
$this->autoRender = false;
Also, haven't tested it, but have you tried this to set the header:
// register the type
$this->response->type(array('docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'));
// set the type for the response
$this->response->type('docx');
See the documentation:
http://book.cakephp.org/2.0/en/controllers/request-response.html#dealing-with-content-types
You can modify the media.php file in the core of the framework and add the mime-type to the array that have the types.
Eg:
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
I have a quite complicated HTML/CSS layout which I would like to convert to PDF on my server. I already have tryed DOMPDF, unfortunately it did not convert the HTML with correct layout. I have considered HTMLDOC but I have heard that it ignores CSS to a large extent, so I suppose the layout would break apart with that tool too.
My question therefor is - are there any online demos for other tools (like wkhtmltopdf i.e.) that I could use to verify how my HTML is converted? Before spending the rest of my life installing & testing one by one?
Unfortunately, I can't change the HTML layout to fit those tools. Or better said - I could, if any of them would get close to an acceptable result...
Not really an answer but for the question above, but I'll try to provide some of my experience, maybe it will help someone somwhere in the future.
wkthmltopdf is really THE ONLY solution that worked for me that could produce what I call acceptable results. Still, some minor modifications to the CSS had to be made, however, it worked really well when it comes to rendering the content. All the other packages are really only suitable if you have a rather simply document with one basic table etc. No chance to get them to produce fair results on complex docs with design elements, css, multiple overlapping images etc. If complex documents are in game - do not spend the time (like I did) - go straight to wkhtmltopdf.
Beware - the wkhtmltopdf installation is tricky. It was not so easy for me as the guys said in their comments (one of the reasons might be that I am not too familiar with Linux). The static binary did not work for me for some reason I can't explain. I suspect that there were problems with the version - apparently there is a difference between versions for different OS and processors, maybe I have the vrong version. For installing the non-static version first of all you have to have root access to the server, that's obvious. I installed it with apt-get using PuTTy, went quite well. I was lucky that my server already had all the predispositions to install wkhtmltopdf. So this was the easy part for me :) (btw, you don't have to care for symbolic links or wrappers as many tutorials tell you - I spent hours trying to figure out how to do that part, in the end I gave it up and everything works well though)
After the install I got the quite famous Cannot connect to X server error. This is due to the fact that we need to run wkhtmltopdf headless on a 'virtual' x server. Getting around this was also quite simple (if one does not care for the symbolic links). I installed it with apt-get install xvfb. This also went quite well for me, no problems.
After completing this I was able to run wkhtmltopdf. Beware - it took me some time to figure out that trying to run xvfb was the wrong way - instead you have to run xvfb-run. My PHP code now looks like this exec("xvfb-run wkhtmltopdf --margin-left 16 /data/web/example.com/source.html /data/web/example.com/target.pdf"); (notice the --margin-left 16 command line option for wkhtmltopdf - it makes my content more centered; I left it in place to demonstrate how you can use command line options).
I also wanted to protect the generated PDF files from editing (in my case, print protect is also possible). After doing some research I found this class from ID Security Suite. First of all I have to say - IT'S OLD (I am running PHP 5+). However, I made some improvements to it. First of all - it's a wrapper around the FPDF library, so there is a file called fpdf.php in the package. I replaced this file from the latest FPDF version I got from here. It made my PHP warnings look more sustainable. I also changed the $pdf =& new FPDI_Protection(); and removed the & sign as I was getting an deprecated warning for it. However, there are more of those to come. Instead of searching and modifying the code I just turned the error reporting lvl to 0 with error_reporting(0); (although turning off the warnings only should be sufficient). Now someone will say that this is not "good practice". I am using this whole stuff on an internal system, so I do not really have to care. For sure the scripts could be modifiyed to match latest requirements. For me I didn't want to spend another hours working on it. Be careful where the script says $pdf->SetProtection(array('print'), '', $password); (I allowed printing my documents as you can see). It took me a while to figure out that the first argument is the permissions. The second is the USER PASSWORD - if you provide this then the docs will require a password to open (I left this blank). The third is the OWNER PASSWORD - this is what you need to make the docs "secured" against editing, copying etc.
My whole code now looks like:
// get the HTML content of the file we want to convert
$invoice = file_get_contents("http://www.example.com/index.php?s=invoices-print&invoice_no=".$_GET['invoice_no'];
// replace the CSS style from a print version to a specially modified PDF version
$invoice = str_replace('href="design/css/base.print.css"','href="design/css/base.pdf.css"',$invoice);
// write the modified file to disk
file_put_contents("docs/invoices/tmp/".$_GET['invoice_no'].".html", $invoice);
// do the PDF magic
exec("xvfb-run wkhtmltopdf --margin-left 16 /data/web/domain.com/web/docs/invoices/tmp/".$_GET['invoice_no'].".html /data/web/domain.com/web/docs/invoices/".$_GET['invoice_no'].".pdf");
// delete the temporary HTML data - we do not need that anymore since our PDF is created
unlink("docs/invoices/tmp/".$_GET['invoice_no'].".html");
// workaround the warnings
error_reporting(0);
// script from ID Security Suite
function pdfEncrypt ($origFile, $password, $destFile){
require_once('libraries/fpdf/FPDI_Protection.php');
$pdf = new FPDI_Protection();
$pdf->FPDF('P', 'in');
//Calculate the number of pages from the original document.
$pagecount = $pdf->setSourceFile($origFile);
//Copy all pages from the old unprotected pdf in the new one.
for ($loop = 1; $loop <= $pagecount; $loop++) {
$tplidx = $pdf->importPage($loop);
$pdf->addPage();
$pdf->useTemplate($tplidx);
}
//Protect the new pdf file, and allow no printing, copy, etc. and
//leave only reading allowed.
$pdf->SetProtection(array('print'), '', $password);
$pdf->Output($destFile, 'F');
return $destFile;
}
//Password for the PDF file (I suggest using the email adress of the purchaser).
$password = md5(date("Ymd")).md5(date("Ymd"));
//Name of the original file (unprotected).
$origFile = "docs/invoices/".$_GET['invoice_no'].".pdf";
//Name of the destination file (password protected and printing rights removed).
$destFile = "docs/invoices/".$_GET['invoice_no'].".pdf";
//Encrypt the book and create the protected file.
pdfEncrypt($origFile, $password, $destFile );
Hope this helps someone to save some time in the future. This whole solution took me like 12 hours to implement into our invoicing system. If there was better info on wkhtmltopdf for users like me, who are not that familiar with Linux/UNIX, I could have saved some of the hours spent on this.
However - what doesn't kill you makes you stronger :) So I am a bit more perfect now that I made this run :)
I want to generate a PDF that will contain an image.
so i already tried this line of codes:
$pdf->Image('b.png',10,8,33);
the other is:
$pdf->Image('Project_ITCPH\images.jpg', 1, 10, 5.8, 1.5);
the problem here is this Error:
"Deprecated: Function set_magic_quotes_runtime() is deprecated in C:\xampp\htdocs\Project_ITCPH\reports\fpdf.php on line 931
FPDF error: Alpha channel not supported: b.png"
is there a problem with the fpdf.php? i only use it as include.
You have my regards.
This error simply means that FPDF is using a function call that is deprecated and outdated. This is shown because your PHP displays errors and warnings and deprecation notes. You should try turning off errors before generating the PDF or writing # before function calls (like here) when using FPDF.
By the way, I highly recommend you use mPDF for PDF generation with PDF, it's better supported in my opinion.
Upgrade your FPDF to 1.7. It now supports alpha channel in PNGs.
Check out this class it lets you add images to PDF's with PHP it has a lot of demo's
https://github.com/dompdf/dompdf
Try
$pdf->Image('..\Project_ITCPH\images.jpg', 1, 10, 5.8, 1.5);
this is some time happen cause server could not find the folder path hope this work for u
also try this
require('fpdf.php');