Zend PDF - want to open instead of saving - zend-framework

am generating pdf using Zend_pdf
its saving after creating
I want to open it instead of saving.
When i access the url directly

Use render() method
// Set PDF headers
header ('Content-Type:', 'application/pdf');
header ('Content-Disposition:', 'inline;');
// Output pdf
echo $pdf->render();

I couldn't find a way to open a PDF directly, so I did this instead:
<?php
// Save PDF into file
$oPdf->save("./pdfcache/filename.pdf");
// Set headers
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename=filename.pdf');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
ini_set('zlib.output_compression','0');
// Get File Contents and echo to output
echo file_get_contents("./pdfcache/filename.pdf");
// Prevent anything else from being outputted
die();
It's not perfect, but it does the job for me.

Related

How to create docx file and download it using PhpWord

Hi I always got error when trying to create docx file and I want to download it directly. My browser is stuck on ERR_INVALID_RESPONSE. I'm using CodeIgniter framework by the way. Here is the code.
<?php
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Writer\Word2007;
class Test extends MY_Controller{
public function create()
{
$phpWord = new PhpWord();
$section = $phpWord->addSection();
$section->addText('Hello World!');
$file = 'HelloWorld.docx';
header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="' . $file . '"');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$xmlWriter->save("php://output");
}
}
This code is just taken from the example in the PhpWord docs, but somehow it doesn't work. No error just ERR_INVALID_RESPONSE on the browser. What did I miss?
After a couple hours digging, I finally found the solution for my problem. The problem exists because it relates to temporary folder. So what I have to do is 1. setting the path where the file temporarily saved and 2. I have to tell Phpword that it should use that path to store generated file.
$path = './uploads/tmp'; // Set the temporary path
\PhpOffice\PhpWord\Settings::setTempDir($path); // Tell Phpword where the temporary path is
So this is the complete code
<?php
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Writer\Word2007;
class Test extends MY_Controller{
public function create()
{
$phpWord = new PhpWord();
$section = $phpWord->addSection();
$section->addText('Hello World!');
$path = './uploads/tmp'; // Set the temporary path
\PhpOffice\PhpWord\Settings::setTempDir($path); // Tell Phpword where the temporary path is
$file = 'HelloWorld.docx';
header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="' . $file . '"');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$xmlWriter->save("php://output");
}
}
Hope it can help those who get the same problem

OG Tags via php

I'm trying to make a very simple game.
a) I let the user input his name;
b) I put this name in a canvas;
c) I generate an image (base64) whit canvas.toDataRL() and I create an image file sending the base64 URI to a php file. I'm doing it with this code:
JAVASCRIPT:
var canvas = document.getElementById("myCanvas");
var dataURL = canvas.toDataURL("image/jpeg", 0.2);
//console.log(dataURL);
// post the dataUrl to php
$.ajax({
type: "POST",
url: "upload.php",
data: {image: dataURL}
}).done(function( respond ) {
console.log(respond);
});
UPLOAD.PHP
<?php
if ( isset($_POST["image"]) && !empty($_POST["image"]) ) {
$dataURL = $_POST["image"];
$parts = explode(',', $dataURL);
$data = $parts[1];
$data = base64_decode($data);
// create a temporary unique file name
$file = "img/" . UPLOAD_DIR . uniqid() . '.png';
// write the file to the upload directory
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save this image.';
}
?>
d) Now I'd like to use this image that I've created to set the og:image tag (to share it on Facebook)! How can I do? I've honestly no idea.
Thank you!
Maybe in the OG you can put the link with <?php echo $file; ?>
I've found out the solution.
I pass the respond via get to another php page that catch the get parameter and put it in the og:image'content part.
You can debug your OG markup here: https://developers.facebook.com/tools/debug/
General information about open graph markup: https://developers.facebook.com/docs/sharing/webmasters#markup

Remove gzip encoding in Zend

