Javascript 放大简单的 pdf.js 查看器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27607526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Zoom on simple pdf.js viewer
提问by Rizzo
I started to build a pdf viewer with the pdf.js library. I really liked how simple some of the examples were so I used the PREV/NExt example to start off my viewer:
我开始用 pdf.js 库构建一个 pdf 查看器。我真的很喜欢一些示例的简单性,所以我使用了 PREV/NExt 示例来开始我的查看器:
https://github.com/mozilla/pdf.js/blob/master/examples/learning/prevnext.html
https://github.com/mozilla/pdf.js/blob/master/examples/learning/prevnext.html
I wanted to add zoom in and out and found this simple viewer which I wanted to model my zoom and scroll off of:
我想添加放大和缩小,并找到了这个简单的查看器,我想对我的缩放进行建模并滚动关闭:
https://github.com/zedr/simple-pdf-reader.js/blob/master/viewer.js
https://github.com/zedr/simple-pdf-reader.js/blob/master/viewer.js
Here is my html for my index.html:
这是我的 index.html 的 html:
<div class="row">
<div class="col-md-4">
<button class="btn btn-primary" id="prev"><i class="fa fa-level-up fa-lg"></i></button>
<button class="btn btn-primary" id="next"><i class="fa fa-level-down fa-lg"></i></button>
</div><div class="col-md-4">
<span>Page: <span id="page_num"></span> / <span id="page_count"></span></span>
<div id="pdf-controls">
<button id="zoom_minus" onclick="url.zoomMinus()"
oncontextmenu="return false;" class="btn btn-primary">-</button>
<button id="zoom_plus" onclick="url.zoomPlus()"
oncontextmenu="return false;" class="btn btn-primary">+</button>
<div id="pdf-stats">
<p>
<span id="pdf-page-zoom">n/a</span> <span>%</span>
</p>
</div>
</div>
</div><div class="col-md-4 pull-right">
<a href="sample.pdf" class="btn btn-primary"><i class="fa fa-arrows-alt fa-lg"></i></a>
<a href="sample.pdf" class="btn btn-primary" download><i class="fa fa-cloud-download fa-lg"></i></a>
</div>
</div>
<br><br>
<center>
<div style="overflow: scroll" id="pdfviewer">
<canvas id="pdfcanvas" style="border:1px solid black; width: 100%"></canvas>
</div>
</center>
and this is my javascript for my viewer.js:
这是我的javascript viewer.js:
<script id="pdfviewer">
//
// If absolute URL from the remote server is provided, configure the CORS
// header on that server.
//
var url = 'sample.pdf';
//
// Disable workers to avoid yet another cross-origin issue (workers need
// the URL of the script to be loaded, and dynamically loading a cross-origin
// script does not work).
//
// PDFJS.disableWorker = true;
//
// In cases when the pdf.worker.js is located at the different folder than the
// pdf.js's one, or the pdf.js is executed via eval(), the workerSrc property
// shall be specified.
//
PDFJS.workerSrc = 'pdf.worker.js';
var pdfDoc = null,
pageNum = 1,
pageRendering = false,
pageNumPending = null,
scale = 1.5,
canvas = document.getElementById('pdfcanvas'),
ctx = canvas.getContext('2d');
var camera = {
x: 0,
y: 0,
scale: 1,
};
/**
* Get page info from document, resize canvas accordingly, and render page.
* @param num Page number.
*/
function renderPage(num) {
pageRendering = true;
// Using promise to fetch the page
pdfDoc.getPage(num).then(function(page) {
var viewport = page.getViewport(scale);
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
var renderContext = {
canvasContext: ctx,
viewport: viewport
};
var renderTask = page.render(renderContext);
// Wait for rendering to finish
renderTask.promise.then(function () {
pageRendering = false;
if (pageNumPending !== null) {
// New page rendering is pending
renderPage(pageNumPending);
pageNumPending = null;
}
});
});
// Update page counters
document.getElementById('page_num').textContent = pageNum;
}
/**
* If another page rendering in progress, waits until the rendering is
* finised. Otherwise, executes rendering immediately.
*/
function queueRenderPage(num) {
if (pageRendering) {
pageNumPending = num;
} else {
renderPage(num);
}
}
/**
* Displays previous page.
*/
function onPrevPage() {
if (pageNum <= 1) {
return;
}
pageNum--;
queueRenderPage(pageNum);
}
document.getElementById('prev').addEventListener('click', onPrevPage);
/**
* Displays next page.
*/
function onNextPage() {
if (pageNum >= pdfDoc.numPages) {
return;
}
pageNum++;
queueRenderPage(pageNum);
}
document.getElementById('next').addEventListener('click', onNextPage);
/**
* Asynchronously downloads PDF.
*/
PDFJS.getDocument(url).then(function (pdfDoc_) {
pdfDoc = pdfDoc_;
document.getElementById('page_count').textContent = pdfDoc.numPages;
// Initial/first page rendering
renderPage(pageNum);
});
//The PdfRead object is a browser-aware reading device that the User will
//manipulate to read the page. Basically, a wrapper around the PdfView object.
var frame = document.getElementById('pdfcanvas');
var zoom_widget = document.getElementById('pdf-page-zoom');
// Keep track of certain values inside the most interesting nodes of the DOM
var state = {
get ctop () { return frame.lastChild.offsetTop },
get ftop () { return frame.scrollTop },
get fsh () { return frame.scrollHeight },
get fh () { return frame.offsetHeight },
};
// Decrease the Zoom, acting on the scale
this.zoomMinus = function (val) {
doc.page.scale -= (val) ? val : 0.25;
zoom_widget.innerText = doc.page.scale * 100;
};
// Increase the Zoom, acting on the scale
this.zoomPlus = function (val) {
doc.page.scale += (val) ? val : 0.25;
zoom_widget.innerText = doc.page.scale * 100;
};
// Controller: monitor for frame scroll events and advance page rendering
frame.onscroll = function () {
var test = (state.fsh - (state.fh + state.ftop));
if (test < 0 && doc.page.head < doc.page.last) {
doc.page.number++;
}
};
// Init the widgets
zoom_widget.innerText = doc.page.scale * 100;
</script>
I attempted to integrate the two and add zoom to my viewer, but am not having any success. My javascript knowledge is pretty limited compared to the complexity of pdf.js, but I was wondering if someone could help me with my problem. any advice, direction, code would be appreciated.
我尝试将两者集成并为我的查看器添加缩放功能,但没有任何成功。与 pdf.js 的复杂性相比,我的 javascript 知识非常有限,但我想知道是否有人可以帮助我解决我的问题。任何建议,方向,代码将不胜感激。
回答by frabjous
Sorry I know this is an old question, and you've probably come up with a solution by now. Below, however, you'll code for a very simple PDF.js page (which I made by tinkering with the sampleon Mozilla's webpage) with zoom in and zoom out buttons that work.
抱歉,我知道这是一个老问题,您现在可能已经想出了一个解决方案。但是,在下面,您将为一个非常简单的 PDF.js 页面(我通过修改Mozilla 网页上的示例制作的)编写代码,其中包含有效的放大和缩小按钮。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Simple PDF.js with zoom</title>
<script src="pdfjs/build/pdf.js"></script>
</head>
<body>
<h1>Simple PDF.js with zoom</h1>
<button id="nextbutton" type="button">next page</button>
<button id="prevbutton" type="button">prev page</button>
<button id="zoominbutton" type="button">zoom in</button>
<button id="zoomoutbutton" type="button">zoom out</button>
<br>
<canvas id="the-canvas" style="border:1px solid black"></canvas>
<script id="script">
var pageNum = 1;
var pdfScale = 1; // make pdfScale a global variable
var shownPdf; // another global we'll use for the buttons
var url = './helloworld.pdf' // PDF to load: change this to a file that exists;
function renderPage(page) {
var scale = pdfScale; // render with global pdfScale variable
var viewport = page.getViewport(scale);
var canvas = document.getElementById('the-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
}
function displayPage(pdf, num) {
pdf.getPage(num).then(function getPage(page) { renderPage(page); });
}
var pdfDoc = PDFJS.getDocument(url).then(function getPdfHelloWorld(pdf) {
displayPage(pdf, 1);
shownPdf = pdf;
});
var nextbutton = document.getElementById("nextbutton");
nextbutton.onclick = function() {
if (pageNum >= shownPdf.numPages) {
return;
}
pageNum++;
displayPage(shownPdf, pageNum);
}
var prevbutton = document.getElementById("prevbutton");
prevbutton.onclick = function() {
if (pageNum <= 1) {
return;
}
pageNum--;
displayPage(shownPdf, pageNum);
}
var zoominbutton = document.getElementById("zoominbutton");
zoominbutton.onclick = function() {
pdfScale = pdfScale + 0.25;
displayPage(shownPdf, pageNum);
}
var zoomoutbutton = document.getElementById("zoomoutbutton");
zoomoutbutton.onclick = function() {
if (pdfScale <= 0.25) {
return;
}
pdfScale = pdfScale - 0.25;
displayPage(shownPdf, pageNum);
}
</script>
</body>
</html>
Sorry I haven't examined your code above to see how it differs from mine, or determine what about it doesn't work, but perhaps this will give you what you need.
抱歉,我没有检查你上面的代码,看看它与我的有什么不同,或者确定它不起作用的地方,但也许这会给你你需要的东西。
回答by Kamil Kie?czewski
Function which can set canvas (of any size) with arbitrary region of zoomed pdf (viewport.transform)
可以使用缩放pdf的任意区域设置画布(任何大小)的功能(viewport.transform)
/*
* Load pdf page to canvas and zoom it on arbitrary region
*
* @url - url to pdf
* @pageNum - which page (start from 1)
* @width - canvas width
* @height - canvas height
* @zoom - zoom, 1=no zoom
* @posX - shift pdf on x axis (in pixels)
* @posY - shift pdf on y axis (in pixels)
*/
async function load(url,pageNum,width,height,zoom,posX,posY) {
let pdfjs = window['pdfjs-dist/build/pdf'];
pdfjs.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';
let pdf = await pdfjs.getDocument(url).promise;
let page = await pdf.getPage(pageNum);
let viewport = page.getViewport({scale:1});
let pY = viewport.transform[5]*zoom + posY;
viewport.transform = [zoom, 0, 0, -zoom, posX, pY];
let context = canvasPdf.getContext('2d');
canvasPdf.width = width;
canvasPdf.height = height;
let renderContext = {canvasContext: context, viewport};
var render = await page.render(renderContext).promise;
}
let url = "http://cors-anywhere.herokuapp.com/http://www.africau.edu/images/default/sample.pdf";
load(url,1,500,140,2,-140,-110);
body {background: gray }
<script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>
<canvas id="canvasPdf"></canvas>
回答by Mars Robertson
I wanted to add zoom in and out...
我想添加放大和缩小...
@frabjous answer is good, it offers exactly what you've described. I was tinkering with it as well, live demo: http://next.plnkr.co/edit/XQBGOhdzkX3zQ86Y
@frabjous 的回答很好,它提供了您所描述的内容。我也在修补它,现场演示:http: //next.plnkr.co/edit/XQBGOhdzkX3zQ86Y
For something more advanced check this one: mozilla pdf.js without fullview
对于更高级的东西,请检查这个:mozilla pdf.js without fullview
Using an iframe and passing URL as parameter seems easy!
使用 iframe 并将 URL 作为参数传递似乎很容易!

