Wrote a custom module for Joomla. The user enters a file name in the text filed and the pdf file with the entered value as name should be downloaded. But when clicked the page is redirected to home page. Here's the code
$file = $_POST['posttext'] . '.' . 'pdf';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment;
filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
Tried adding ob_flush() as one of the asker suggested but no good. The code works perfectly as a separate php file.
Try the following
$app = JFactory::getApplication();
$file = $app->input->get('posttext') . '.pdf';
if (JFile::exists($file)) {
// File headers
header("Content-type: application/pdf");
header("Content-Disposition: attachment");
// File contents.
readfile($file);
}
If you are still having issues, you could check if the file exists in Joomla and download the file in a new tab/window using window.open()
Related
I am creating a resource site for my campus where teachers upload files to folder and reference of that filed stored in db, and students can download those files using download option in student view side, and all these I have done in codeigniter using model view controller.
I need help for coding to download files. I managed to display a set of files but could not download yet, can anyone please help me with this? I'll be so thankful.
Try this
$download_file = 'C:\example.zip';//path of the file
$content_type = mime_content_type($download_file);//mime type of the file
$file_name = basename($download_file);//file name
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: ".$content_type);
header("Content-Disposition: attachment; filename=\"".$file_name."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($download_file));
while (ob_get_level()) {
ob_end_clean();
}
readfile($download_file);
im making currently making my thesis about a record management of our university secretary.. in which all papers inside the office will be scanned and uploaded in the system.. i am using codeigniter..one of the feature in my system is to view the pdf file in other window of the browser. but my problem is, when i click the title. only blank page will be displayed in the other tab.. can you help me solve this one?? here is my code
controller:
function viewMinutesFile(){
if(isset($_GET['id'])){
$id = $_GET['id'];
$file = $this->minutes_model->getFile($id);
$fp= fopen($file->path, "r");
header("Cache-Control: maxage=1");
header("Pragma: public");
header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=".$file->filename."");
header("Content-Description: PHP Generated Data");
header("Content-Transfer-Encoding: binary");
header('Content-Length:' .filesize($file->path));
ob_clean();
flush();
while (!feof($fp)){
$buff = fread($fp,1024);
print $buff;
}
exit;
}
}
code to open the file: this is my syntax to be clicked by the user so that pdf file will be open in the new tab
File
index.php/admin/viewMinutesFile?
id=" target="_tab">
try this one with a static url. no need any extra words for that.
Show My Pdf
New Update
if its work for you then fetch pdf name from database and put the name in the view like
Show My Pdf
now in the controller
$this->load->helper('download');
if($this->uri->segment(3))
{
$data = file_get_contents('./file_path/'.$this->uri->segment(3));
}
$name = $this->uri->segment(3);
force_download($name, $data);
well, you could add a link to file with target="_blank", like
<a href="<?php echo base_url(). 'your_controller/viewMinutesFile'; ?>" target="_blank">
View Pdf
</a>
and in controller function:
function viewMinutesFile(){
....
$file = $this->minutes_model->getFile($id);
$this->output
->set_content_type('application/pdf')
->set_output(file_get_contents($your_pdf_file));
}
you can try this on your view :
Filename
and on your controller, you can try this, because this is works for me :
function viewfile(){
$fname = $this->uri->segment(3);
$tofile= realpath("uploaddir/".$fname);
header('Content-Type: application/pdf');
readfile($tofile);
}
hope this might help you...
Just create a link to a blank page and use this code in your controller:
public function myPdfPage(){
$url = base_url('assets/your.pdf');
$html = '<iframe src="'.$url.'" style="border:none; width: 100%; height: 100%"></iframe>';
echo $html;
}
Enjoy!
There is no any problem with your code you can open easily on next tab, like other pages only difference you have to change header description and it is make sure on your browser pdf reader add-ons are available, otherwise it will give you option to download.
You may just follow this.
<?php echo form_open_multipart('your_controller/your_function','target="_blank"') ;?>
//other input fields
<?php form_close();?>
I have download the package PHPWord_0.6.2_Beta.zip from this siteThere are 2 directory : Examples and PHPWord, and 1 file : PHPWord.phpI put PHPWord directory and PHPWord.php in application/third_party and create new library named 'Word.php' in application/libraries as explained in this articleHere is the new library code Word.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once APPPATH."/third_party/PHPWord.php";
class Word extends PHPWord {
public function __construct() {
parent::__construct();
}
}
?>
Now we can easily use PHPWord as CI libraryI have tried Text Example from directory Example in downloaded package, here is the original code
<?php
require_once '../PHPWord.php';
// New Word Document
$PHPWord = new PHPWord();
// New portrait section
$section = $PHPWord->createSection();
// Add text elements
$section->addText('Hello World!');
$section->addTextBreak(2);
$section->addText('I am inline styled.', array('name'=>'Verdana', 'color'=>'006699'));
$section->addTextBreak(2);
$PHPWord->addFontStyle('rStyle', array('bold'=>true, 'italic'=>true, 'size'=>16));
$PHPWord->addParagraphStyle('pStyle', array('align'=>'center', 'spaceAfter'=>100));
$section->addText('I am styled by two style definitions.', 'rStyle', 'pStyle');
$section->addText('I have only a paragraph style definition.', null, 'pStyle');
// Save File
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('Text.docx');
?>
And I tried implement it in my CI controller, here is the code PHPWord_Text.php
<?php if (!defined('BASEPATH')) exit ('No direct script access allowed');
class PHPWord_Text extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('word');
}
function index() {
$PHPWord = $this->word; // New Word Document
$section = $PHPWord->createSection(); // New portrait section
// Add text elements
$section->addText('Hello World!');
$section->addTextBreak(2);
$section->addText('I am inline styled.', array('name'=>'Verdana', 'color'=>'006699'));
$section->addTextBreak(2);
$PHPWord->addFontStyle('rStyle', array('bold'=>true, 'italic'=>true, 'size'=>16));
$PHPWord->addParagraphStyle('pStyle', array('align'=>'center', 'spaceAfter'=>100));
$section->addText('I am styled by two style definitions.', 'rStyle', 'pStyle');
$section->addText('I have only a paragraph style definition.', null, 'pStyle');
// Save File / Download (Download dialog, prompt user to save or simply open it)
$filename='just_some_random_name.docx'; //save our document as this file name
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document'); //mime type
header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('php://output');
}
}
?>
Access it in
http://localhost/codeigniter/index.php/PHPWord_Text
Foilaa!!! my code works! But... I'm a bit confused when i tried to translate Template Example in directory Examples from downloaded package into a new CI controller, here is the original code of Template.php
<?php
require_once '../PHPWord.php';
$PHPWord = new PHPWord();
$document = $PHPWord->loadTemplate('Template.docx');
$document->setValue('Value1', 'Sun');
$document->setValue('Value2', 'Mercury');
$document->setValue('Value3', 'Venus');
$document->setValue('Value4', 'Earth');
$document->setValue('Value5', 'Mars');
$document->setValue('Value6', 'Jupiter');
$document->setValue('Value7', 'Saturn');
$document->setValue('Value8', 'Uranus');
$document->setValue('Value9', 'Neptun');
$document->setValue('Value10', 'Pluto');
$document->setValue('weekday', date('l'));
$document->setValue('time', date('H:i'));
$document->save('Solarsystem.docx');
?>
Can anyone please help me with this problem? please.. T_TNOTE : i dont want it to be saved in server, i want it to show download dialog prompt user wether to save it or open it, works like some code down here
// Save File / Download (Download dialog, prompt user to save or simply open it)
$filename='just_some_random_name.docx'; //save our document as this file name
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document'); //mime type
header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('php://output');
I think you may be experiencing more than one issue with Template.php.
First, you may be trying to figure out what it is doing.
With the other examples x.php produces x.docx. In the case of Template.php, it uses Template.docx to produce Solarsystem.docx.
The variables Value1, Value2, Value3, etc. are all defined within Template.docx as ${Value1}, ${Value2}, ${Value3}, etc. If you change the values on the right in Template.php, it will change the corresponding values in Solarsystem.docx.
Second, you seem to be concerned with output.
What works for me is this:
$filename = 'nameOfFile.docx';
$document->save($filename);
header('Content-Description: File Transfer');
header('Content-type: application/force-download');
header('Content-Disposition: attachment; filename='.basename($filename));
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($filename));
readfile($filename);
This way still saves it on the server but downloads it too. If I use both $document->save(); and $objWriter->save(); I get a blank document when I try to use readfile(); on the file saved by objWriter.
I thing this is correct :
$filename = 'nameOfFile.docx';
$document->save($filename);
header('Content-Description: File Transfer');
header('Content-type: application/force-download');
header('Content-Disposition: attachment; filename='.basename($filename));
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($filename));
readfile($filename);
unlink($filename);
Method save() of Template class returns name of temp file document, so you just give it to user with readfile($tempName);
I'm not sure I get your question correctly, so excuse me if I'm wrong.
In your 4th code block you've got a line
$document->save('Solarsystem.docx');
If you don't want to save the file to the local disk, but instead send it to the client, you'll just have to remove that line and add the code from the 5th code block:
// Save File / Download (Download dialog, prompt user to save or simply open it)
$filename='just_some_random_name.docx'; //save our document as this file name
header('Content-Type: application/vnd.openxmlformats- officedocument.wordprocessingml.document'); //mime type
header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('php://output');
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
require_once APPPATH . '/src/PhpWord/Autoloader.php';
use PhpOffice\PhpWord\Autoloader as Autoloader;
Autoloader::register();
When client request for a file, I use this code to send it:
public static Result download(String file) {
File file = getRealFile(file);
return Ok(file);
}
But I found the browser will not download it, but display its content instead. The response header:
Content-Type text/plain
Transfer-Encoding chunked
What's the correct way to send a file?
Update
Per Razvi's answer, I found an answer seems good for this question: https://stackoverflow.com/a/1074925/342235
But do we really have to set so many headers?
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$filepath");
header("Content-Type: mime/type");
header("Content-Transfer-Encoding: binary");
// UPDATE: Add the below line to show file size during download.
header('Content-Length: ' . filesize($filepath));
You need to set the Content-Disposition header. I believe the value of the header should be attachment. See Manipulating the response doc for this.
For play 2.0 the following works without explicitly setting the header:
ok(new FileInputStream(file))
Im trying to generate pdf using dompdf, how can I open the pdf in a new tab in a browser? Like, I Click A link for the PDF and it should open in a new tab, not save it automatically. I want to give the user a choice to save the file after seeing it first. how do i do that?
whenever i use $pdf->output at the end of the file, it does not change a thing, the file is still downloaded automatically.
please help. thanks.
Whether a PDF is downloaded or viewed in the browser depends on a couple of factors. One is your browser settings, but we have no control there. The second is how dompdf present the PDF to the browser. You can tell dompdf to offer the PDF for direct viewing using $dompdf->stream('my.pdf',array('Attachment'=>0));.
As far as opening in a new tab. That depends on how you are generating the PDF. But the simplest way it to provide a link with a target attribute.
I have a same problem into my site (http://www.pdfwebcreator.com)
My solution is:
$myfile = fopen($strFileName, "r") or die("Unable to open file!");
$fileSize = filesize($strFileName);
header("HTTP/1.1 200 OK");
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=\"temporaryPdf.pdf\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $fileSize);
echo fread($myfile, $fileSize);
}
I don't know if you got, but if you use false in this line:
$dompdf-> stream("pasta/doc/relatorio.pdf", array("Attachment" => false));
You can see the pdf in the browser.
Well that you can do with the ->stream(); at the end of the chain.
Example:
//Routes (web.php in case laravel version >= 5.4)
Route::get('/pdf', 'PdfController#pdfStream')->name('pdfStream');
//PdfController.php
public function pdfStream(Request $request) {
$data["info"] = "I is usefull!";
$pdf = PDF::loadView('whateveryourviewname', $data);
return $pdf->stream('whateveryourviewname.pdf');
}
//yourViewPage.blade.php
<a href="{{route("pdfStream")}}" target="_blank" > click me to pdf </a>
Here more information
Am still experimenting, but something like this works fine as well
$pdf->loadView('file/path', compact('values'));
return $pdf->stream();
With this you can add dynamic values to your pdf file page within the browser.