[JS] pdf.js


最近有個預覽 pdf 的需求,可以透過 pdf.js 這個套件來達成:https://mozilla.github.io/pdf.js/

簡單步驟說明:

  • 引入套件、Worker
  • 建立 fileReader 讀取使用者選取的檔案
  • 使用.getDocument() 取得文檔
  • 執行 for 迴圈,透過 .getPage() 讀取並以 .render() 方法以 canvas 繪出

需要注意 .getPage 是非同步方法,因此直接執行讀取並直接繪製的話,可能會有亂碼錯誤問題。

節錄 vue 中的 methods:

importPdfJs() {
    const plugin = document.createElement('script')
    plugin.setAttribute('src', 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.2.228/pdf.min.js')
    plugin.async = true
    document.head.appendChild(plugin)
},
previewPdf(file) {
    const vm = this
    // Loaded via <script> tag, create shortcut to access PDF.js exports.
    const pdfjsLib = window['pdfjs-dist/build/pdf']
    // The workerSrc property shall be specified.
    pdfjsLib.GlobalWorkerOptions.workerSrc =
        'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.2.228/pdf.worker.js'
    const fileReader = new FileReader()
    fileReader.onload = function() {
        const viewer = document.getElementById('preview-container')
        const pdfData = new Uint8Array(this.result)
        const scale = 1.5
        let thePdf = null
        // Using DocumentInitParameters object to load binary data.
        pdfjsLib.getDocument({ data: pdfData }).promise.then(
            function(pdf) {
                console.log('PDF loaded')
                thePdf = pdf
                for (let pageNumber = 1; pageNumber <= pdf.numPages; pageNumber++) {
                    const canvas = document.createElement('canvas')
                    canvas.className = 'pdf-page-canvas'
                    viewer.appendChild(canvas)
                    renderPage(pageNumber, canvas)
                }
            },
            function(reason) {
                // PDF loading error
                console.error(reason)
            }
        )
        function renderPage(pageNumber, canvas) {
            thePdf.getPage(pageNumber).then(function(page) {
                console.log('Page loaded')
                const viewport = page.getViewport({ scale })
                canvas.height = viewport.height
                canvas.width = viewport.width
                const renderContext = {
                    canvasContext: canvas.getContext('2d'),
                    viewport: viewport
                }
                const renderTask = page.render(renderContext)
                renderTask.promise.then(function() {
                    pageRenderedNum++
                    if (pageRenderedNum === thePdf.numPages) {
                        console.log('Page rendered finished')
                        vm.showUploadLoading = false
                        viewer.classList.add('border', 'border-dotted', 'border-grey')
                    }
                })
            })
        }
    }
    fileReader.readAsArrayBuffer(file)
}

資料來源:How to display whole PDF (not only one page) with PDF.JS?


發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *