Problem/Motivation

With the "PDF: Default viewer of PDF.js" formatter, the PDF.js viewer downloads the whole file, even when the web server supports range requests and the visitor only reads the first page. By default, PDF.js streams the full file in the background (disableStream) and prefetches all the pages (disableAutoFetch). These options cannot be set in the viewer URL hash: the viewer only reads them in debug mode (pdfBugEnabled).

The iframe is also loaded with the page, even when the viewer is far below the fold.

On my tests (PDF.js 6.4.299, nginx with range support):

  • 98 MB, 850 pages book: the default viewer downloads 98 MB. With both options set, about 15 MB, even when scrolling to the last page.
  • 40 MB, 40 pages with large images: with both options set, the pages are downloaded as they are scrolled into view.

#2650950 asked for this in 2016 and was closed as there was nothing the module could do. There is now: the viewer dispatches a webviewerloaded event on the parent document right before it runs, and the options can be set on PDFViewerApplicationOptions at that point, without modifying PDF.js.

Proposed resolution

Add two settings to the pdf_default formatter, both disabled by default so existing sites are not affected:

  • Load only the pages being read: a small script sets disableStream and disableAutoFetch on the viewer from the webviewerloaded event. Requires the server to answer range requests (206).
  • Load the viewer when it becomes visible: the iframe URL is set by an IntersectionObserver. (loading="lazy" is not enough: browsers load lazy iframes up to a few thousand pixels before they are visible.)

Known limitation, to document: when the page tree of a PDF is flat (one /Pages node, as written by Ghostscript and most scanners), PDF.js reads every page dictionary when it opens the document, to check the last page. On the 850 pages book, that is about 10 MB before the first page. This is a PDF.js design choice (https://github.com/mozilla/pdf.js/issues/21859) and is not related to these settings.

I can provide a merge request with tests.

User interface changes

Two new checkboxes in the formatter settings.

API changes

None.

Data model changes

Two new formatter settings, with their schema.

CommentFileSizeAuthor
40MB-TESTFILE.ORG_.pdf40.84 MBpogfra

Issue fork pdf-3629209

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

pogfra created an issue.