Symfony & Phantom JS Bundle - Routing Error - php

I am using this Bundle to convert HTML to PDF files.
The actual conversion works, but I have a problem understanding the routing.
Here is my code:
/**
* #Route("/formulare/selbstauskunft/{keycode}", name="saPrint")
*/
public function saPrintAction(Request $request, $keycode)
{
$em = $this->getDoctrine()->getManager();
$sa = $em->getRepository('AppBundle:Selfinfo')->findOneBy(array(
'keycode' => $keycode,
));
if(count($sa) > 0){
$response = new Response(
$this->get('padam87_rasterize.rasterizer')->rasterize(
$this->renderView('default/formSAPrint.html.twig', array(
'selfinfo' => $sa,
))
),
200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="my.pdf"'
]
);
return $response;
}else{
return new Response("fail");
}
}
The bundle creates 2 files, rasterize-UNIQUEID.html and rasterize-UNIQUEID.pdf. The html file contains the correct output.
After the creation of the html file in /bundles/padam87rasterize/temp/ the second part of the script opens this file via an url call here.
Unfortunately the actual rendered page is a symfony error page, saying:
No route found for GET /bundles/padam87rasterize/temp/rasterize-UNIQUEID.html
What do I have to set in order to render the html file?

I think you actually have to create a separare route to render the html. As far as I can tell the rasterize function generates a pdf from the temporary html file (The key word being temporary).

Related

Laravel 8 download PDF with Livewire

On my page I am making an invoice that is fully compatible with Livewire. I use this package: https://github.com/LaravelDaily/laravel-invoices to generate my invoice and everything works fine. But their is one problem I ran into. I can't download my PDF with Livewire.
Here is a basic example to generate a PDF and download it:
public function invoice()
{
$customer = new Buyer([
'name' => 'John Doe',
'custom_fields' => [
'email' => 'test#example.com',
],
]);
$item = (new InvoiceItem())->title('Service 1')->pricePerUnit(2);
$invoice = Invoice::make()
->buyer($customer)
->discountByPercent(10)
->taxRate(15)
->shipping(1.99)
->addItem($item);
return $invoice->download();
}
Whenever I click on a button
<a role="button" class="pdf-download cursor-pointer" wire:click="invoice">download</a>
Nothing happens. So the problem is that Livewire doesn't support this download method. And this download method looks like this:
public function download()
{
$this->render();
return new Response($this->output, Response::HTTP_OK, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="' . $this->filename . '"',
'Content-Length' => strlen($this->output),
]);
}
$this->render(); Renders a template in a specific folder
Is their a work around for this? Where I can download my pdf with a template or maybe a different strategy. I allready tried one thing. I stored the invoice into a session, like so:
Session::put('invoice', $invoice);
Session::save();
And in a different controller I have.
if ($invoice = Session::get('invoice')) {
$invoice->download();
}
But that gives me this error:
serialization of 'closure' is not allowed
And I tried some stuff I found here: https://github.com/livewire/livewire/issues/483
But nothing works. Can someone give me a direction on where to look or how to fix this? Thanks!
return response()->streamDownload(function () use($invoice) {
echo $invoice->stream();
}, 'invoice.pdf');
Seems to do the trick.

Laravel - How to stop printing URL and load page content?

