DEV Community

Asif
Asif

Posted on

Displaying PDF Files in an Iframe: A Simple Solution

Are you looking for a way to embed a PDF file on your website without relying on external services or plugins? If so, then you're in luck! In this tutorial, we'll show you how to use PHP and cURL to download the content of a PDF file from a URL and display it in an iframe.

First, let's start by creating a function that uses cURL to download the PDF file:



function displayPdfFromUrl($url) {
  // Initialize cURL session
  $ch = curl_init();

  // Set cURL options
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  // Execute cURL request
  $data = curl_exec($ch);

  // Close cURL session
  curl_close($ch);

  // Return PDF file content
  return $data;
}


Enter fullscreen mode Exit fullscreen mode

This function takes a URL as an argument and uses cURL to download the content of the PDF file at that URL. The content is then returned as a string.

Next, we can use the base64_encode function to encode the PDF data as a base64 string, which we can then use as the src attribute for an iframe element:

code sample

That's all there is to it! With just a few lines of code, you can easily display PDF files on your website without relying on external services or plugins.

Top comments (0)