Web API - File - Using object URLs to display PDF
Example: Using object URLs to display PDF
Object URLs can be used for other things than just images! They can be used to display embedded PDF files or any other resources that can be displayed by the browser.
In Firefox, to have the PDF appear embedded in the iframe (rather than proposed as a downloaded file), the preference pdfjs.disabled
must be set to false
.
<iframe id="viewer">
And here is the change of the src
attribute:
const obj_url = URL.createObjectURL(blob);
const iframe = document.getElementById('viewer');
iframe.setAttribute('src', obj_url);
URL.revokeObjectURL(obj_url);
预览 PDF 文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Using object URLs to display PDF</title>
</head>
<body>
<input type="file" accept=".pdf" />
<br />
<iframe width="100%" height="500"></iframe>
<script type="text/javascript">
window.onload = (event) => {
console.log(event)
const input = document.querySelector('input[type=file]')
const iframe = document.querySelector('iframe')
console.log(input, iframe)
input.onchange = (event) => {
console.log(event)
const files = event.target.files
if (files.length > 0) {
const objectURL = URL.createObjectURL(files[0])
iframe.setAttribute('src', objectURL)
URL.revokeObjectURL(objectURL)
}
}
}
</script>
</body>
</html>
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步