PDFs show on phones, drawn with PDF.js

Android shows nothing for a PDF in a frame and iPhones only its first
page. On touch screens the document viewer now draws every page with
PDF.js 6.5.438 (vendored in public/pdfjs/<version>/, loaded only there);
desktop browsers keep their own viewer in the frame.

- Pages are drawn as they come near the screen and let go once far from
  it, so a long manual doesn't use up a phone's memory.
- Only the parts of the file those pages need are downloaded: uploaded
  files now send Accept-Ranges, and PDF.js's background fetch of the
  whole file is off.
- JBIG2/JPEG 2000 scans decode (wasm, with JS fallbacks).

Checked on an Android 14 emulator with Chromium 160 (which reports
pdfViewerEnabled but can't show a PDF in a frame).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-15 13:15:45 -05:00
1 parent 2e8d789975
commit 66fa5f4423
38 files changed
+1236 -1

No files matched your search

@@ -0,0 +1,109 @@
import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
// A PDF in the document viewer. Desktop browsers show it in their own viewer,
// in a frame. Phones don't: Android shows nothing in a frame and iPhones only
// the first page, so there every page is drawn with PDF.js (public/pdfjs,
// loaded only here), each one as it scrolls into view, fetching only the
// parts of the file those pages need.
export default class extends Controller {
static targets = [ "frame", "status", "pages" ]
static values = { url: String, pdfjs: String }
// Starts over each time, as a page restored from Turbo's cache comes back
// with blank pages.
connect() {
this.pagesTarget.replaceChildren()
this.statusTarget.replaceChildren(t("pdf.loading"))
this.statusTarget.hidden = false
if (navigator.pdfViewerEnabled && !matchMedia("(pointer: coarse)").matches) return this.showFrame()
this.draw().catch((error) => this.failed(error))
}
disconnect() {
this.observer?.disconnect()
this.loading?.destroy()
}
showFrame() {
this.statusTarget.hidden = true
this.pagesTarget.append(this.frameTarget.content.cloneNode(true))
}
async draw() {
const base = this.pdfjsValue
const pdfjs = await import(`${base}pdf.min.mjs`)
pdfjs.GlobalWorkerOptions.workerSrc = `${base}pdf.worker.min.mjs`
this.loading = pdfjs.getDocument({
url: this.urlValue,
withCredentials: true,
// Only the parts needed for the pages being drawn, not the whole file
// in the background (a long manual on a phone's data plan).
disableAutoFetch: true,
disableStream: true,
wasmUrl: `${base}wasm/`,
standardFontDataUrl: `${base}standard_fonts/`,
iccUrl: `${base}iccs/`
})
const pdf = await this.loading.promise
if (!this.element.isConnected) return
// Placeholders the size of the first page keep the scroll position steady
// while pages are drawn; each takes its own shape once it's drawn.
const first = (await pdf.getPage(1)).getViewport({ scale: 1 })
// Pages are drawn as they come near the screen and let go once they're
// far from it, so a long manual doesn't use up a phone's memory.
this.observer = new IntersectionObserver((entries) => {
for (const { target, isIntersecting } of entries) {
target.dataset.near = isIntersecting
if (isIntersecting && !target.dataset.drawn) this.drawPage(pdf, target)
else if (!isIntersecting && target.dataset.drawn) { delete target.dataset.drawn; target.replaceChildren() }
}
}, { rootMargin: "200% 0px" })
for (let number = 1; number <= pdf.numPages; number++) {
const page = document.createElement("div")
page.className = "relative w-full bg-white shadow-sm ring-1 ring-slate-200"
page.style.aspectRatio = `${first.width} / ${first.height}`
page.dataset.page = number
page.setAttribute("role", "img")
page.setAttribute("aria-label", t("pdf.page", { page: number, pages: pdf.numPages }))
this.pagesTarget.append(page)
this.observer.observe(page)
}
this.statusTarget.hidden = true
}
async drawPage(pdf, holder) {
holder.dataset.drawn = "drawing"
try {
const page = await pdf.getPage(Number(holder.dataset.page))
const natural = page.getViewport({ scale: 1 })
holder.style.aspectRatio = `${natural.width} / ${natural.height}`
// Sharp on the screen and when pinched in a little.
const density = Math.min((window.devicePixelRatio || 1) * 1.25, 2.5)
const viewport = page.getViewport({ scale: (holder.clientWidth * density) / natural.width })
const canvas = document.createElement("canvas")
canvas.width = Math.floor(viewport.width)
canvas.height = Math.floor(viewport.height)
canvas.className = "block h-auto w-full"
await page.render({ canvas, canvasContext: canvas.getContext("2d"), viewport }).promise
page.cleanup()
if (holder.dataset.near !== "true") { canvas.width = canvas.height = 0; delete holder.dataset.drawn; return } // scrolled away meanwhile
holder.dataset.drawn = "drawn"
holder.replaceChildren(canvas)
} catch (_) {
holder.dataset.drawn = "failed"
holder.replaceChildren(Object.assign(document.createElement("p"), { className: "p-6 text-center text-sm text-slate-500", textContent: t("pdf.page_failed") }))
}
}
// Can't draw it here (an old browser, or not a readable PDF): the browser's own viewer is one tap away.
failed(error) {
if (!this.element.isConnected) return
console.warn("PDF viewer:", error)
this.statusTarget.hidden = false
this.statusTarget.replaceChildren(t("pdf.failed"), " ")
this.statusTarget.append(Object.assign(document.createElement("a"), { href: this.urlValue, target: "_blank", rel: "noopener", className: "link", textContent: t("pdf.open") }))
}
}
+8 -1
View File
@@ -13,7 +13,14 @@
<% if current.image? %>
<%= image_tag rails_blob_path(current, disposition: :inline), alt: current.filename.to_s, class: "max-h-[80vh] max-w-full" %>
<% elsif current.content_type == "application/pdf" %>
<iframe src="<%= rails_blob_path(current, disposition: :inline) %>" class="h-[80vh] w-full"></iframe>
<% pdf_url = rails_blob_path(current, disposition: :inline) %>
<%# Phones get the pages drawn by PDF.js; browsers with a PDF viewer of their own get it in the frame. %>
<div class="w-full space-y-2" data-controller="pdf-viewer" data-pdf-viewer-url-value="<%= pdf_url %>" data-pdf-viewer-pdfjs-value="<%= Rails.application.config.x.pdfjs_path %>">
<template data-pdf-viewer-target="frame"><iframe src="<%= pdf_url %>" title="<%= current.filename %>" class="h-[80vh] w-full"></iframe></template>
<p class="p-6 text-center text-sm text-slate-500" role="status" data-pdf-viewer-target="status"><%= t("js.pdf.loading") %></p>
<div class="space-y-2" data-pdf-viewer-target="pages"></div>
<noscript><iframe src="<%= pdf_url %>" title="<%= current.filename %>" class="h-[80vh] w-full"></iframe></noscript>
</div>
<% else %>
<p class="p-6 text-sm"><%= link_to t(".download", filename: current.filename), rails_blob_path(current, disposition: :attachment), class: "link" %></p>
<% end %>