需求:在线浏览pdf文档.
解题:拿到pdf文档后,使用pdf.js库,将其转换成canvas,不就可以看了吗.
思路:
读取指定的pdf文档,获取文档的总页数;
根据总页数,创建对应数量的canvas元素,并以id标识;
将每页内容渲染到对应id的canvas中;
代码如下:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>在线浏览pdf文档</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.13.216/pdf.min.js"></script>
</head>
<body>
<div id="myContainer"></div>
<script>
function loadPDF (url) {
// 思路:
// 读取指定的pdf文档,获取文档的总页数
// 根据总页数,创建对应数量的canvas元素,并以id标识
// 将每页内容渲染到对应id的canvas中
pdfjsLib
.getDocument('./a.pdf')
.promise
.then(function(pdf) {
let num = pdf.numPages
const id_prefix = 'ok_'
createCanvas(num, id_prefix)
renderCanvas(pdf, num, id_prefix)
})
}
// 创建画布容器
function createCanvas (num, idPrefix) {
const container = document.getElementById('myContainer')
for (let i = 1; i <= num; i++) {
let canvas = document.createElement('canvas')
canvas.id = `${idPrefix}${i}`
container.appendChild(canvas)
}
}
// 将文档内容渲染到画布
function renderCanvas (pdf, num, idPrefix) {
for (let i = 1; i <= num; i++) {
pdf
.getPage(i)
.then(function(page) {
var scale = 2
var viewport = page.getViewport({ scale: scale, })
var canvas = document.getElementById(`${idPrefix}${i}`)
var context = canvas.getContext('2d')
canvas.height = viewport.height
canvas.width = viewport.width
var renderContext = {
canvasContext: context,
viewport: viewport
}
page.render(renderContext)
})
}
}
loadPDF('./a.pdf')
</script>
</body>
</html>
32 天前