Compare commits

...

7 Commits

Author SHA1 Message Date
calixteman
9efd9fa2c7
Merge pull request #21071 from Snuffleupagus/BBOX_INIT
Add constants for defining the initial BBox and Float32 BBox
2026-04-09 14:51:56 +02:00
calixteman
b5f52c49d0
Merge pull request #21070 from Snuffleupagus/ChunkedStream-getBytes-non-length-update-pos
Update the position when calling `ChunkedStream.prototype.getBytes` without a length
2026-04-09 14:00:52 +02:00
calixteman
1d48f17b98
Merge pull request #21065 from calixteman/issue19988
Dont revoke blob URLs while printing but do it after
2026-04-09 13:50:34 +02:00
Jonas Jenwald
2d8b25cd6d Update the position when calling ChunkedStream.prototype.getBytes without a length
Currently the code only updates the position when the length is defined, and it seems that this has "always" been wrong. Originally I believe that the `ChunkedStream` class was essentially a copy of the `Stream` class, and that implementation had the same problem until PR 20593.

Hopefully there's no code that relies on the current incorrect behaviour[1], since testing every aspect of the `ChunkedStream` implementation can be tricky given that these things are timing dependant.

---

[1] If there are, fixing those call-sites may be as easy calling `ChunkedStream.prototype.reset`.
2026-04-09 12:15:19 +02:00
Jonas Jenwald
0fd556f435 Take full advantage of the lookupRect helper in the FunctionBasedShading constructor 2026-04-08 20:30:20 +02:00
Jonas Jenwald
654985c621 Add constants for defining the initial BBox and Float32 BBox
Nowadays there's a lot of places in the code-base where we need to initialize or reset bounding boxes. Rather than spelling this out repeatedly, this patch adds new `Array`/`Float32Array` constants that can be copied or used as-is where appropriate.
2026-04-08 20:30:20 +02:00
Calixte Denizet
ea15ac31ef Dont revoke blob URLs while printing but do it after
It fixes #19988.

In Firefox, when printing, the document is cloned and use an image cache
which isn't available when there's a service worker.
2026-04-08 14:04:09 +02:00
13 changed files with 175 additions and 76 deletions

View File

