Show a PDF file in the browser instead of downloading it

Hi,

I’m using Slim 4.
I want to show a PDF file in the browser instead of downloading it. If I use a JPG file, the image is shown in the browser. But if I use a PDF file, the browser automatically downloads the file. Downloaded files can be open perfectly on any computer.
Both test files are stored in the server, not generated by a library.

This is the code I’m using:

$attachmentFilename = "test.pdf"; //"test.jpg"
$pathFilename = $directory . DIRECTORY_SEPARATOR . $attachmentFilename;
$attachmentFile = file_get_contents($pathFilename);

$response->getBody()->write($attachmentFile);
$response = $response->withHeader('Content-Type', mime_content_type($pathFilename));
$response = $response->withHeader('Content-Disposition', 'inline; filename="'.$attachmentFilename.'"');
$response = $response->withHeader('Content-Transfer-Encoding', 'binary');
$response = $response->withHeader('Accept-Ranges', 'bytes');
$response = $response->withHeader('Content-Length', filesize($pathFilename));
return $response;

I´ve also tried the following code with the same result:

$attachmentFilename = "test.pdf"; //"test.jpg"
$pathFilename = $directory . DIRECTORY_SEPARATOR . $attachmentFilename;

$fh = fopen($pathFilename, 'r');
$file_stream = new Stream($fh);

$response->getBody()->write($attachmentFile);
return $response->withHeader('Content-Type', mime_content_type($pathFilename))
			    ->withHeader('Content-Length', filesize($pathFilename))
				->withHeader('Content-Disposition', 'inline; filename="'.$attachmentFilename.'"')
				->withHeader('Accept-Ranges', 'bytes')
				->withHeader('Expires', '0');

What am I doing wrong?
Thanks in advance.

This also depends on the browser settings. As soon as the user tells the browser to download the PDF, the browser will always download it. So you never have 100% control about the behavior within the browser. Except you display the pdf in a modal window (sweetalert2 or bootstrap).

Thank you @odan.
I’ve made some tests with Chrome and Firefox.

The first snippet always force the file to download, in both browsers. But the second snippet works perfectly in Firefox, it shows the pdf in browser. I searched in Chrome configuration and, as you pointed out, it depends on Chrome configuration. As default it is configured as “Download pdf files instead of automatically opening them in Chrome”.