Creating pdf in symfony 2.3.* - php

I have searched for creating pdf file in symfony 2.3 but was not successful. I've got 2 bundle
Knp snapy bundle and another is
psliwa / PHPPdf
My task is just download pdf file on click. For this I have given the link in html.twig like
Download file
In pdf action I am generating the PDF file
In knp snapy bundle I am doing:
$html = $this->renderView('MyBundle:Foo:bar.html.twig', array(
'some' => $vars
));
return new Response(
$this->get('knp_snappy.pdf')->getOutputFromHtml($html),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="file.pdf"'
)
);
And got error
The exit status code '1' says something went wrong: stderr: "The
system cannot find the path specified.
Is wkpdftohtml necessary for installation if YES then how can I install on sharing based hosting.
In psliwa / PHPdf I have read the example from:
psliwa/PdfBundle
psliwa/PHPPdf
and got
unable to find twig file
If I change the $format = $this->get('request')->get('_format'); to $format='pdf'; then it show simple html file.
Unable to understand what should I do for completion of task...

Yes. For Knp Snappy Bundle, wkhtmltopdf is required and you need to configure it properly in the config.yml
knp_snappy:
pdf:
enabled: true
binary: /usr/local/bin/wkhtmltopdf #path to wkhtmltopdf binary
options: []

This is an excerpt from a controller in a live shared host environment using psliwa/PHPPdf:
$facade = $this->get('ps_pdf.facade');
$response = new Response();
$this->render('ManaClientBundle:Contact:roster.html.twig', array(
'date' => $found['latestDate'],
'center' => $location,
'roster' => $found['contactSet'],
), $response);
$date = new \DateTime($found['latestDate']);
$filename = str_replace(' ', '', $location) . date_format($date, '_Ymd') . '.pdf';
$xml = $response->getContent();
$stylesheet = $this->renderView('ManaClientBundle:Contact:contact.xml.twig', array());
$content = $facade->render($xml, $stylesheet);
return new Response($content, 200, array
('content-type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename=' . $filename
));

Related

WOPI Host in PHP - Not able to view file

I have implemented APIs which are required for WOPI Host, as I am trying to solve Viewing doc problem right now, I implemented CheckFileInfo and GetFile endpoints only.
/wopi/files/{fileId}
$filePath = public_path('sample.docx');
$handle = fopen($filePath, "r");
$size = filesize($filePath);
$contents = fread($handle, $size);
return [
"BaseFileName" => "sample.docx",
"Size" => $size,
"OwnerId" => 1,
"UserId" => 1,
"Version" => rand(),
"FileUrl" => url("sample.docx")
];
/wopi/files/{fileId}/contents
$file = public_path('sample.docx');
return new BinaryFileResponse($file);
BinaryResponse is from - Symfony\Component\HttpFoundation\BinaryFileResponse
I have tried multiple implementations to return "the full binary contents of the file" (To satisfy this: https://wopi.readthedocs.io/projects/wopirest/en/latest/files/GetFile.html)
But I always end up with the following error.
Side Note: We registered with Cloud Storage Program of Microsoft, with domain www.**world.com, and I hosted the app at test-wopi.**world.com

Zend Framework CSV download

I am currently working on a CSV generator in Zend Framwork. At this point I am able to create a valid CSV file on the server side and now I want to download that file. I am currently using the following code:
$reader = new \PHPExcel_Reader_CSV();
$reader->setReadDataOnly(true);
$excel = $reader->load($file); //$file = Path of the csv file in the local storage
$writer = \PHPExcel_IOFactory::createWriter($excel, 'CSV');
$path = 'public/download';
$fileName = 'test.csv';
$writer->save($path . '/' . $fileName);
$response = new ResponseStream();
$response->setStream(fopen($path . '/' . $fileName, 'r'));
$headers = new Headers();
$headers->addHeaders([
'Content-Type' => [
'application/force-download',
'application/octet-stream',
'application/download'
],
'Content-Length' => filesize($path . '/' . $fileName),
'Content-Disposition' => 'attachment;filename=' . $fileName,
'Cache-Control' => 'must-revalidate',
'Pragma' => 'no-cache',
'Expires' => 'Thu, 1 Jan 1970 00:00:00 GMT'
]);
$response->setHeaders($headers);
$cookie = new SetCookie('downloadComplete', 'true', time() + 60 * 60, '/');
$response->getHeaders()->addHeader($cookie);
$response->setContent($writer);
return $response;
The problem is now that I only get a Zend error popup:
statusCode 200 thrownError SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 21 of the JSON data
And the content of my CSV as response text.
Do you have an idea?
Thanks in advance.
After a lot of investigation I found out that the download only fails if we send a Post request to the download action via zend (I assume it overrides the self-setted headers). So I sendt the request via a java script redirect ($viewModel->addScriptBlock('window.location = "Your URL";');) and it worked.

Two FileNotFoundException-s when trying to download

So i'm using Laravel for a while. I wrote this:
public function downloadUserFile(){
$result = $_POST['filename'];
$entry = File::where('filename', '=', $result)->firstOrFail();
$file = Storage::disk()->get(storage_path($entry->filePath));
$headers = array('Content-Disposition' => 'attachment; filename="'.basename($entry->filePath).'"', 'Content-Type' => $entry->mimetype );
return (new Response($file, 200))->header($headers);
}
With the hope that I can download a selected file. Well I get two exceptions in FilesystemAdapter.php line 58 and in Filesystem.php line 381: File not found at path: C:\xampp\htdocs\bluedrive\drive\storage\uploads\1\SHTURCITE - Ti I Az.mp3 ---- This file is in the directory and i can't understand why laravel can't find it.

Server send a image as response and rename it before serving - Symfony 2

I want to serve a image as Response in Symfony 2.3.16
So I'm doing this in my action:
$image = $this->getDoctrine()->getRepository('MakoBackendBundle:Image')->find($id);
if($image !== null) {
/** #var $image Image */
$info = getimagesize($image->getAbsolutePath());
$content = file_get_contents($image->getAbsolutePath());
return new Response($content, 200, array(
'Content-Type' => $info['mime'],
'Content-Length' => strlen($content),
'Content-Disposition' => 'attachment;'
));
}
return new Response();
My question is how can I serve this image with a different name, like a time based hash or something? I want to serve it with a different name than it is stored on the server-side.
Symfony2 has a helper for this. This is from the documentation.
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
$d = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT, // disposition
'foo.pdf' // filename
);
$response->headers->set('Content-Disposition', $d);