@ -23,6 +23,8 @@ import {
AnnotationType,
assert,
BASELINE_FACTOR,
BBOX_INIT,
F32_BBOX_INIT,
FeatureTest,
getModificationDate,
info,
@ -637,7 +639,7 @@ function getQuadPoints(dict, rect) {
function getTransformMatrix(rect, bbox, matrix) {
// 12.5.5: Algorithm: Appearance streams
const minMax = new Float32Array([Infinity, Infinity, -Infinity, -Infinity]);
const minMax = F32_BBOX_INIT.slice();
Util.axialAlignedBoundingBox(bbox, matrix, minMax);
const [minX, minY, maxX, maxY] = minMax;
if (minX === maxX || minY === maxY) {
@ -1724,7 +1726,7 @@ class MarkupAnnotation extends Annotation {
fillAlpha,
pointsCallback,
}) {
const bbox = (this.data.rect = [Infinity, Infinity, -Infinity, -Infinity]);
const bbox = (this.data.rect = BBOX_INIT.slice());
const buffer = ["q"];
if (extra) {
@ -4463,7 +4465,7 @@ class PolylineAnnotation extends MarkupAnnotation {
// If the /Rect-entry is empty/wrong, create a fallback rectangle so that
// we get similar rendering/highlighting behaviour as in Adobe Reader.
const bbox = [Infinity, Infinity, -Infinity, -Infinity];
const bbox = BBOX_INIT.slice();
for (let i = 0, ii = vertices.length; i < ii; i += 2) {
Util.rectBoundingBox(
vertices[i] - borderAdjust,
@ -4551,7 +4553,7 @@ class InkAnnotation extends MarkupAnnotation {
// If the /Rect-entry is empty/wrong, create a fallback rectangle so that
// we get similar rendering/highlighting behaviour as in Adobe Reader.
const bbox = [Infinity, Infinity, -Infinity, -Infinity];
const bbox = BBOX_INIT.slice();
for (const inkList of this.data.inkLists) {
for (let i = 0, ii = inkList.length; i < ii; i += 2) {
Util.rectBoundingBox(

View File

@ -190,6 +190,7 @@ class ChunkedStream extends Stream {
if (strEnd > this.progressiveDataLength) {
this.ensureRange(pos, strEnd);
}
this.pos = strEnd;
return bytes.subarray(pos, strEnd);
}

View File

@ -16,7 +16,9 @@
import {
AbortException,
assert,
BBOX_INIT,
DrawOPS,
F32_BBOX_INIT,
FONT_IDENTITY_MATRIX,
FormatError,
info,
@ -2309,7 +2311,7 @@ class PartialEvaluator {
pathMinMax.slice(),
]);
pathBuffer.length = 0;
pathMinMax.set([Infinity, Infinity, -Infinity, -Infinity], 0);
pathMinMax.set(BBOX_INIT, 0);
}
continue;
}
@ -4980,7 +4982,7 @@ class TranslatedFont {
// Override the fontBBox when it's undefined/empty, or when it's at least
// (approximately) one order of magnitude smaller than the charBBox
// (fixes issue14999_reduced.pdf).
this._bbox ??= [Infinity, Infinity, -Infinity, -Infinity];
this._bbox ??= BBOX_INIT.slice();
Util.rectBoundingBox(...charBBox, this._bbox);
}
@ -5050,7 +5052,7 @@ class TranslatedFont {
case OPS.constructPath:
const minMax = operatorList.argsArray[i][2];
// Override the fontBBox when it's undefined/empty (fixes 19624.pdf).
this._bbox ??= [Infinity, Infinity, -Infinity, -Infinity];
this._bbox ??= BBOX_INIT.slice();
Util.rectBoundingBox(...minMax, this._bbox);
break;
}
@ -5176,7 +5178,7 @@ class EvalState {
currentPointY = 0;
pathMinMax = new Float32Array([Infinity, Infinity, -Infinity, -Infinity]);
pathMinMax = F32_BBOX_INIT.slice();
pathBuffer = [];
@ -5200,12 +5202,7 @@ class EvalState {
const clone = Object.create(this);
if (newPath) {
clone.pathBuffer = [];
clone.pathMinMax = new Float32Array([
Infinity,
Infinity,
-Infinity,
-Infinity,
]);
clone.pathMinMax = F32_BBOX_INIT.slice();
}
return clone;
}

View File

@ -15,6 +15,7 @@
import {
assert,
BBOX_INIT,
FormatError,
info,
MeshFigureType,
@ -413,20 +414,13 @@ class FunctionBasedShading extends BaseShading {
const fn = pdfFunctionFactory.create(fnObj, /* parseArray = */ true);
// Domain [x0, x1, y0, y1]; defaults to [0, 1, 0, 1].
let x0 = 0,
x1 = 1,
y0 = 0,
y1 = 1;
const domainArr = lookupRect(dict.getArray("Domain"), null);
if (domainArr) {
[x0, x1, y0, y1] = domainArr;
}
const [x0, x1, y0, y1] = lookupRect(dict.getArray("Domain"), [0, 1, 0, 1]);
// Matrix maps shading (domain) space to user space; defaults to identity.
const matrix = lookupMatrix(dict.getArray("Matrix"), IDENTITY_MATRIX);
// Transform the four domain corners to find the user-space bounding box.
this.bounds = [Infinity, Infinity, -Infinity, -Infinity];
this.bounds = BBOX_INIT.slice();
Util.axialAlignedBoundingBox([x0, y0, x1, y1], matrix, this.bounds);
const bboxW = this.bounds[2] - this.bounds[0];

View File

@ -18,6 +18,7 @@ import {
Dependencies,
} from "./canvas_dependency_tracker.js";
import {
F32_BBOX_INIT,
FeatureTest,
FONT_IDENTITY_MATRIX,
ImageKind,
@ -66,14 +67,6 @@ const SCALE_MATRIX = new DOMMatrix();
// Used to get some coordinates.
const XY = new Float32Array(2);
// Initial rectangle values for the minMax array.
const MIN_MAX_INIT = new Float32Array([
Infinity,
Infinity,
-Infinity,
-Infinity,
]);
/**
* Overrides certain methods on a 2d ctx so that when they are called they
* will also call the same method on the destCtx. The methods that are
@ -335,7 +328,7 @@ class CanvasExtraState {
transferMaps = "none";
minMax = MIN_MAX_INIT.slice();
minMax = F32_BBOX_INIT.slice();
constructor(width, height) {
this.clipBox = new Float32Array([0, 0, width, height]);
@ -379,7 +372,7 @@ class CanvasExtraState {
startNewPathAndClipBox(box) {
this.clipBox.set(box, 0);
this.minMax.set(MIN_MAX_INIT, 0);
this.minMax.set(F32_BBOX_INIT, 0);
}
getClippedPathBoundingBox(pathType = PathType.FILL, transform = null) {
@ -1056,7 +1049,7 @@ class CanvasGraphics {
0,
]);
maskToCanvas = Util.transform(maskToCanvas, [1, 0, 0, 1, 0, -height]);
const minMax = MIN_MAX_INIT.slice();
const minMax = F32_BBOX_INIT.slice();
Util.axialAlignedBoundingBox([0, 0, width, height], maskToCanvas, minMax);
const [minX, minY, maxX, maxY] = minMax;
const drawnWidth = Math.round(maxX - minX) || 1;
@ -2529,7 +2522,7 @@ class CanvasGraphics {
const inv = getCurrentTransformInverse(ctx);
if (inv) {
const { width, height } = ctx.canvas;
const minMax = MIN_MAX_INIT.slice();
const minMax = F32_BBOX_INIT.slice();
Util.axialAlignedBoundingBox([0, 0, width, height], inv, minMax);
const [x0, y0, x1, y1] = minMax;
@ -2675,7 +2668,7 @@ class CanvasGraphics {
let bounds;
if (group.bbox) {
bounds = MIN_MAX_INIT.slice();
bounds = F32_BBOX_INIT.slice();
Util.axialAlignedBoundingBox(
group.bbox,
getCurrentTransform(currentCtx),
@ -2804,7 +2797,7 @@ class CanvasGraphics {
this.restore(opIdx);
this.ctx.save();
this.ctx.setTransform(...currentMtx);
const dirtyBox = MIN_MAX_INIT.slice();
const dirtyBox = F32_BBOX_INIT.slice();
Util.axialAlignedBoundingBox(
[0, 0, groupCtx.canvas.width, groupCtx.canvas.height],
currentMtx,

View File

@ -13,7 +13,7 @@
* limitations under the License.
*/
import { FeatureTest, Util } from "../shared/util.js";
import { BBOX_INIT, FeatureTest, Util } from "../shared/util.js";
import { MathClamp } from "../shared/math_clamp.js";
const FORCED_DEPENDENCY_LABEL = "__forcedDependency";
@ -81,7 +81,7 @@ class CanvasBBoxTracker {
#clipBox = [-Infinity, -Infinity, Infinity, Infinity];
// Float32Array<minX, minY, maxX, maxY>
#pendingBBox = new Float64Array([Infinity, Infinity, -Infinity, -Infinity]);
#pendingBBox = new Float64Array(BBOX_INIT);
_pendingBBoxIdx = -1;
@ -209,10 +209,7 @@ class CanvasBBoxTracker {
resetBBox(idx) {
if (this._pendingBBoxIdx !== idx) {
this._pendingBBoxIdx = idx;
this.#pendingBBox[0] = Infinity;
this.#pendingBBox[1] = Infinity;
this.#pendingBBox[2] = -Infinity;
this.#pendingBBox[3] = -Infinity;
this.#pendingBBox.set(BBOX_INIT, 0);
}
return this;
}
@ -222,7 +219,7 @@ class CanvasBBoxTracker {
this.#baseTransformStack.at(-1),
ctx.getTransform()
);
const clipBox = [Infinity, Infinity, -Infinity, -Infinity];
const clipBox = BBOX_INIT.slice();
Util.axialAlignedBoundingBox([minX, minY, maxX, maxY], transform, clipBox);
const intersection = Util.intersect(this.#clipBox, clipBox);
if (intersection) {
@ -256,7 +253,7 @@ class CanvasBBoxTracker {
return this;
}
const bbox = [Infinity, Infinity, -Infinity, -Infinity];
const bbox = BBOX_INIT.slice();
Util.axialAlignedBoundingBox([minX, minY, maxX, maxY], transform, bbox);
this.#pendingBBox[0] = MathClamp(bbox[0], clipBox[0], this.#pendingBBox[0]);
@ -1130,7 +1127,7 @@ class CanvasImagesTracker {
let coords;
if (clipBox[0] !== Infinity) {
const bbox = [Infinity, Infinity, -Infinity, -Infinity];
const bbox = BBOX_INIT.slice();
Util.axialAlignedBoundingBox([0, -height, width, 0], transform, bbox);
const finalBBox = Util.intersect(clipBox, bbox);

View File

@ -13,8 +13,8 @@
* limitations under the License.
*/
import { BBOX_INIT, Util } from "../../../shared/util.js";
import { Outline } from "./outline.js";
import { Util } from "../../../shared/util.js";
class FreeDrawOutliner {
#box;
@ -588,22 +588,14 @@ class FreeDrawOutline extends Outline {
lastPointX = ltrCallback(lastPointX, x);
}
} else {
bezierBbox[0] = bezierBbox[1] = Infinity;
bezierBbox[2] = bezierBbox[3] = -Infinity;
bezierBbox.set(BBOX_INIT, 0);
Util.bezierBoundingBox(
lastX,
lastY,
...outline.slice(i, i + 6),
bezierBbox
);
Util.rectBoundingBox(
bezierBbox[0],
bezierBbox[1],
bezierBbox[2],
bezierBbox[3],
minMax
);
Util.rectBoundingBox(...bezierBbox, minMax);
if (firstPointY > bezierBbox[1]) {
firstPointX = bezierBbox[0];

View File

@ -13,9 +13,9 @@
* limitations under the License.
*/
import { BBOX_INIT, Util } from "../../../shared/util.js";
import { FreeDrawOutline, FreeDrawOutliner } from "./freedraw.js";
import { Outline } from "./outline.js";
import { Util } from "../../../shared/util.js";
class HighlightOutliner {
#box;
@ -41,7 +41,7 @@ class HighlightOutliner {
* the last point of the boxes.
*/
constructor(boxes, borderWidth = 0, innerMargin = 0, isLTR = true) {
const minMax = [Infinity, Infinity, -Infinity, -Infinity];
const minMax = BBOX_INIT.slice();
// We round the coordinates to slightly reduce the number of edges in the
// final outlines.

View File

@ -13,9 +13,9 @@
* limitations under the License.
*/
import { F32_BBOX_INIT, Util } from "../../../shared/util.js";
import { MathClamp } from "../../../shared/math_clamp.js";
import { Outline } from "./outline.js";
import { Util } from "../../../shared/util.js";
class InkDrawOutliner {
// The last 3 points of the line.
@ -587,12 +587,7 @@ class InkDrawOutline extends Outline {
}
#computeBbox() {
const bbox = (this.#bbox = new Float32Array([
Infinity,
Infinity,
-Infinity,
-Infinity,
]));
const bbox = (this.#bbox = F32_BBOX_INIT.slice());
for (const { line } of this.#lines) {
if (line.length <= 12) {

View File

@ -13,7 +13,13 @@
* limitations under the License.
*/
import { assert, FeatureTest, MeshFigureType, Util } from "../shared/util.js";
import {
assert,
BBOX_INIT,
FeatureTest,
MeshFigureType,
Util,
} from "../shared/util.js";
import {
CSS_FONT_INFO,
FONT_INFO,
@ -438,7 +444,7 @@ class PatternInfo {
const shadingType = this.data[PATTERN_INFO.SHADING_TYPE];
let bounds = null;
if (coords.length > 0) {
bounds = [Infinity, Infinity, -Infinity, -Infinity];
bounds = BBOX_INIT.slice();
for (let i = 0, ii = coords.length; i < ii; i += 2) {
Util.pointBoundingBox(coords[i], coords[i + 1], bounds);

View File

@ -25,6 +25,9 @@ const isNodeJS =
!process.versions.nw &&
!(process.versions.electron && process.type && process.type !== "browser");
const BBOX_INIT = [Infinity, Infinity, -Infinity, -Infinity];
const F32_BBOX_INIT = new Float32Array(BBOX_INIT);
const FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0];
// Represent the percentage of the height of a single-line field over
@ -1310,10 +1313,12 @@ export {
assert,
BaseException,
BASELINE_FACTOR,
BBOX_INIT,
bytesToString,
createValidAbsoluteUrl,
DocumentActionEventType,
DrawOPS,
F32_BBOX_INIT,
FeatureTest,
FONT_IDENTITY_MATRIX,
FormatError,

View File

@ -1784,4 +1784,113 @@ describe("PDF viewer", () => {
);
});
});
describe("PDFPrintService", () => {
describe("blob URL revocation (issue #19988)", () => {
let pages;
beforeEach(async () => {
pages = await loadAndWait(
"basicapi.pdf",
".textLayer .endOfContent",
null,
{
earlySetup: () => {
// Track blob URLs created during the print phase (between
// beforeprint and afterprint).
let trackPrintURLs = false;
window._printBlobURLs = [];
const origCreate = URL.createObjectURL.bind(URL);
URL.createObjectURL = blob => {
const url = origCreate(blob);
if (trackPrintURLs) {
window._printBlobURLs.push(url);
}
return url;
};
// beforeprint fires before renderPages(); start tracking here.
window.addEventListener("beforeprint", () => {
trackPrintURLs = true;
});
// window.print() is called by performPrint() after renderPages()
// completes and all images are loaded into #printContainer.
window.print = () => {
const isFirefox = navigator.userAgent.includes("Firefox");
if (isFirefox) {
// Firefox re-fetches blob URLs when rendering the print
// preview (especially when a service worker is registered).
// Verify the URLs are still accessible at this point.
window._printImagesAccessible = Promise.all(
window._printBlobURLs.map(url =>
fetch(url).then(
() => true,
() => false
)
)
);
} else {
// Chrome uses the cached decoded data already in the <img>
// elements and does not re-fetch blob URLs for printing.
// Just verify the images rendered correctly.
const imgs = document.querySelectorAll("#printContainer img");
window._printImagesAccessible = Promise.resolve(
Array.from(imgs).map(
img => img.complete && img.naturalWidth > 0
)
);
}
};
},
appSetup: app => {
app._testPrintResolver = Promise.withResolvers();
},
eventBusSetup: eventBus => {
eventBus.on(
"afterprint",
() => {
// Wait for the checks initiated in window.print() before
// resolving, so the test can assert on them.
(window._printImagesAccessible ?? Promise.resolve([])).then(
window.PDFViewerApplication._testPrintResolver.resolve
);
},
{ once: true }
);
},
}
);
});
afterEach(async () => {
await closePages(pages);
});
it("must keep print image blob URLs accessible until destroy() is called", async () => {
await Promise.all(
pages.map(async ([browserName, page]) => {
await waitAndClick(page, "#printButton");
// Resolves with an array of booleans, one per print page image.
const accessible = await awaitPromise(
await page.evaluateHandle(() => [
window.PDFViewerApplication._testPrintResolver.promise,
])
);
expect(accessible.length)
.withContext(`In ${browserName}: print pages were rendered`)
.toBeGreaterThan(0);
expect(accessible.every(v => v))
.withContext(
`In ${browserName}: all print images accessible at print time`
)
.toBeTrue();
})
);
});
});
});
});

View File

@ -144,6 +144,12 @@ class PDFPrintService {
this.pageStyleSheet.remove();
this.pageStyleSheet = null;
}
if (this._blobURLs) {
for (const url of this._blobURLs) {
URL.revokeObjectURL(url);
}
this._blobURLs = null;
}
this.scratchCanvas.width = this.scratchCanvas.height = 0;
this.scratchCanvas = null;
activeService = null;
@ -189,7 +195,13 @@ class PDFPrintService {
this.throwIfInactive();
const img = document.createElement("img");
this.scratchCanvas.toBlob(blob => {
img.src = URL.createObjectURL(blob);
const blobURL = URL.createObjectURL(blob);
img.src = blobURL;
// Defer revocation until after printing completes (in destroy()) to avoid
// broken print images in Firefox when a service worker is registered,
// since Firefox re-fetches blob URLs when rendering the print dialog.
// See https://github.com/mozilla/pdf.js/issues/19988
(this._blobURLs ??= []).push(blobURL);
});
const wrapper = document.createElement("div");
@ -201,13 +213,9 @@ class PDFPrintService {
img.onload = resolve;
img.onerror = reject;
promise
.catch(() => {
// Avoid "Uncaught promise" messages in the console.
})
.then(() => {
URL.revokeObjectURL(img.src);
});
promise.catch(() => {
// Avoid "Uncaught promise" messages in the console.
});
return promise;
}