Today I face a strange problem (as I face this first time so it is a strange problem for me). After saving the content of a model I just write the following line of code return route('organization'); so that it will redirect to the naming route organization after saving the content.
Once the content of the organization model saves it just print the URL of the page http//xyz.laravel/organization rather than printing the content of the page itself!
When I manually type and hit the dashboard URL it surprisingly prints the dashboard URL rather than loading the dashboard content! like the below image:
Everything was working fine before I tried to store the content of that model. Once the content is stored the application starts strange behavior. Here is the code of that model:
public function store(Request $request)
{
$validated = $request->validate([
'organization_name' => 'required|unique:organizations|max:255',
'abn_number' => 'required',
'address_one' => 'required|max:100',
'state' => 'required',
'post_code' => 'required'
]);
// check organization exist or not
$org = Organization::where('organization_name', $request->organization_name)->get();
if( count( $org ) > 0 ) {
//
} else {
$organization = new Organization();
$organization->organization_name = $request->organization_name;
$organization->abn_number = $request->abn_number;
$organization->address_one = $request->address_one;
$organization->address_two = $request->address_two;
$organization->state = $request->state;
$organization->post_code = $request->post_code;
$organization->created_by = Auth::user()->id;
$organization->created_at = Carbon::now();
$organization->save();
return route('organization');
}
}
Can anyone tell me what's actually happen and how can I fix this issue?
return route('organization'); will generate the URL link to the route and print it
You can use
return redirect()->route('organization);
You can get more info from https://laravel.com/docs/8.x/redirects
This is because you are not redirecting to that route but you are returning route url as a string, to redirect a user to a named route you can use global redirect() helper as below
return redirect()->route('organization'); instead of return route('organization');
for more see
documentation

symfony 4 error when uploading file

I am trying to upload a file, very much following the instructions on Symfony's cookbook, but it doesn't seem to work.
The specific error is as follows, but the background reason is that the file as such does not seem to be ( or remain ) uploaded.
Call to a member function guessExtension() on string
As it happens, the file is momentarily created at upload_tmp_dir, but gets deleted almost immediately ( I know that 'cause I kept that directory visible on my Finder).
The file metadata is available on the var_dump($_FILES) command on the script below.
So, for some reason the file is being discarded which, I believe, causes the specific error seen above.
I believe $file ( from UploadedFile ), should receive the file as such, not the path to it, but not sure how to get there. Particularly is the file does not remain on upload_tmp_dir.
For information, I tried the upload in a plain PHP project I have and it works fine. The file remains in upload_tmp_dir till is moved elsewhere.
Thanks
Here is the controller:
class ApiUserXtraController extends Controller
{
public function UserXtraAction(Request $request, ValidatorInterface $validator) {
$is_logged = $this->isGranted('IS_AUTHENTICATED_FULLY');
if ($is_logged) {
$user = $this->getUser();
}
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository(UserXtra::class);
$userxtra = new UserXtra();
$form = $this->createFormBuilder($userxtra)
->add('imgFile', FileType::class, array('label' => 'file'))
->add('save', SubmitType::class, array('label' => 'Create Task'))
->getForm();
var_dump($_FILES); // outputs file metadata, ie, name, type, tmp_name, size
$form->handleRequest($request);
$userxtra->setUser($user);
if ($form->isSubmitted() && $form->isValid()) {
/**
* #var UploadedFile $file
* */
$file = $userxtra->getImgFile();
var_dump('file', $file);// outputs full path to upload_tmp_dir
$fileName = $this->generateUniqueFileName().'.'.$file->guessExtension(); // **THIS THROWS THE ERROR**
$file->move(
$this->getParameter('user_image_directory'),
$fileName
);
$userxtra->setImgFile($fileName);
//$data = json_decode($data);
return new JsonResponse(array(
'status' => 'ok',
'is_logged' => $is_logged,
));
}
return $this->render('upload.html.twig', array(
'form' => $form->createView(),
));
}
Maybe you are looking for something like
$form->getData('imgFile')->guessExtension();
instead?
Edit: Ah sorry, missed that you are assuming that $file = $userxtra->getImgFile(); actually gives back an UploadedFile object. Apparently that assumption is not correct, as the error you are seeing indicates that it gives back a string instead.
I've found the solution on this SO question.
The docs, or actually Symfony's cookbook, is wrong.
The line on my code above that states:
$file = $userxtra->getImgFile();
should be:
$file = $form->get('imgFile')->getData();

Download CSV from serverside to browser in Laravel 4

I'm using Laravel 4 framework, I have a function that creates a csv file called data_78888.csv the number 78888 changes everytime the function is run to generate a csv file. That function returns a string like that : "Download/78888"
The folder where my csv files are created is called "outputs" and is located in my project folder where the app folder is located to, (it is not in the public folder).
What I would like to do is to create a route that points to my Process controller like that :
Route::get('Download/{token}', array('uses' => 'ProcessController#downloadCSV'));
In my controller I would like to send that csv file to the browser to download it , I'm doing like that :
<?php
class ProcessController extends BaseController {
public function downloadCSV($token){
$fileToDownload = "data_".$token.".csv";
$filePath = "outputs/";
return Response::download($filePath, $fileToDownload, array(
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment;filename="'.$fileToDownload
));
}
}
The issue is that this is not working and I get an html file called 78888.htm and an error on the server.
How can I make this working please?
The path to the file has to include the name and file extension of the file.
So try this;
$fileToDownload = "data_".$token.".csv";
$filePath = base_path() . "outputs/" . $fileToDownload;
return Response::download($filePath, $fileToDownload, array(
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment;filename="'.$fileToDownload
));
Also make sure the file exists, before downloading.

Symfony2 - PdfBundle not working

Using Symfony2 and PdfBundle to generate dynamically PDF files, I don't get to generate the files indeed.
Following documentation instructions, I have set up all the bundle thing:
autoload.php:
'Ps' => __DIR__.'/../vendor/bundles',
'PHPPdf' => __DIR__.'/../vendor/PHPPdf/lib',
'Imagine' => array(__DIR__.'/../vendor/PHPPdf/lib', __DIR__.'/../vendor/PHPPdf/lib/vendor/Imagine/lib'),
'Zend' => __DIR__.'/../vendor/PHPPdf/lib/vendor/Zend/library',
'ZendPdf' => __DIR__.'/../vendor/PHPPdf/lib/vendor/ZendPdf/library',
AppKernel.php:
...
new Ps\PdfBundle\PsPdfBundle(),
...
I guess all the setting up is correctly configured, as I am not getting any "library not found" nor anything on that way...
So, after all that, I am doing this in the controller:
...
use Ps\PdfBundle\Annotation\Pdf;
...
/**
* #Pdf()
* #Route ("/pdf", name="_pdf")
* #Template()
*/
public function generateInvoicePDFAction($name = 'Pedro')
{
return $this->render('AcmeStoreBundle:Shop:generateInvoice.pdf.twig', array(
'name' => $name,
));
}
And having this twig file:
<pdf>
<dynamic-page>
Hello {{ name }}!
</dynamic-page>
</pdf>
Well. Somehow, what I just get in my page is just the normal html generated as if it was a normal Response rendering.
The Pdf() annotation is supposed to give the "special" behavior of creating the PDF file instead of rendering normal HTML.
So, having the above code, when I request the route http://www.mysite.com/*...*/pdf, all what I get is the following HTML rendered:
<pdf>
<dynamic-page>
Hello Pedro!
</dynamic-page>
</pdf>
(so a blank HTML page with just the words Hello Pedro! on it.
Any clue? Am I doing anything wrong? Is it mandatory to have the alternative *.html.twig apart from the *.pdf.twig version? I don't think so... :(
Ok I got it.
For some reason, the example that comes in the bundle documentation didn't work for me. Nevertheless, there is this class in de bundle: http://github.com/psliwa/PdfBundle/blob/master/Controller/ExampleController.php, where I could find an example that did work for me. This is the code that I finally used:
/**
* #Route ("/generateInvoice", name="_generate_invoice")
*/
public function generateInvoiceAction($name = 'Pedro')
{
$facade = $this->get('ps_pdf.facade');
$response = new Response();
$this->render('AcmeStoreBundle:Shop:generateInvoiceAction.pdf.twig', array("name" => $name), $response);
$xml = $response->getContent();
$content = $facade->render($xml);
return new Response($content, 200, array('content-type' => 'application/pdf'));
}
Next challenge: store that PDF into disk.
It's because you've missed the "_format" option in the URL.
$this->render() shouldn't be used with the #Template annotation. The #Template will serve the correct template's format depending of the _format parameter.
...
use Ps\PdfBundle\Annotation\Pdf;
...
/**
* #Pdf()
* #Route ("/pdf.{_format}", name="_pdf")
* #Template()
*/
public function generateInvoicePDFAction($name = 'Pedro')
{
return array('name' => $name);
}
Should work fine.

Categories