Embedding PDF to the HTML view increases the accessibility of the document. It favours user experience instead of keeping a link to preview or download PDF.
There are many ways to embed PDFs in an HTML page. This tutorial provides various examples of achieving this using JavaScript and HTML.
The quick example below uses JS to create an iframe dynamically to embed the PDF chosen. It shows a file input on the screen to select a PDF file. The JavaScript validates and confirms that the uploaded file is a PDF and embeds it in the HTML target.
The iframe source attribute is used to see the embedded PDF content on the screen. It finds the PDF Data URL from the file binary and uses it to set the iframe source.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>How to Embed PDF File in HTML</title>
<style>
</style>
</head>
<body>
<div class="phppot-container">
<h1>How to Embed PDF File in HTML</h1>
<div id="error-message" class="error" style="display: none;">Invalid PDF file. Please select a valid PDF file.
</div>
<input type="file" id="pdf-input" class="row" accept=".pdf" onchange="loadPDF(this)">
<div class="pdf-embed-container" id="pdf-header" style="display: none;">
<h2 id="pdf-filename">PDF File: <span id="filename"></span></h2>
<div id="pdf-embed"></div>
</div>
</div>
<script>
function loadPDF(input) {
// Get the chosen file binary from the input type=file
var file = input.files[0];
// Get references embed PDF on a page
var errorMessage = document.getElementById('error-message');
var pdfContainer = document.getElementById('pdf-embed');
var pdfHeader = document.getElementById('pdf-header');
var filenameSpan = document.getElementById('filename');
// Clear error message from the screen initially
errorMessage.style.display = 'none';
// Validate if the chosen file type is PDF
if (file && file.type === 'application/pdf') {
// Create a data URL for the PDF file
var pdfPath = URL.createObjectURL(file);
// Create a target iframe element to embed the PDF
var iframe = document.createElement('iframe');
iframe.src = pdfPath;
iframe.width = '100%';
iframe.height = '100%';
iframe.style.border = 'none';
// Clear the existing and embed recently chosen PDF on a page
pdfContainer.innerHTML = '';
pdfContainer.appendChild(iframe);
// Display the PDF filename above the embed
filenameSpan.textContent = file.name;
// Display the PDF container and header
pdfContainer.style.display = 'block';
pdfHeader.style.display = 'block';
} else {
// Display an error message if the selected file is not a PDF
errorMessage.style.display = 'block';
pdfContainer.style.display = 'none';
pdfHeader.style.display = 'none';
}
}
</script>
</body>
</html>
This code defines a JavaScript function loadPDF()
like the above quick example. This function creates an HTML <embed> element via scripting.
This script sets the PDF data URL as the embed element source. Then, the PDF embed will be added to HTML for a target container.
embed.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="css/style.css" />
<link rel="stylesheet" href="css/form.css" />
<title>How to Embed PDF File in HTML</title>
</head>
<body>
<div class="phppot-container">
<h1>How to Embed PDF File in HTML</h1>
<div id="error-message" class="error" style="display: none;">Invalid PDF file. Please select a valid PDF file.
</div>
<input type="file" id="pdf-input" class="row" accept=".pdf" onchange="loadPDF(this)">
<div class="pdf-embed-container" id="pdf-header">
<h2 id="pdf-filename">PDF File: <span id="filename"></span></h2>
<div id="pdf-embed"></div>
</div>
</div>
<script>
function loadPDF(input) {
var file = input.files[0];
var errorMessage = document.getElementById('error-message');
var pdfContainer = document.getElementById('pdf-embed');
var pdfHeader = document.getElementById('pdf-header');
var filenameSpan = document.getElementById('filename');
if (file && file.type === 'application/pdf') {
var pdfPath = URL.createObjectURL(file);
var embed = document.createElement('embed');
embed.src = pdfPath;
iframe.width = '100%';
embed.height = '100%';
embed.style.border = 'none';
pdfContainer.innerHTML = '';
pdfContainer.appendChild(embed);
filenameSpan.textContent = file.name;
pdfContainer.style.display = 'block';
pdfHeader.style.display = 'block';
} else {
errorMessage.style.display = 'block';
pdfContainer.style.display = 'none';
pdfHeader.style.display = 'none';
}
}
</script>
</body>
</html>
An HTML object element embeds external data sources like media files or documents into an HTML page.
This code gets the uploaded PDF URL from the JavaScript files[]
array. Then, it reads the file blob object URL using the JavaScript Web API method createObjectURL()
.
The file blob URL is set to the data attribute of the <object>
tag via JavaScript. This will show the PDF embedded in the HTML view.
It can also render images and embed video or audio files to a webpage.
object-pdf.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="css/style.css" />
<link rel="stylesheet" href="css/form.css" />
<title>How to Embed PDF File in HTML</title>
</head>
<body>
<div class="phppot-container">
<h1>How to Embed PDF File in HTML</h1>
<div id="error-message" class="error" style="display: none;">Invalid PDF file. Please select a valid PDF file.
</div>
<input type="file" id="pdf-input" class="row" accept=".pdf" onchange="loadPDF(this)">
<div class="pdf-embed-container" id="pdf-header">
<h2 id="pdf-filename">PDF File: <span id="filename"></span></h2>
<div id="pdf-embed"></div>
</div>
</div>
<script>
function loadPDF(input) {
var file = input.files[0];
var errorMessage = document.getElementById('error-message');
var pdfContainer = document.getElementById('pdf-embed');
var pdfHeader = document.getElementById('pdf-header');
var filenameSpan = document.getElementById('filename');
if (file && file.type === 'application/pdf') {
var pdfPath = URL.createObjectURL(file);
var object = document.createElement('object');
object.data = pdfPath;
object.width = '100%';
object.height = '100%';
object.style.border = 'none';
pdfContainer.innerHTML = '';
pdfContainer.appendChild(object);
filenameSpan.textContent = file.name;
pdfContainer.style.display = 'block';
pdfHeader.style.display = 'block';
} else {
errorMessage.style.display = 'block';
pdfContainer.style.display = 'none';
pdfHeader.style.display = 'none';
}
}
</script>
</body>
</html>
Unlike the above three examples, it uses a JavaScript library, PDF.js, to embed a PDF document on a webpage. We have already worked with a few PHP PDF libraries to implement PDF generation, embedding watermarks on a PDF, and more.
The PDF.js
library is for embedding PDF documents into the browser using HTML5.
This example validates the selected PDF and instantiates the PDF.js
library to render a specific page to the UI.
TheĀ renderPDF()
function uses the file object URL to refer to the document source to embed.
It creates a 2D viewport context about an HTML5 canvas. Then, it gets the first page of the PDF document and embeds it into the HTML context using this library.
Loading a complete PDF to the UI may reduce performance and take too long to load. So, page-by-page loading on scroll may increase the efficiency.
embed-pdf-js.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="css/style.css" />
<link rel="stylesheet" href="css/form.css" />
<title>How to Embed PDF File in Library</title>
</head>
<body>
<div class="phppot-container">
<h1>How to Embed PDF File in Library</h1>
<!-- Error message container, initially hidden -->
<div class="error" id="errorMessage">Invalid PDF file. Please select a valid PDF file.</div>
<!-- Input to choose PDF files -->
<input type="file" class="row" id="pdfInput" accept=".pdf">
<!-- Container for embedding the PDF -->
<div id="pdf-embed-library">
<h2 id="pdf-filename">PDF File: <span id="filename"></span></h2>
<canvas id="pdfCanvas"></canvas>
</div>
</div>
<!-- PDF.js library inc -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.9.359/pdf.min.js"></script>
<!-- JavaScript code for handling file selection and PDF rendering -->
<script>
function handleFileSelect(event) {
var input = event.target;
var file = input.files[0];
var errorMessage = document.getElementById('errorMessage');
// Check if the selected file is a valid PDF
if (file && file.type === 'application/pdf') {
// Create a file object URL
var pdfUrl = URL.createObjectURL(file);
document.getElementById("filename").textContent = file.name;
errorMessage.style.display = 'none';
// Call PDF.js library function
renderPDF(pdfUrl);
} else {
errorMessage.style.display = 'block';
document.getElementById("pdf-embed-library").style.display = "none";
}
}
function renderPDF(pdfUrl) {
// Load the PDF document with the reference of its file object URL
var loadingTask = pdfjsLib.getDocument(pdfUrl);
loadingTask.promise.then(
function (pdf) {
// get the first page of the PDF document
pdf.getPage(1).then(function (page) {
var scale = 1;
var viewport = page.getViewport({ scale: scale });
// Target HTML canvas element
var canvas = document.getElementById("pdfCanvas");
var context = canvas.getContext("2d");
canvas.height = viewport.height;
canvas.width = viewport.width;
// Build 2D viewport with context
var renderContext = {
canvasContext: context,
viewport: viewport
};
// Embed the PDF docuemtnt on the HTML canvas
if (typeof page.render === 'function') {
page.render(renderContext);
} else {
page.render(renderContext);
console.log("Page rendered!");
}
document.getElementById("pdf-embed-library").style.display = "block";
});
},
function (reason) {
console.error(reason);
}
);
}
// Bind the file change event to the JS listener
document.getElementById('pdfInput').addEventListener('change', handleFileSelect);
</script>
</body>
</html>
Thus, we have seen different HTML embedding tags and a popular library to embed a PDF document in HTML. We have seen the similarities and variations of using <iframe>
, <embed>
, and <object>
tags and their attributes to load the PDF source. One of the above methods can be used based on the availability of the browser support and the design requirements.