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>

参考

Example: Using object URLs to display PDF

Unique file type specifiers

posted @ 2021-04-11 23:20  heismk  阅读(63)  评论(0编辑  收藏  举报