Lots of questions here from people trying to implement gzip encoding in Zend - I need to do the opposite!
I have a controller which extends the standard Zend_Controller_Action. My downloadAction has a PDF file as it's response body. That works well, except that the downloaded file isn't correctly recognised by the client browsers.
The downloaded file is identified as a 'Zip Archive' by the browser download. When saved and double-clicked it opens correctly as a PDF. The response header shows Content-Encoding:gzip, so I figure that's likely the culprit.
The core of my action is:
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
if ($fd = fopen($pdfpath.$pdf->Filename,'r'))
{
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="summary.PDF"');
while(!feof($fd))
{
$buffer = fread($fd, 2048);
echo $buffer;
}
fclose($fd);
}
There is some other code before this piece, but it does nothing more exciting than populate the variables.
How would I go about disabling the Content-Encoding:gzip header for just this response, or if that's the wrong end of the stick (it would be good to use compression, but not at the expense of user experience), how do I get the client to correctly identify the downloaded file once the compression has been reversed?
I would recommend to use framework's Zend_Controller_Response_Http instead of header() function, usually I specify "default" headers with gzip compression etc. in my Bootstrap for all responses, and override them in actions for some special reasons:
public function indexAction()
{
$frontContoller = $this->getFrontController();
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$response = new Zend_Controller_Response_Http();
$response
->setHeader('Content-Type', 'application/pdf')
->setHeader('Content-Disposition', 'attachment; filename=summary.pdf')
->setHeader('Expires', ''.gmdate('D, d M Y H:i:s', strtotime('31.08.1986')) . ' GMT', true)
->setHeader('Cache-Control', 'no-cache')
->setHeader('Pragma', 'no-cache', true);
$response->setBody(file_get_contents('/full/path/to/summary.pdf'));
$frontContoller->setResponse($response);
}

Downloading files with Zend Framework

I'm a newbie to Zend Framework and I have such problem. On my web page I have the demos of products to be downloaded by users. When they want to download them, they have to fill the form (name, company, e-mail, contact phone) and then click Submit to start downloading. I would like them to be redirected to the product page. Here is my showFormAction code in controller:
if ($this->_request->isPost())
{
if (!$form->isValid($this->_request->getPost()))
{
//shows messages and the form again
}
else
{
$file = $this->findYoungestFile('/demo/'.$product.'/');
$this->sendFileToClient($file);
$this->_redirect('/products/'.$product);
//sending mail
$infoMail = new InfoMail($this->_request->getPost(), 'download', $product);
$this->sendInfoMails($infoMail);
}
}
else
//show form
And here is sendFileToClient function
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
The redirection doesn't work. I suppose there is a problem with headers sent to the browser, but I don't know how to solve it. Could anyone help me, please?
Thanks & regards,
Malgorzata
By the time you're trying to redirect user to another page the HTTP-headers had already sent. In other words you cannot supply a file and do a redirect at the same time. Well, at least the way you're trying to do this.

ZEND - Issue with download file (encoding, not able to open downloaded file)

I made a download form in my project, but problem is when i download the file and im trying to open it, Zend renderer is adding to it my layout html code... I read that i have to disable renderer and layout. But the problem is tjat i have to do this in my own helper, not in controller file, cause i need to have download in that helper file.
My download function is something like this:
<?php
class Zend_View_Helper_EditArticles extends Zend_View_Helper_Abstract
{
public function EditArticles()
{
//some code here, getting data from db table
//and now the download
if (isset($_POST['downloadarticle' . $i])) {
//this is probably bad and its not working as it should
//(?)Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setNoRender(true);
//(?)Zend_Controller_Action_HelperBroker::getStaticHelper('layout')->disableLayout();
$targetPath = $_SERVER['DOCUMENT_ROOT'] . '/articles/';
$file = $articles->GetArticleToDownload($_POST['art_id' . $i]);
$name = $file['name'];
$path = $file['path'];
$getfile = str_replace('//', '/', $targetPath) . $path . '.pdf';
$size = $file['size'];
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=$name.pdf");
header("Content-length: $size");
header('Content-Transfer-Encoding: binary');
readfile($getfile);
break;
}
}
echo $this->view->partial('/index/index.phtml','EditArticles');
And when I download the PDF, Adobe Reader can't open it (when I download other files they can't be opened either). I opened them with notepad and before the PDF content there was a lot of HTML layout code... What am I doing wrong?
In Adobe Reader I get this message:
Adobe Reader could not open 'filename.pdf' because it is either not a supported file type or because the file has been damaged for example, it was sent as an email attachment and wasn't correctly decoded).
That code does not belong in a view helper. It belongs in the controller or maybe an action helper.
Something like this in your controller should work:
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
// ...
$this->getResponse()
->setHeader('Content-Description', 'File Transfer', true)
->setHeader('Content-Type', 'application/pdf', true) // change to application/pdf
->setHeader('Content-Disposition', "attachment; filename={$name}.pdf", true)
->setHeader('Content-length', $size, true)
->setHeader('Content-Transfer-Encoding', 'binary', true)
->appendBody(readfile($getfile));
The following 2 lines of code should accomplish what you need and do it in a fashion that works from anywhere in your Zend application.
Zend_Layout::getMvcInstance()->disableLayout();
Zend_Controller_Front::getInstance()->setParam('noViewRenderer', true);