Good evening,
I would like to create a feature for my users that allows them to read a pdf file without downloading or printing it.
They will only be able to read the pdf file.
I tried pdf.js which did not work,
I also tried to convert my pdf to html via a script,
I also tried this php code but the download and print button appears:
<?php
// The location of the PDF file
// on the server
$filename = "/path/to/the/file.pdf";
// Header content type
header("Content-type: application/pdf");
header("Content-Length: " . filesize($filename));
// Send the file to the browser.
readfile($filename);
?>
Do you have any solutions or technologies to suggest to me,
I use PHP, HTML and JS.
Try this one:
<?php
// Store the file name into variable
$file = '/path/to/the/filename.pdf';
$filename = 'filename.pdf';
// Header content type
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
// Read the file
#readfile($file);
?>
PHP uses a standard code to display the pdf file in web browser. The process of displaying pdf involves location of the PDF file on the server and it uses various types of headers to define content composition in form of type, Disposition, Transfer-Encoding etc. PHP passes the PDF files to read it on the browser. Browser either shows it or download it from localhost server then display pdf.
Note: PHP is not actually reading the PDF file. It does not recognize File as pdf. It only passes the PDF file to the browser to be read there. If copy the pdf file inside htdocs folder of XAMPP then it does not need to specify the file path.
The php script you offered only can download the file. if you use php ,you can try the demo ,which is using pdf2text here
or try the method in this link read-pdf-files-with-php
Is there a way to force PDF files to open in the browser when the option "Display PDF in browser" is unchecked?
I tried using the embed tag and an iframe, but it only works when that option is checked.
What can I do?
To indicate to the browser that the file should be viewed in the browser, the HTTP response should include these headers:
Content-Type: application/pdf
Content-Disposition: inline; filename="filename.pdf"
To have the file downloaded rather than viewed:
Content-Type: application/pdf
Content-Disposition: attachment; filename="filename.pdf"
The quotes around the filename are required if the filename contains special characters such as filename[1].pdf which may otherwise break the browser's ability to handle the response.
How you set the HTTP response headers will depend on your HTTP server (or, if you are generating the PDF response from server-side code: your server-side programming language).
The correct type is application/pdf for PDF, not application/force-download. This looks like a hack for some legacy browsers. Always use the correct mimetype if you can.
If you have control over the server code:
Forced download/prompt: use header("Content-Disposition", "attachment; filename=myfilename.myextension");
Browser tries to open it: use header("Content-Disposition", "inline; filename=myfilename.myextension");
No control over the server code:
Use the HTML5 download attribute. It uses the custom filename specified on the view side.
NOTE: I prefer setting the filename on the server side as you may have more information and can use common code.
(I misread the question, the following answer is about forcefully downloading the file instead of opening it in the browser)
If you are using HTML5 (and I guess nowadays everyone uses that), there is an attribute called download.
For example,
<a href="somepathto.pdf" download="filename">
Here filename is optional, but if provided, it will take this name for the downloaded file.
EDIT
I know this is the opposite of what the question asked. I am keeping the opposite answer for those (like me) who came searching for the opposite question (Evidence: this answer has more upvotes then downvotes)
I had the same issue and most of the above answers should resolve your issue. Unfortunately, even if i was receiving the content-type & content-disposition headers in the response but still my pdf was being downloaded rather than viewed. After brainstorming and trying for many hours.
The Culprit was firefox, well in a way it was me. Nervous Laughter
By default, when you open a pdf file in firefox, it will provide you with a popup to either save the pdf file or to open it directly and there is also a check box which says do this action automatically from now on and guess who selected it.
Due to this mistake, my pdf was being downloaded rather than viewed, even if had all the required headers in response. This is a simple mistake but cost me a good amount of time.
To resolve this, just go to settings and search for applications and change pdf setting to whatever you need.
This is for ASP.NET MVC
In your cshtml page:
<section>
<h4><i class="fa fa-download"></i> #Model.Name</h4>
<object data="#Url.Action("View", "Document", new { id = #Model.GUID })" type="application/pdf" width="100%" height="800" class="col-md-12">
<h2>Your browser does not support viewing PDFs, click on the link above to download the document.</h2>
</object>
</section>
In your controller:
public ActionResult Download(Guid id)
{
if (id == Guid.Empty)
return null;
var model = GetModel(id);
return File(model.FilePath, "application/pdf", model.FileName);
}
public FileStreamResult View(Guid id)
{
if (id == Guid.Empty)
return null;
var model = GetModel(id);
FileStream fs = new FileStream(model.FilePath, FileMode.Open, FileAccess.Read);
return File(fs, "application/pdf");
}
While the following works well on firefox, it DOES NOT work on chrome and mobile browsers.
Content-Type: application/pdf
Content-Disposition: inline; filename="filename.pdf"
To fix the chrome & mobile browsers error, do the following:
Store your files on a directory in your project
Use the google PDF Viewer
Google PDF Viewer can be used as so:
<iframe src="http://docs.google.com/gview?url=http://example.com/path/to/my/directory/pdffile.pdf&embedded=true" frameborder="0"></iframe>
If you have Apache add this to the .htaccess file:
<FilesMatch "\.(?i:pdf)$">
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>
Oops, there were typing errors in my previous post.
header("Content-Type: application/force-download");
header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=\"".$name."\";");
If you don't want the browser to prompt the user then use "inline" for the third string instead of "attachment". Inline works very well. The PDF display immediately without asking the user to click on Open. I've used "attachment" and this will prompt the user for Open, Save. I've tried to change the browser setting nut it doesn't prevent the prompt.
for large files you need to get your output buffer started add :-
ob_start(); // at the start
..//your code
ob_clean();// at the end of you file
You can do this in the following way:
Open PDF
If the PDF file is inside some folder and that folder doesn't have permission to access files in that folder directly then you have to bypass some file access restrictions using .htaccess file setting by this way:
<FilesMatch ".*\.(jpe?g|JPE?G|gif|GIF|png|PNG|swf|SWF|pdf|PDF)$" >
Order Allow,Deny
Allow from all
</FilesMatch>
But now allow just certain necessary files.
I have used this code and it worked perfectly.
Open downloads.php from rootfile.
Then go to line 186 and change it to the following:
if(preg_match("/\.jpg|\.gif|\.png|\.jpeg/i", $name)){
$mime = getimagesize($download_location);
if(!empty($mime)) {
header("Content-Type: {$mime['mime']}");
}
}
elseif(preg_match("/\.pdf/i", $name)){
header("Content-Type: application/force-download");
header("Content-type: application/pdf");
header("Content-Disposition: inline; filename=\"".$name."\";");
}
else{
header("Content-Type: application/force-download");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$name."\";");
}
Here is another method of forcing a file to view in the browser in PHP:
$extension = pathinfo($file_name, PATHINFO_EXTENSION);
$url = 'uploads/'.$file_name;
echo '<html>'
.header('Content-Type: application/'.$extension).'<br>'
.header('Content-Disposition: inline; filename="'.$file_name.'"').'<br>'
.'<body>'
.'<object style="overflow: hidden; height: 100%;
width: 100%; position: absolute;" height="100%" width="100%" data="'.$url.'" type="application/'.$extension.'">
<embed src="'.$url.'" type="application/'.$extension.'" />
</object>'
.'</body>'
. '</html>';
Either use
<embed src="file.pdf" />
if embedding is an option or my new plugin, PIFF: https://github.com/terrasoftlabs/piff
If you link to a .PDF it will open in the browser.
If the box is unchecked it should link to a .zip to force the download.
If a .zip is not an option, then use headers in PHP to force the download
header('Content-Type: application/force-download');
header('Content-Description: File Transfer');
i have been working on a website which will allow users to upload and download files. The file is renamed on upload and stored on my server. But when it is downloaded, it has to be renamed i.e to its original name. Presently i am using the following to do so :
Download
But the "download" attribute does not work with firefox. Any alternative using javascript or jquery ? I am using php for server side.
Edit:
Thanks for the solution using php. But that is not what i am looking for. I am using a custom file viewer using javascript. On clicking the thumbnail of the file, the viewer is displayed. An AJAX request is sent to get the link to the file. The response (the link) is used to display the file, also is added to the tag for download. A php solution would mean a page reload on every request, which i want to avoid. So any javascript or jquery solutions ?
On the server use header("Content-Disposition: attachment; filename='Original name'")
Try Below Code
header('Content-Disposition: attachment; filename='.basename('newfilename.txt'));
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize('filename.txt'));
ob_clean();
flush();
readfile('filename.txt');
Let's say that I have some URL to an image on the web. Let's say the URL is http://www.gearheadwalls.com/wp-content/uploads/2013/07/Mercedes-Benz-S-Class-4.jpg
Now, when a user press the download button, the image should be downloaded.
I've tried this:
window.location.href = Link;
But sometimes it just opens the image on the browser and sometimes it is downloaded as I wanted.
How can I achieve this?
You can use the HTML5 download attribute on anchors :
<a href="http://www.gearheadwalls.com/wp-content/uploads/2013/07/Mercedes-Benz-S-Class-4.jpg" download="http://www.gearheadwalls.com/wp-content/uploads/2013/07/Mercedes-Benz-S-Class-4.jpg">
<img src="http://www.gearheadwalls.com/wp-content/uploads/2013/07/Mercedes-Benz-S-Class-4.jpg">
</a>
You need to pass appropriate headers in order to allow user to download the file. If you just provide the file link in the url the browsers interpret it differently. They may first try to open the file in the browser, if it fails the file will be prompt as force-download.
If you are using PHP, the headers in download script is something like:
header('Content-Type: ' . $mime_type);
header('Content-Disposition: attachment; file="'.$name.'"');
header("Content-Transfer-Encoding: binary");
header('Accept-Ranges: bytes');
header("Cache-control: private");
header('Pragma: private');
The full tutorial can be found here: www.phptutorialforbeginners.com/2013/04/file-download-script-in-php-php.html
You will have to set Content-Disposition header field, as suggested by http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html, if you want the image should not be handled natively by browser. If you use PHP, may be this link would help, http://w3schools.invisionzone.com/index.php?showtopic=39943
Only issue with this, you can't directly make apache serve you this file, as a normal static resource, or I don't know the way to do this Apache :)
I am trying to open a word document using window.open as below
window.open("myworddoc.doc");
It works fine in FF, but IE tries to open a tab, but closes it immediately and jumps back to the current screen (no dialog is displayed to save or open a file).
What could be the issue?
This is surely a security mesure. Opening Word documents using JavaScript could have nasty effects. Imagine if you are browsing the internet, and someone makes an infected Word document open when your page loads.
Personally, I'd create a PHP file, let's say "servedoc.php", and open that file like so:
window.open("servedoc.php");
servedoc.php could contain something like this:
<?php
$file = "myworddoc.doc";
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
header("Content-Type: application/msword");
header("Content-Transfer-Encoding: binary");
readfile($file);
IE will open the PHP file, as it's a perfectly valid web file. And the PHP script would serve the file to the browser, asking the user to download the file.
Or if you are using .net (vb):
Response.ContentType = "image/jpeg" 'mime type of the file to serve.
Response.AddHeader("content-Disposition", "attachment;filename=YOURFILENAME")
Response.TransmitFile(YourFILEPath)
Like this you can let them download the .doc or the .zip file if you prefer.