基本上你需要被限制在指令元素上。使用模板添加canvas
和div
标签。然后在link
函数中调用它们来渲染 pdf。
您可以更进一步,将PDFJS
和render
和load
函数包装在角度服务中,然后将其注入指令中。这样加载和渲染方法将位于服务中,指令将设置模板并调用它们。
标记:
<pdf-viewer pdf-path="pathToYourPdf"></pdf-viewer>
指令:
这实际上不是一个功能指令,但它应该让您大致了解如何实现您正在寻找的东西。
angular.module('myApp', [])
.directive('pdfViewer', [
function() {
return {
template: '<canvas></canvas><div></div>',
replace: true,
restrict: 'E',
scope: {
pdfPath: '='
},
link: function postLink(scope, iElement, iAttrs) {
scope.pdfPath = iAttrs.$eval(pdfPath);
scope.pdf = PDFJS.getDocument(scope.pdfPath);
scope.pdf
.then(renderPdf);
var renderPdf = function() {
service.pdf.getPage(1)
.then(renderPage);
};
var renderPage = function(page) {
var viewport = page.getViewport(scale);
var canvas = iElement.find('canvas')[0];
// Set the canvas height and width to the height and width of the viewport
var context = canvas.getContext("2d");
// The following few lines of code set up scaling on the context if we are on a HiDPI display
var outputScale = getOutputScale(context);
canvas.width = (Math.floor(viewport.width) * outputScale.sx) | 0;
canvas.height = (Math.floor(viewport.height) * outputScale.sy) | 0;
canvas.style.width = Math.floor(viewport.width) + 'px';
canvas.style.height = Math.floor(viewport.height) + 'px';
// Append the canvas to the pdf container div
var $pdfContainer = iElement;
iElement.css("height", canvas.style.height)
.css("width", canvas.style.width);
var canvasOffset = canvas.offset();
var textLayerDiv = iElement.find('div')[0];
textLayerDiv
.addClass("textLayer")
.css("height", canvas.style.height)
.css("width", canvas.style.width)
.offset({
top: canvasOffset.top,
left: canvasOffset.left
});
context._scaleX = outputScale.sx;
context._scaleY = outputScale.sy;
if (outputScale.scaled) {
context.scale(outputScale.sx, outputScale.sy);
}
page.getTextContent()
.then(function(textContent) {
var textLayer = new TextLayerBuilder({
textLayerDiv: textLayerDiv,
viewport: viewport,
pageIndex: 0
});
textLayer.setTextContent(textContent);
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
});
};
}
};
}
]);