Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

viewer.js / pdf.js: Memory usage increases every time a pdf is rendered

My problem is that the memory usage of my application increases every time I render a pdf file with viewer.js.

I render my pdf this way:

container = document.getElementById('viewerContainer');
viewer = document.getElementById('viewer');

pdfViewer = new PDFViewer({
    container: container,
    viewer: viewer
});

$scope.pdfFindController = new PDFFindController({
      pdfViewer: pdfViewer
});

pdfViewer.setFindController($scope.pdfFindController);

container.addEventListener('pagesinit', function () {
    pdfViewer.currentScaleValue = 'page-width';                            
});

PDFJS.getDocument($scope.getPageLink(pdf)).then(function (pdfDocument) {
    documentPdf = pdfDocument;
    pdfViewer.setDocument(pdfDocument);                       
});

I render the file in a separate view. When I go back to my previous view and open another file, the memory usage increases by ~20MB.

I tried this:

documentPdf.destroy();

Now, the memory usage decreases a bit, but not as much as it was allocated before.

Is there a solution for this?

UPDATE:

Pdf.js version: 1.6.210

pdf.js worker version: 1.6.210

like image 621
chocolate cake Avatar asked Dec 10 '22 14:12

chocolate cake


2 Answers

You need to call the destroy method on the promise of the DocumentPageProxy.

The documentation describes it as followed:

Destroys current document instance and terminates worker.

Source: https://github.com/mozilla/pdf.js/blob/master/src/display/api.js (Line 621)

There are some tests in the current pdf.js library, which tests the behaviour of the destroy method. (https://github.com/mozilla/pdf.js/blob/master/test/unit/api_spec.js (Line 86)

In your case something like:

 // a variable to store the callback function
 var loadingTask = PDFJS.getDocument(basicApiUrl);
 
...

 // when the document should get destroyed call
 loadingTask.destroy();
 
like image 129
duffy356 Avatar answered Apr 06 '23 00:04

duffy356


I think that by calling documentPdf.destroy(); you don't free the memory taken by pdfViewer: I didn't find any methods to destroy pdfViewer, but you can try to call

delete pdfViewer;
delete documentPdf;

and if you are not confident that deleting properties is enough, you can set both to null.

If you still experience memory leaks it can be that the HTML stored in the history cache is using up your memory, so try to replace the viewer or container HTML with an empty element (or remove it completely)

document.getElementById('viewerContainer').outerHTML = '';

or

container.parentNode.removeChild(container);
like image 27
Giovazz89 Avatar answered Apr 06 '23 00:04

Giovazz89