Skip to content

Instantly share code, notes, and snippets.

@kyletimmermans
Created June 26, 2024 15:13
Show Gist options
  • Save kyletimmermans/0a564a24770f19d23e13d636e7aaa54b to your computer and use it in GitHub Desktop.
Save kyletimmermans/0a564a24770f19d23e13d636e7aaa54b to your computer and use it in GitHub Desktop.
An HTML button element that can be clicked to download a PDF directly instead of previewing it in the browser
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<script>
// This function takes a PDF and turns it into a blob,
// so when its visited, its downloaded instead of previewed
function download(url) {
const fileName = url.match(/[^/\\&\?]+\.\w{3,4}(?=([\?&].*$|$))/);
const elem = (url) => {
const link = document.createElement('a');
link.setAttribute('download', fileName[0]);
link.setAttribute('href', url);
link.setAttribute("id", "tempDownloadA");
link.click();
}
downloadBlob = (blob) => elem(URL.createObjectURL(blob))
function removeElements(elements){
for(var i = 0; i < elements.length; i++){
elements[i].parentNode.removeChild(elements[i]);
}
}
fetch(url)
.then(response => response.blob())
.then(downloadBlob)
.then(removeElements(document.querySelectorAll('#tempDownloadA')))
}
</script>
<!-- Put your PDF url here v -->
<button type="button" class="btn btn-success" onclick="download('/path-or-URL-to-your-PDF')">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-download" viewBox="0 0 16 16">
<path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5"/>
<path d="M7.646 11.854a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 10.293V1.5a.5.5 0 0 0-1 0v8.793L5.354 8.146a.5.5 0 1 0-.708.708z"/>
</svg>
&nbsp;Download as PDF
</button>
</body>
<html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment