3

I want to display, embedded in the HTML, a pdf file which is in a directory up to the document root.

Document root points to /var/www/web1/web and the pdf file is in /var//www/web1/docs/pdf, so I can't point it from the html.

I'm using PHP and I tried some suggestions like get_file_contents, base64_encode, .... but didn't worked.

All examples I find are to make download the pdf or to convert it into a jpg, but this is not what I need.

Any suggestions?

Carlos
  • 352
  • 1
  • 3
  • 13

4 Answers4

9

Simply load the pdf content by a php page, we call it viewer.php, then embed the PHP page as it would be the document itself: <embed src="viewer.php" width="80%" height="900px" />

In the viewer.php file:

<?php
//Load file content
$pdf_content = file_get_contents('../unreachable_file_outside_webserver.pdf');
//Specify that the content has PDF Mime Type
header("Content-Type: application/pdf");
//Display it
echo $pdf_content;

Otherwise another solution for bigger files (easier on RAM due to bufferized read/output without storing content in RAM) use readfile

<?php
header("Content-Type: application/pdf");
readfile("../unreachable_file_outside_webserver.pdf");
GrowingBrick
  • 731
  • 4
  • 12
  • Right, thanks GrowingBrick. This worked perfectly. This is the good answer. I can't figure out how to tell the pdf size to the "embed" tag in order to dimension it correctly. – Carlos Jun 07 '18 at 10:22
  • To size properly the embed element you should choose a ratio and then scale on the browser's windows size. This is done statically by CSS, you could do it dynamically using JavaScript changing style width and height properties in base of `window.innerWidth` and `window.innerHeight` or the embed's parent container size. – GrowingBrick Jun 07 '18 at 11:23
0

You can embed PDF on your website using a library, for example there's a great one called PDF.js

PDF is a binary format so you cannot exactly "display it".

matiit
  • 7,969
  • 5
  • 41
  • 65
0

Use the following html tag:-

<embed src="path_to_pdf_file.pdf" width="800px" height="2100px" />
nandal
  • 2,544
  • 1
  • 18
  • 23
  • Thanks nandal. This is not what I want, I don't want somebody accessing directly to the file via the URL shown in the src tag. That's why I want to send it from the php and why is in an unaccessible folder. – Carlos Jun 07 '18 at 08:34
  • ok, no problem, you could write a php script serving the pdf file, and then use the url of that pdf serving php script in this html tag. – nandal Jun 07 '18 at 08:38
0

You first need to go to root dir using "../"

<embed src="../docs/pdf/fileName.pdf" type="application/pdf" width="100%" height="500px" />
Dipanshu Mahla
  • 152
  • 1
  • 16