How to force a PDF to be displayed in the browser

Asked

Viewed 11,278 times

7

I have a sequence of PDF files that I can link normally, only as soon as I click on one of them it downloads, and I need the PDF to be displayed in the browser itself. I tried to use this on my link but it didn’t help:

target="_blank"

I cannot let the user download directly in any way. How to resolve this issue?

  • 2

    That depends on the browser... If you are linking the file directly you are saying to the browser, "Here is a file, do what you want with it..."

  • but there is no way to change this in the case of google Chrome for a security issue nor the path of pdf show in the url and I have to preview on screen and not download

  • 1

    I know you can force the download, but otherwise...

  • and if you put yourself in an iframe I tried here more I think I did wrong and that no matter how it’s done it doesn’t really matter I just want it to display on the screen.

  • If you do not want/cannot depend on the browser for this (it is the one who decides whether to force the download or not), you will need to convert each page of the PDF to image on the server, and display the images in the browser. Or upload the file to a service that does this for you, like http://issuu.com/

  • Forget it because it depends on the user’s configuration. Here on my pc, for example, I have Foxit installed. When I click on any PDF, it is downloaded and opens in Foxit.. Of course, I can change and disable that behavior, but I don’t give a damn, and I think you’d better open it on Foxit. It doesn’t mean that everyone has to do this or whoever doesn’t is wrong. It’s just personal choice. To be aware, on another PC, which I have here, opens in the browser directly. Anyway, this freedom of the user to choose how to use the device itself, you "never" can take. Note that the "never" is in quotes.

  • @Kirito Some of the answers answered what you asked?

  • yes the last now was difficult but it worked thanks

Show 3 more comments

3 answers

3

As far as I know how Pdfs are not native web pages is the browser that decides what to do with them. That is why the browser has to be configured to open using some plugin or internal viewer as in firefox for example.

Or else try this

header("Content-Type: application/pdf");
header('Content-Disposition: inline; "nome_do_arquivo.pdf"');
  • hello friend then only that my pdf files are not published they are in another location outside the project so understand it and accessed via url

  • So I guess you have to set up the browser yourself

3


As already mentioned by Ivan Nack, this will depend on the browser, there is how to manipulate the header Content-Disposition, but it will depend on how the browser will handle the file, as there is how to configure the browser to always download the file or if the browser does not handle natively with PDF, it is used plugins like Adobe Reader.

As said by bfavaretto in comment, a way to do this is to convert each page of the PDF file into image and display it, this is how Google should do (I believe), a way to do this in PHP is by using ImageMagick.

Follow an example taken from from here:

$arquivoPDF = 'demo.pdf';
$imagem = 'demo.jpg';
$img = new imagick();

$img->setResolution(200,200); // Isto é importante para dar uma saída de boa qualidade, caso contrário, o texto pode não ser claro  
$img->readImage("{$arquivoPDF}[0]"); // Lê a primeira página do PDF, o número entre [] indica a página
$img->scaleImage(800, 0);            // Reduz as dimensões
$img->setImageFormat('jpg');         // Define novo formato
$img = $img->flattenImages();        // Isso é necessário para imagens com transparência, que irá produzir um fundo branco para regiões transparentes
$img->writeImages($imagem, false);   // Salva a imagem

Another alternative, now in Javascript, is to use a renderer like the pdf.js, that does not require third party applications. There is a demonstration here.


Finally, there is also how to use the Google viewer to do this what you want, for example:

<iframe src="http://docs.google.com/gview?
 url=http://infolab.stanford.edu/pub/papers/google.pdf&embedded=true"
 style="width:600px; height:500px;" frameborder="0">
</iframe>

DEMO

0

I was having a similar difficulty following the solution I found giving the two options view in the browser or Download:

<?php
function varSet($VAR) { return isset($_GET[$VAR]) ? $_GET[$VAR] : ""; }
$action = varSet("action");
$pasta = base64_decode(varSet('pasta'));

//Lista dos arquivos que nao serão listados
$denyFiles = array(".htaccess","thumbs.db");

if ($action == "download") {
    $file = base64_decode(varSet("file"));
        header("Content-disposition: attachment; filename=\"".basename($file)."\"");
    readfile(".$file");
    exit;
}
 if ($action == "embed") {
    $file = base64_decode(varSet("file"));
        header("Content-Type: application/pdf");
    readfile(".$file");
    exit;
}
?>
<?php
$pasta = '/arquivos';
$arquivos = "$user->cod_func".'  '.utf8_decode($_POST['select_mes']).' de '.$_POST['select_ano'].'.pdf';
$filename = 'arquivos/'.$arquivos;


if (file_exists($filename)) {
?>  
Download do Arquivo: <a href="?action=download&file=<?php echo base64_encode("$pasta/$arquivos"); ?>"><?php echo $_POST['select_mes'].' '.$_POST['select_ano']; ?></a>
<br><br>
Vizualizar: <a href="?action=embed&file=<?php echo base64_encode("$pasta/$arquivos"); ?>"><?php echo $_POST['select_mes'].' '.$_POST['select_ano']; ?></a>
<br>

<?php
} else {
    echo "Não existe holerith no mês selecionado";
}
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.