Вы отображали PDF в элементе canvas the-canvas
, но при добавлении прямоугольного объекта вы использовали этот же элемент для создания элемента fabricjs canvas the-canvas
, поэтому он очистил холст и нарисовал только прямоугольный объект.
Вам необходимо отобразить данные страницы pdf в верхнем контексте холста fabricjs, а после загрузки изображения добавить их как объект изображения в нижний элемент canvas.
DEMO
// If absolute URL from the remote server is provided, configure the CORS
// header on that server.
var url = 'https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf';
// Loaded via <script> tag, create shortcut to access PDF.js exports.
var pdfjsLib = window['pdfjs-dist/build/pdf'];
// The workerSrc property shall be specified.
pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';
var pdfDoc = null,
pageNum = 1,
prevPageNum = 1,
pageRendering = false,
pageNumPending = null,
scale = 0.8,
fCanvas = new fabric.Canvas("the-canvas", {
selection: false
});
/**
* Get page info from document, resize canvas accordingly, and render page.
* @param num Page number.
*/
var pageHistory = {};
function renderPage(num) {
pageHistory[prevPageNum] = fCanvas.toJSON();
var jsonData = pageHistory[num];
fCanvas.discardActiveObject(); //if you have any object selected, then it will deselect
if (jsonData) {
fCanvas.loadFromJSON(jsonData, function() {
renderPdfData(num);
fCanvas.renderAll.bind(fCanvas)
});
} else {
pageHistory[num] = fCanvas.toJSON();
fCanvas.clear();
renderPdfData(num);
}
}
function renderPdfData(num) {
pageRendering = true;
// Using promise to fetch the page
pdfDoc.getPage(num).then(function(page) {
var viewport = page.getViewport(scale);
fCanvas.setDimensions({
height: viewport.height,
width: viewport.width
})
// Render PDF page into canvas context, use fabricjs top canvas element context
var renderContext = {
canvasContext: fCanvas.contextTop,
viewport: viewport
};
var renderTask = page.render(renderContext);
// Wait for rendering to finish
renderTask.promise.then(function() {
pageRendering = false;
var imageData = fCanvas.upperCanvasEl.toDataURL(); //create an image from top context and put it in lower canvas element
fabric.Image.fromURL(imageData, function(img) {
img.set({
left: 0,
top: 0,
evented: false,
selectable: false,
excludeFromExport:true
});
fCanvas.add(img).sendToBack(img);
fCanvas.clearContext(fCanvas.contextTop);
if (pageNumPending !== null) {
// New page rendering is pending
renderPage(pageNumPending);
pageNumPending = null;
}
});
});
});
// Update page counters
document.getElementById('page_num').textContent = num;
}
/**
* 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;
}
prevPageNum = pageNum;
pageNum--;
queueRenderPage(pageNum);
}
document.getElementById('prev').addEventListener('click', onPrevPage);
/**
* Displays next page.
*/
function onNextPage() {
if (pageNum >= pdfDoc.numPages) {
return;
}
prevPageNum = pageNum;
pageNum++;
queueRenderPage(pageNum);
}
document.getElementById('next').addEventListener('click', onNextPage);
/**
* Asynchronously downloads PDF.
*/
pdfjsLib.getDocument(url).then(function(pdfDoc_) {
pdfDoc = pdfDoc_;
document.getElementById('page_count').textContent = pdfDoc.numPages;
// Initial/first page rendering
renderPage(pageNum);
});
// Adding a rectangle
jQuery(function($) {
$("#addRectangle").click(function() {
fCanvas.add(new fabric.Rect({
left: 100,
top: 100,
fill: 'red',
width: 20,
height: 20
}));
});
});
#the-canvas {
border:1px solid black;
}
<script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<h1>PDF.js Previous/Next example</h1>
<div>
<input type="button" id="addRectangle" value="Add Signature">
<button id="prev">Previous</button>
<button id="next">Next</button>
<span>Page: <span id="page_num"></span> / <span id="page_count"></span></span>
</div>
<canvas id="the-canvas"></canvas>