Open PDF in a new tab using dompdf - dompdf

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.

Related

can't reach page while export pdf/downloading file in dompdf

I want to export data tables to PDF.
I'm using Codeigniter Framework, and use dompdf plugin.
I think the code is correct, because it doesn't show any error information when I click the button to export to PDF, the page spends a long time loading, and in the end, it just displays "can't reach the page".
This problem also happens when I try to download files from my local directory.
Here is the code:
actually issue happened when i try to download more number of records
The controller:
$this->load->library('pdf'); // change to pdf_ssl for ssl
$data = array();
$data['result'] = $finaldata;
$data['search_header'] = $search_header;
$html = $this->load->view('admin/report/school_pdf', $data, TRUE);
$this->pdf->create($html, $filename);

How to display PDF Documents on the browser using a View in Laravel 5.8

I'm working on a web application using Laravel 5.8, I'm new to Laravel framework. I would like to display PDF documents on the browser when users click on some buttons. I will allow authenticated users to "View" and "Download" the PDF documents.
I have created a Controller and a Route to allow displaying of the documents. I'm however stuck because I have a lot of documents and I don't know how to use a Laravel VIEW to display and download each document individually.
/* PDFController*/
public function view($id)
{
$file = storage_path('app/pdfs/') . $id . '.pdf';
if (file_exists($file)) {
$headers = [
'Content-Type' => 'application/pdf'
];
return response()->download($file, 'Test File', $headers, 'inline');
} else {
abort(404, 'File not found!');
}
}
}
/The Route/
Route::get('/preview-pdf/{id}', 'PDFController#view');
Mateus' answer does a good job describing how to setup your controller function to return the PDF file. I would do something like this in your /routes/web.php file:
Route::get('/show-pdf/{id}', function($id) {
$file = YourFileModel::find($id);
return response()->file(storage_path($file->path));
})->name('show-pdf');
The other part of your question is how to embed the PDF in your *.blade.php view template. For this, I recommend using PDFObject. This is a dead simple PDF viewer JavaScript package that makes embedding PDFs easy.
If you are using npm, you can run npm install pdfobject -S to install this package. Otherwise, you can serve it from a CDN, or host the script yourself. After including the script, you set it up like this:
HTML:
<div id="pdf-viewer"></div>
JS:
<script>
PDFObject.embed("{{ route('show-pdf', ['id' => 1]) }}", "#pdf-viewer");
</script>
And that's it — super simple! And, in my opinion, it provides a nicer UX for your users than navigating to a page that shows the PDF all by itself. I hope you find this helpful!
UPDATE:
After reading your comments on the other answer, I thought you might find this example particularly useful for what you are trying to do.
According to laravel docs:
The file method may be used to display a file, such as an image or PDF, directly in the user's browser instead of initiating a download.
All you need to do is pass the file path to the method:
return response()->file($pathToFile);
If you need custom headers:
return response()->file($pathToFile, $headers);
Route::get('/show-pdf/{id}', function($id) {
$file = YourFileModel::find($id);
return response()->file(storage_path($file->path));
})->name('show-pdf');
Or if file is in public folder
Route::get('/show-pdf', function($id='') {
return response()->file(public_path().'pathtofile.pdf');
})->name('show-pdf');
then show in page using
<embed src="{{ route('show-pdf') }}" type="text/pdf" >

UploadFile callback is not being triggered in CKEditor

I am using latest Full CKEditor (4.5.3) with Office2013 style enabled.
I added filebrowserImageUploadUrl option here:
CKEDITOR.replace( 'news_content' ,
{
"filebrowserImageUploadUrl": "/path/to/script.php"
});
When an image is uploaded, backed is returning proper HTML and headers to CKEditor, but what it does - just displays that JavaScript code and doesn't actually trigger that. If I copy-paste that JS to the browser (Chrome) console - it works (switches tab to the first one and inputs the image).
Please find screenshot attached. What have I missed?
P.S> The first argument is taken from the Request when file is being uploaded, so in that case it's = 1 (it's not the issue :))
As it was guessed by #Wiktor the issue was in setting proper headers. I was almost there, setting wrong headers.
Right headers are obviously: "text/html" (not "plain/text", it recognizes it just as a text in this case)
$uploadResponse = new Response();
$uploadResponse->headers->set('Content-type', 'text/html');
$content = "<script type=\"text/javascript\">\n";
$content .= "window.parent.CKEDITOR.tools.callFunction(" . $funcNum . ", '/uploads/news_image/" . $response['uploadedName'] . "', '');\n";
$content .= "</script>";
$uploadResponse->setContent($content);

how to open pdf file to another tab in browser using codeigniter

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();?>

Preventing ajax-jquery loaded external file from caching in IE

I have this jquery script to call an external file. So far so good. The script is working fine, but as always IE makes what he wants. The external file that I load with this script (weather.php) is a file with real-time weather conditions data in it. Whit this script, I can refresh the div inside which is my weather.php file. And obviously I don't want IE to cache the data in this file. I want when someone click on button "REFRESH", the included page to be reloaded with the new data in it. In IE this doesn't happens because of the cache.
How can I change this script to not cache the div's content, or how can I say to my included file (weather.php) to do not cache it self?
This is the script:
function ajax_request() {
$('#column_weather').html('<img src="../images/home/ajax-loader.gif" width="16" height="11" style="vertical-align:middle;"/><b> Loading...</b>');
$('#column_weather').load("../includes/home/weather.php");
}
`
And that's how I call the script:
Refresh`
Put a random variable on your query String
$('#column_weather').load("../includes/home/weather.php?myRand=" + guid());
I would make random var return a guid
function s4() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
function() guid{
return s4()+s4()+"-"+s4()+"-"+s4()+"-"+s4()+"-"+s4()+s4()+s4();
}
Can't you just have proper caching instructions inside this weather.php file (to say not to cache it)
I would attach the current date and time as a GET parameter. Internet Explorer (and other browsers) view this information as critical to loading the page, just as any function returns a different value with different parameters. The trick is that you don't have to use the parameter. :)
$('#column_weather').load("../includes/home/weather.php?t=" + date());
Adding a random parameter to the end of the query URL will help, but try adding this to the beginning of weather.php:
<?php
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', FALSE);
header('Pragma: no-cache');
?>

Resources