2

URL预览

function previewPdf(url, filename) {
    window.open(url, filename, `width=1060,height=${screen.height},left=${(screen.width - 1060)>>1}`)
}

PDF文件 预览

function objectURL2Blob(url) {
  return new Promise((resolve) => {
    let xhr = new XMLHttpRequest()
    xhr.open('GET', url, true)
    xhr.responseType = 'blob'
    xhr.onload = function () {
      if (this.status == 200) resolve(this.response)
    }
    xhr.send()
  })
}

// 预览 pdf 文件
async function previewPdfFile(file) {
  let url = URL.createObjectURL(file)
  let blob = new Blob([await objectURL2Blob(url)], { type: 'application/pdf' })
  url = URL.createObjectURL(blob)
  previewPdf(url, 'JavaScript权威指南.pdf')
}

// 选择 pdf 文件
function fileSelect() {
  return new Promise((resolve) => {
    const input = document.createElement('input')
    input.accept = '.pdf'
    input.type = 'file'
    input.onchange = () => {
      resolve(input.files)
    }
    input.click()
  })
}
// 选择 PDF文件 预览
fileSelect().then((files) => {
  previewPdfFile(files[0])
})

部分浏览器可能不支持



灬都是个谜
38 声望4 粉丝