FORM

Open PDF in browser with PHP

Example 1: This example display the pdf file on the browser.,How to open a PDF files in web browser using PHP?,How to convert an array to CSV file in PHP ?,Example 2:this examples displays a format and explains every section of code

Answer by Melani Davidson

I want to display a PDF file on browser which is store on our server. Here is my code :-,So as per the answer below I have to use phpmerger to merge multiple PDF file and display into the browser. I gone through this website http://pdfmerger.codeplex.com/ but unable to use into codeignter. Can anyone please help me to use this phpmerger inside my codeingter, yes im using CI so as you said I have to include pdfmerger.php inside applications/libraries but there is another folder fpdf and fpdi should I upload it into the same location ? and How can I load the merger in my controller ? Can you please help me how to use phpmerger in CI – Rakesh Shetty Nov 21 ’14 at 5:01 , thanks and i tried that file_get_contents($file);exit; it shows the pdf file but actually there is more than one pdf file and im using foreach to display pdf file. So when I remove exit; from file_get_contents($file); it shows %PDF-1.4 % 5 0 obj >stream – Rakesh Shetty Nov 20 ’14 at 12:40

$filePath="file path here"; $filename="file name here"; header('Content-type:application/pdf'); header('Content-disposition: inline; filename="'.$filename.'"'); header('content-Transfer-Encoding:binary'); header('Accept-Ranges:bytes'); @ readfile($filePath); 

Answer by Murphy Patel

      

FILE UPLOAD




if(empty($errors)) < if(move_uploaded_file($tmpname,$uploadpath)) < echo "file uploaded successfully"; >else < echo "not successfull"; >> else < foreach($errors as $value) < echo "$value"; >> ?>

Answer by Keilani Murillo

How to display PHP variable values with echo, print_r, and var_dump,How to open a PDF file in browser with PHP,How to remove the last element from an array in PHP,How to remove the first element from an array in PHP

Читайте также:  Python normcase path os
Example 1 : How to open a PDF file in browser with PHP
Example 2 : How to open a PDF file in browser with PHP

Answer by Willie Hoover

Posted 16 July 2012 — 05:59 PM , Posted 16 July 2012 — 06:58 PM , Posted 16 July 2012 — 07:15 PM ,How To Make Complete Calculator With All Buttons Using PHP?

Answer by Brennan Whitehead

Example source:

Answer by Amina Whitehead

Now, create a PHP file ‘index.php’ and write the database connection code at the top. For this, we are using Object Oriented PHP MySQLi connection code. Then, fetch the pdf file name and directory using select statement. To embed the PDF in a web page, we use the iframe element.,In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician. Here is the PDF file displayed on the webpage that is fetched from the MySQL database table using the PHP code:,Python has a set of useful Libraries and Packages that minimize the use of code.

Suppose we have a ‘infopdf‘ TABLE in the Database as follows. You can use your existing database or copy and paste this in MySQL.

CREATE TABLE IF NOT EXISTS `infopdf` ( `fileid` int(11) NOT NULL AUTO_INCREMENT, `filename` varchar(150) NOT NULL, `directory` varchar(150) NOT NULL, `created_date` date NOT NULL, PRIMARY KEY (`fileid`) )
CREATE TABLE IF NOT EXISTS `infopdf` ( `fileid` int(11) NOT NULL AUTO_INCREMENT, `filename` varchar(150) NOT NULL, `directory` varchar(150) NOT NULL, `created_date` date NOT NULL, PRIMARY KEY (`fileid`) )
INSERT INTO `infopdf` (`fileid`, `filename`, `directory`, `created_date`) VALUES (1, 'etp.pdf', '/document/', '2019-07-12');

Now, create a PHP file ‘index.php‘ and write the database connection code at the top. For this, we are using Object Oriented PHP MySQLi connection code. Then, fetch the pdf file name and directory using select statement. To embed the PDF in a web page, we use the iframe element.

query($select); while($row = $result->fetch_object())< $pdf = $row->filename; $path = $row->directory; $date = $row->created_date; > echo '

Here is the information PDF

'; echo 'Created Date : '.$date; echo 'File Name : '.$pdf; ?>

In the above method, we have embedded PDF in an iframe. This is basically used when we have to show a pdf in addition to the web contents. But if you want to display PDF as the whole content of webpage, then it’s better to use header() function. In this below example, we have added header() function and set the file ‘Content-type’, ‘Content-Disposition’, ‘Content-Transfer-Encoding’. We have used PHP predefined readfile() function to read the file and added error control operator (@) in front of it. When this operator pretended to an expression, any error or warning might be generated by this expression will be ignored.

query($select); while($row = $result->fetch_object())< $pdf = $row->filename; $path = $row->directory; $date = $row->created_date; $file = $path.$pdf; > // Add header to load pdf file header('Content-type: application/pdf'); header('Content-Disposition: inline; filename="' .$file. '"'); header('Content-Transfer-Encoding: binary'); header('Accept-Ranges: bytes'); @readfile($file); ?>

Answer by Ryker Klein

In my current project I don’t want to keep PDF and DOC file on server or open due to security purpose so I want a system where only login user can view or download the files. so to do this have used given below code,Their is no way you can display Doc file on browser, you can only user google reader but google reader don’t open password protected files, for google reader you need to give public access file to view on browser,Display Pdf/Word Document in Browser Using PHP,All the site contents are Copyright © www.stechies.com and the content authors. All rights reserved. All product names are trademarks of their respective companies. The site www.stechies.com is in no way affiliated with SAP AG. Every effort is made to ensure the content integrity. Information used on this site is at your own risk. The content on this site may not be reproduced or redistributed without the express written permission of www.stechies.com or the content authors.