Download file from Amazon S3 with Laravel

I'm a little sure as to how to launch a download of a file from Amazon S3 with Laravel 4. I'm using the AWS
$result = $s3->getObject(array(
'Bucket' => $bucket,
'Key' => 'data.txt',
));
// temp file
$file = tempnam('../uploads', 'download_');
file_put_contents($file, $result['Body']);
$response = Response::download($file, 'test-file.txt');
//unlink($file);
return $response;
The above works, but I'm stuck with saving the file locally. How can I use the result from S3 correctly with Response::download()?
Thanks!
EDIT: I've found I can use $s3->getObjectUrl($bucket, $file, $expiration) to generate an access URL. This could work, but it still doesn't solve the problem above completely.
EDIT2:
$result = $s3->getObject(array(
'Bucket' => $bucket,
'Key' => 'data.txt',
));
header('Content-type: ' . $result['ContentType']);
header('Content-Disposition: attachment; filename="' . $fileName . '"');
header('Content-length:' . $result['ContentLength']);
echo $result['Body'];
Still don't think it's ideal, though?
The S3Client::getObject() method allows you to specify headers that S3 should use when it sends the response. The getObjectUrl() method uses the GetObject operation to generate the URL, and can accept any valid GetObject parameters in its last argument. You should be able to do a direct S3-to-user download with your desired headers using a pre-signed URL by doing something like this:
$downloadUrl = $s3->getObjectUrl($bucket, 'data.txt', '+5 minutes', array(
'ResponseContentDisposition' => 'attachment; filename="' . $fileName . '"',
));
If you want to stream an S3 object from your server, then you should check out the Streaming Amazon S3 Objects From a Web Server article on the AWS Developer Guide
This question is not answered fully. Initially it was asked to how to save a file locally on the server itself from S3 to make use of it.
So, you can use the SaveAs option with getObject method. You can also specify the version id if you are using versioning on your bucket and want to make use of it.
$result = $this->client->getObject(array(
'Bucket'=> $bucket_name,
'Key' => $file_name,
'SaveAs' => $to_file,
'VersionId' => $version_id));
The answer is somewhat outdated with the new SDK. The following works with v3 SDK.
$client->registerStreamWrapper();
$result = $client->headObject([
'Bucket' => $bucket,
'Key' => $key
]);
$headers = $result->toArray();
header('Content-Type: ' . $headers['ContentType']);
header('Content-Disposition: attachment');
// Stop output buffering
if (ob_get_level()) {
ob_end_flush();
}
flush();
// stream the output
readfile("s3://{$bucket}/{$key}");

Categories