$file = 'myfile.pdf'; $file1 = '/file-dir/'.$file; ob_clean(); header("Cache-Control: no-store"); header("Expires: 0"); header("Content-Type: application/pdf"); header("Cache-Control: public"); header('Content-Disposition: inline; filename="' . $file . '"'); header("Content-Transfer-Encoding: binary"); header('Accept-Ranges: bytes'); readfile($file1);
$file = 'myfile.pdf'; $file1 = '/file-dir/'.$file; ob_clean(); header("Cache-Control: no-store"); header("Expires: 0"); header("Content-Type: application/pdf"); header("Cache-Control: public"); header("Content-Description: File Transfer"); header("Content-Disposition: attachment; filename=$file"); header("Content-Transfer-Encoding: binary"); header('Accept-Ranges: bytes'); readfile($file1);

Their is no way you can display Doc file on browser, you can only user google reader but google reader don’t open password protected files, for google reader you need to give public access file to view on browser

Источник

Create a Custom PDF Viewer With PDF.js and Restrict Downloading & Printing

Create a Custom PDF Viewer

In this tutorial, I will create a custom PDF viewer with PDF.js, which will restrict users to download and print PDF file.

This is often required by many PDF books sellers who let the user to read their PDF books online on their websites but do not allow user to download or print their PDF file without making a certain payment of that PDF file or book.

Whenever you view any PDF file on any web browser such as Google Chrome, Mozilla Firefox, IE, Opera, Safari and etc. They all uses their custom PDF file viewer which allow user to download PDF file and also print those PDF files easily.

There are several paid solution available to this problem but I will share a way in which you can resolve the issue without making any payment.

PDF.js is the most useful library which will allow me to achieve my goal of creating a custom PDF viewer with JavaScript with read only feature.

I will also create a Next and Previous button which will allow me to move to next or previous page of PDF file.

I will also display the current and total pages of PDF file on the same custom PDF viewer on the top right side.

Steps to Create a Custom PDF Viewer With JavaScript

I will follow the below steps to create a custom PDF viewer with JavaScript through PDF.js.

  1. Create an index.php for PDF viewer
  2. Add HTML for PDF viewer
  3. Add CSS for navigation and view of PDF viewer
  4. Add PDF.js library and JavaScript
  5. Add PHP in header to configure the CORS
  6. Create .htaccess file to revoke direct PDF file access via URL

1. Create an index.php for PDF viewer

First of all create an index.php file which will act as PDF viewer file. Once the file is created I will add HTML, CSS, PDF.js and PHP code in it.

2. Add HTML for PDF viewer

Add the below HTML code for PDF viewer, pagination of Next, Previous buttons, current and total number of pages.

3. Add CSS for navigation and view of PDF viewer

Add the below CSS to style your PDF viewer.

body < background: black; margin:0px; >.pagination < background: #ffffff; width: 100%; float: left; >.pagination .wrap < float:right; width: 300px; >#the-canvas < border: 1px solid black; direction: ltr; margin: 0 auto; display: block; >@media print < body >

4. Add PDF.js library and JavaScript

Now, it is the time to add the PDF.js library and add required JavaScript to make it functional.

  

5. Add PHP in header to configure the CORS

Everything is ready now but it will not work because of Cross-Origin Resource Sharing (CORS) issue. Therefore, I will add the below PHP code to resolve the CORS issue in the top of index.php file.

// Allow from any origin if (isset($_SERVER['HTTP_ORIGIN'])) < // should do a check here to match $_SERVER['HTTP_ORIGIN'] to a // whitelist of safe domains header("Access-Control-Allow-Origin: "); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Max-Age: 86400'); // cache for 1 day > // Access-Control headers are received during OPTIONS requests if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') < if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS"); if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) header("Access-Control-Allow-Headers: "); > if(!isset($_GET['pdf_file']) || empty($_GET['pdf_file']))< header("Location: error.php"); exit(); >else

The above code also getting the PDF file name through $_GET[] super global variable. If it is an empty then you can not view the PDF file, file name must be available to read the file on server therefore the URL must contain pdf_file parameter, for example like below URL.

https://www.allphptricks.com/demo/2022/apr/custom-pdf-viewer/index.php?pdf_file=sample-file1.pdf

6. Create .htaccess file to revoke direct PDF file access via URL

This is the most important step, although the application is ready but user can still access the PDF file directly hitting the below URL in the browser.

https://www.allphptricks.com/demo/2022/apr/custom-pdf-viewer/sample-file1.pdf

Therefore, I will add some code that will revoke direct PDF file access via URL like above.

# Simple File List Access Restricter RewriteEngine On # 1) If NOT the current host RewriteCond %@@% !^([^@]*)@@https?://\1/.* # 2) Deny access to these types RewriteRule \.(gif|jpg|jpeg|png|tif|pdf|wav|wmv|wma|avi|mov|mp4|m4v|mp3|zip?)$ - [F]

Save the above file with .htaccess and placed it in the same folder where PDF files exist.

Conclusion

By following the above steps, you can easily create your custom PDF file viewer using JavaScript and PDF.js library.

I hope this will solve your issue and help you to achieve your desired goal to restrict PDF files downloading and printing.

If you found this tutorial helpful, share it with your friends and developers group.

I spent several hours to create this tutorial, if you want to say thanks so like my page on Facebook, Twitter and share it.

Facebook Official Page: All PHP Tricks

Twitter Official Page: All PHP Tricks

Javed Ur Rehman is a passionate blogger and web developer, he loves to share web development tutorials and blogging tips. He usually writes about HTML, CSS, JavaScript, Jquery, Ajax, PHP and MySQL.

Источник

Оцените статью