Compare commits

..

No commits in common. "20b6e32907f49006f8bb94e491126641442da540" and "2305c6416e4d214a79304a2295ad2380471b0ee1" have entirely different histories.

8 changed files with 112 additions and 262 deletions

View File

@ -11,7 +11,7 @@ const STANDARD_FONT_DATA_URL =
// Loading file from file system into typed array. // Loading file from file system into typed array.
const pdfPath = const pdfPath =
process.argv[2] || "C:\\Users\\kj131\\pdf-forge\\test_pdfs\\ISO_32000-2_2020(en).pdf"; process.argv[2] || "../../web/compressed.tracemonkey-pldi-09.pdf";
const data = new Uint8Array(fs.readFileSync(pdfPath)); const data = new Uint8Array(fs.readFileSync(pdfPath));
// Load the PDF file. // Load the PDF file.
@ -21,46 +21,12 @@ const loadingTask = getDocument({
cMapPacked: CMAP_PACKED, cMapPacked: CMAP_PACKED,
standardFontDataUrl: STANDARD_FONT_DATA_URL, standardFontDataUrl: STANDARD_FONT_DATA_URL,
}); });
test(loadingTask); try {
async function test(loading) { const pdfDocument = await loadingTask.promise;
try { console.log("# PDF document loaded.");
const pdfDocument = await loading.promise; const page = await pdfDocument.getPage(1);
console.log("# PDF document loaded.");
const page = await pdfDocument.getPage(4);
printOpList(page);
console.time("contents");
const contents = await page.getContents();
console.timeEnd("contents");
console.time("oplist");
const opList = await page.getOperatorList();
console.timeEnd("oplist");
// console.log(opList);
let newContents = "";
for (let i = 0; i < 5; i++) {
const range = opList.rangeArray[i];
if (range) {
newContents += contents.slice(range[0], range[1]);
newContents += "\n";
}
}
console.log(newContents);
await page.updateContents(newContents);
await printOpList(page);
} catch (e) {
console.error(e);
}
}
async function printOpList(page) {
const contents = await page.getContents();
const opList = await page.getOperatorList(); const opList = await page.getOperatorList();
// console.log(opList); console.log(opList);
const ops = []; } catch (e) {
for (let i = 0; i < opList.rangeArray.length; i++) { console.error(e);
const range = opList.rangeArray[i];
if (range) {
ops.push(contents.slice(range[0], range[1]));
}
}
console.log(ops.slice(0, 100));
} }

View File

@ -45,7 +45,7 @@ function bytesToString(bytes) {
} }
async function parse(doc) { async function parse(doc) {
const path = "/Page2/Contents/1"; const path = "/Page2/Contents/2";
let [stream] = await getPrimitive(path, doc); let [stream] = await getPrimitive(path, doc);
const lexer = new Lexer(stream); const lexer = new Lexer(stream);
const parser = new Parser({ lexer, xref: doc.xref, trackRanges: true }); const parser = new Parser({ lexer, xref: doc.xref, trackRanges: true });
@ -63,12 +63,12 @@ async function parse(doc) {
const bytes = stream.getBytes(); const bytes = stream.getBytes();
const classes = new Set(); const classes = new Set();
for (const o of objs) { for (const o of objs) {
// console.log(o[0].constructor.name); console.log(o[0].constructor.name);
classes.add(o[0].constructor.name); classes.add(o[0].constructor.name);
const lexemmeBytes = bytes.slice(o[1], o[2]); const lexemmeBytes = bytes.slice(o[1], o[2]);
// console.log(bytesToString(lexemmeBytes)); console.log(bytesToString(lexemmeBytes));
} }
// console.log("unique classes", classes); console.log("unique classes", classes);
[stream] = await getPrimitive(path, doc); [stream] = await getPrimitive(path, doc);
const preprocessor = new EvaluatorPreprocessor(stream, doc.xref); const preprocessor = new EvaluatorPreprocessor(stream, doc.xref);
const operation = {}; const operation = {};
@ -78,10 +78,10 @@ async function parse(doc) {
const fn = operation.fn; const fn = operation.fn;
const range = operation.range; const range = operation.range;
const op = bytesToString(bytes.slice(range[0], range[1])); const op = bytesToString(bytes.slice(range[0], range[1]));
// console.log(args, fn); console.log(args, fn);
// console.log(`----------------- ${range} -------------------`); console.log(`${range[0]}------------------------------------`);
console.log(`${fn}: ${op}`); console.log(op);
// console.log(`---------------------------------------------`); console.log(`${range[1]}------------------------------------`);
} }
// console.time("xref"); // console.time("xref");
// let table = await retrieveXref(doc); // let table = await retrieveXref(doc);

View File

@ -65,7 +65,7 @@ import { Catalog } from "./catalog.js";
import { clearGlobalCaches } from "./cleanup_helper.js"; import { clearGlobalCaches } from "./cleanup_helper.js";
import { DatasetReader } from "./dataset_reader.js"; import { DatasetReader } from "./dataset_reader.js";
import { Linearization } from "./parser.js"; import { Linearization } from "./parser.js";
import { NullStream, StringStream } from "./stream.js"; import { NullStream } from "./stream.js";
import { ObjectLoader } from "./object_loader.js"; import { ObjectLoader } from "./object_loader.js";
import { OperatorList } from "./operator_list.js"; import { OperatorList } from "./operator_list.js";
import { PartialEvaluator } from "./evaluator.js"; import { PartialEvaluator } from "./evaluator.js";
@ -107,8 +107,6 @@ class Page {
this.resourcesPromise = null; this.resourcesPromise = null;
this.xfaFactory = xfaFactory; this.xfaFactory = xfaFactory;
this.updatedContents = null;
const idCounters = { const idCounters = {
obj: 0, obj: 0,
}; };
@ -248,19 +246,10 @@ class Page {
throw reason; throw reason;
} }
setContents(newContents) {
this.updatedContents = newContents;
}
/** /**
* @returns {Promise<BaseStream>} * @returns {Promise<BaseStream>}
*/ */
getContentStream() { getContentStream() {
if (this.updatedContents !== null) {
return new Promise(resolve => {
resolve(new StringStream(this.updatedContents));
});
}
return this.pdfManager.ensure(this, "content").then(content => { return this.pdfManager.ensure(this, "content").then(content => {
if (content instanceof BaseStream) { if (content instanceof BaseStream) {
return content; return content;
@ -437,11 +426,8 @@ class Page {
cacheKey, cacheKey,
annotationStorage = null, annotationStorage = null,
modifiedIds = null, modifiedIds = null,
contentOverride = null,
}) { }) {
const contentStreamPromise = contentOverride const contentStreamPromise = this.getContentStream();
? new StringStream(contentOverride)
: this.getContentStream();
const resourcesPromise = this.loadResources([ const resourcesPromise = this.loadResources([
"ColorSpace", "ColorSpace",
"ExtGState", "ExtGState",

View File

@ -802,7 +802,6 @@ class PartialEvaluator {
operatorList.addImageOps( operatorList.addImageOps(
OPS.paintImageXObject, OPS.paintImageXObject,
args, args,
range,
optionalContent, optionalContent,
hasMask hasMask
); );
@ -1446,20 +1445,15 @@ class PartialEvaluator {
minMax = [Infinity, Infinity, -Infinity, -Infinity]; minMax = [Infinity, Infinity, -Infinity, -Infinity];
break; break;
} }
operatorList.addOp( operatorList.addOp(OPS.constructPath, [[fn], args, minMax], range);
OPS.constructPath,
[[fn], args, minMax, [range[0], range[1]]],
range
);
if (parsingText) { if (parsingText) {
operatorList.addOp(OPS.restore, null); operatorList.addOp(OPS.restore, null, range);
} }
} else { } else {
const opArgs = operatorList.argsArray[lastIndex]; const opArgs = operatorList.argsArray[lastIndex];
opArgs[0].push(fn); opArgs[0].push(fn);
opArgs[1].push(...args); opArgs[1].push(...args);
opArgs[3].push(...range);
const minMax = opArgs[2]; const minMax = opArgs[2];
const opRange = operatorList.rangeArray[lastIndex]; const opRange = operatorList.rangeArray[lastIndex];
@ -5221,7 +5215,7 @@ class EvaluatorPreprocessor {
operation.fn = fn; operation.fn = fn;
operation.args = args; operation.args = args;
const end = this.parser.getEnd(); const end = this.parser.getPosition();
operation.range = [start, end]; operation.range = [start, end];
return true; return true;
} }

View File

@ -59,39 +59,54 @@ function getInlineImageCacheKey(bytes) {
} }
class Parser { class Parser {
constructor({ lexer, xref, allowStreams = false, recoveryMode = false }) { constructor({
lexer,
xref,
allowStreams = false,
recoveryMode = false,
trackRanges = true,
}) {
this.lexer = lexer; this.lexer = lexer;
this.xref = xref; this.xref = xref;
this.allowStreams = allowStreams; this.allowStreams = allowStreams;
this.recoveryMode = recoveryMode; this.recoveryMode = recoveryMode;
this.withRange = trackRanges;
this.imageCache = Object.create(null); this.imageCache = Object.create(null);
this._imageId = 0; this._imageId = 0;
this.refill(); this.refill();
} }
refill() { refill() {
const [buf1, start1, end1] = this.lexer.getObjWithRange(); if (this.withRange) {
const [buf2, start2, end2] = this.lexer.getObjWithRange(); const [buf1, start1, end1] = this.lexer.getObjWithRange();
this.buf1 = buf1; const [buf2, start2, end2] = this.lexer.getObjWithRange();
this.range1 = [start1, end1]; this.buf1 = buf1;
this.buf2 = buf2; this.range1 = [start1, end1];
this.range2 = [start2, end2]; this.buf2 = buf2;
this.range2 = [start2, end2];
} else {
this.buf1 = this.lexer.getObj();
this.buf2 = this.lexer.getObj();
}
} }
shift() { shift() {
if (this.buf2 instanceof Cmd && this.buf2.cmd === "ID") { if (this.buf2 instanceof Cmd && this.buf2.cmd === "ID") {
this.buf1 = this.buf2; this.buf1 = this.buf2;
this.buf2 = null; this.buf2 = null;
this.lastEnd = this.range1[1]; if (this.withRange) {
this.range1 = this.range2; this.range1 = this.range2;
this.range2 = null; this.range2 = null;
} else { }
} else if (this.withRange) {
this.buf1 = this.buf2; this.buf1 = this.buf2;
this.lastEnd = this.range1[1];
this.range1 = this.range2; this.range1 = this.range2;
const [buf2, start2, end2] = this.lexer.getObjWithRange(); const [buf2, start2, end2] = this.lexer.getObjWithRange();
this.buf2 = buf2; this.buf2 = buf2;
this.range2 = [start2, end2]; this.range2 = [start2, end2];
} else {
this.buf1 = this.buf2;
this.buf2 = this.lexer.getObj();
} }
} }
@ -113,10 +128,6 @@ class Parser {
return this.range1 ? this.range1[0] : 0; return this.range1 ? this.range1[0] : 0;
} }
getEnd() {
return this.lastEnd ?? 0;
}
getObjWithRange(cipherTransform = null) { getObjWithRange(cipherTransform = null) {
const start = this.range1[0]; const start = this.range1[0];
const obj = this.getObj(cipherTransform); const obj = this.getObj(cipherTransform);
@ -1230,18 +1241,14 @@ class Lexer {
} }
getObjWithRange() { getObjWithRange() {
const ch = this._skipWhitespaceAndComments(); // at the start of getObj() the stream has stepped beyond currentChar by one
if (ch === EOF) { const start = this.stream.pos - 1;
return [ch, -1, -1];
}
// currentChar is always at pos - 1
const start = Math.max(this.stream.pos - 1, 0);
const obj = this.getObj(); const obj = this.getObj();
const end = this.stream.pos - 1; const end = this.stream.pos;
return [obj, start, end]; return [obj, start, end];
} }
_skipWhitespaceAndComments() { getObj() {
// Skip whitespace and comments. // Skip whitespace and comments.
let comment = false; let comment = false;
let ch = this.currentChar; let ch = this.currentChar;
@ -1260,14 +1267,7 @@ class Lexer {
} }
ch = this.nextChar(); ch = this.nextChar();
} }
return ch;
}
getObj() {
let ch = this._skipWhitespaceAndComments();
if (ch === EOF) {
return ch;
}
// Start reading a token. // Start reading a token.
switch (ch | 0) { switch (ch | 0) {
case 0x30: // '0' case 0x30: // '0'

View File

@ -123,7 +123,7 @@ class WorkerMessageHandler {
if (apiVersion !== workerVersion) { if (apiVersion !== workerVersion) {
throw new Error( throw new Error(
`The API version "${apiVersion}" does not match ` + `The API version "${apiVersion}" does not match ` +
`the Worker version "${workerVersion}".` `the Worker version "${workerVersion}".`
); );
} }
@ -141,8 +141,8 @@ class WorkerMessageHandler {
if (enumerableProperties.length) { if (enumerableProperties.length) {
throw new Error( throw new Error(
"The `Array.prototype` contains unexpected enumerable properties: " + "The `Array.prototype` contains unexpected enumerable properties: " +
enumerableProperties.join(", ") + enumerableProperties.join(", ") +
"; thus breaking e.g. `for...in` iteration of `Array`s." "; thus breaking e.g. `for...in` iteration of `Array`s."
); );
} }
} }
@ -206,15 +206,15 @@ class WorkerMessageHandler {
} }
async function getPdfManager({ async function getPdfManager({
data, data,
password, password,
disableAutoFetch, disableAutoFetch,
rangeChunkSize, rangeChunkSize,
length, length,
docBaseUrl, docBaseUrl,
enableXfa, enableXfa,
evaluatorOptions, evaluatorOptions,
}) { }) {
const pdfManagerArgs = { const pdfManagerArgs = {
source: null, source: null,
disableAutoFetch, disableAutoFetch,
@ -242,7 +242,7 @@ class WorkerMessageHandler {
loaded = 0; loaded = 0;
fullRequest.headersReady fullRequest.headersReady
.then(function() { .then(function () {
if (!fullRequest.isRangeSupported) { if (!fullRequest.isRangeSupported) {
return; return;
} }
@ -263,13 +263,13 @@ class WorkerMessageHandler {
pdfManagerCapability.resolve(newPdfManager); pdfManagerCapability.resolve(newPdfManager);
cancelXHRs = null; cancelXHRs = null;
}) })
.catch(function(reason) { .catch(function (reason) {
pdfManagerCapability.reject(reason); pdfManagerCapability.reject(reason);
cancelXHRs = null; cancelXHRs = null;
}); });
new Promise(function(resolve, reject) { new Promise(function (resolve, reject) {
const readChunk = function({ value, done }) { const readChunk = function ({ value, done }) {
try { try {
ensureNotTerminated(); ensureNotTerminated();
if (done) { if (done) {
@ -314,7 +314,7 @@ class WorkerMessageHandler {
} }
}; };
fullRequest.read().then(readChunk, reject); fullRequest.read().then(readChunk, reject);
}).catch(function(e) { }).catch(function (e) {
pdfManagerCapability.reject(e); pdfManagerCapability.reject(e);
cancelXHRs = null; cancelXHRs = null;
}); });
@ -341,12 +341,12 @@ class WorkerMessageHandler {
handler handler
.sendWithPromise("PasswordRequest", ex) .sendWithPromise("PasswordRequest", ex)
.then(function({ password }) { .then(function ({ password }) {
finishWorkerTask(task); finishWorkerTask(task);
pdfManager.updatePassword(password); pdfManager.updatePassword(password);
pdfManagerReady(); pdfManagerReady();
}) })
.catch(function() { .catch(function () {
finishWorkerTask(task); finishWorkerTask(task);
handler.send("DocException", ex); handler.send("DocException", ex);
}); });
@ -359,7 +359,7 @@ class WorkerMessageHandler {
function pdfManagerReady() { function pdfManagerReady() {
ensureNotTerminated(); ensureNotTerminated();
loadDocument(false).then(onSuccess, function(reason) { loadDocument(false).then(onSuccess, function (reason) {
ensureNotTerminated(); ensureNotTerminated();
// Try again with recoveryMode == true // Try again with recoveryMode == true
@ -367,7 +367,7 @@ class WorkerMessageHandler {
onFailure(reason); onFailure(reason);
return; return;
} }
pdfManager.requestLoadedStream().then(function() { pdfManager.requestLoadedStream().then(function () {
ensureNotTerminated(); ensureNotTerminated();
loadDocument(true).then(onSuccess, onFailure); loadDocument(true).then(onSuccess, onFailure);
@ -378,7 +378,7 @@ class WorkerMessageHandler {
ensureNotTerminated(); ensureNotTerminated();
getPdfManager(data) getPdfManager(data)
.then(function(newPdfManager) { .then(function (newPdfManager) {
if (terminated) { if (terminated) {
// We were in a process of setting up the manager, but it got // We were in a process of setting up the manager, but it got
// terminated in the middle. // terminated in the middle.
@ -396,14 +396,14 @@ class WorkerMessageHandler {
.then(pdfManagerReady, onFailure); .then(pdfManagerReady, onFailure);
} }
handler.on("GetPage", function(data) { handler.on("GetPage", function (data) {
return pdfManager.getPage(data.pageIndex).then(function(page) { return pdfManager.getPage(data.pageIndex).then(function (page) {
return Promise.all([ return Promise.all([
pdfManager.ensure(page, "rotate"), pdfManager.ensure(page, "rotate"),
pdfManager.ensure(page, "ref"), pdfManager.ensure(page, "ref"),
pdfManager.ensure(page, "userUnit"), pdfManager.ensure(page, "userUnit"),
pdfManager.ensure(page, "view"), pdfManager.ensure(page, "view"),
]).then(function([rotate, ref, userUnit, view]) { ]).then(function ([rotate, ref, userUnit, view]) {
return { return {
rotate, rotate,
ref, ref,
@ -415,104 +415,104 @@ class WorkerMessageHandler {
}); });
}); });
handler.on("GetPageIndex", function(data) { handler.on("GetPageIndex", function (data) {
const pageRef = Ref.get(data.num, data.gen); const pageRef = Ref.get(data.num, data.gen);
return pdfManager.ensureCatalog("getPageIndex", [pageRef]); return pdfManager.ensureCatalog("getPageIndex", [pageRef]);
}); });
handler.on("GetDestinations", function(data) { handler.on("GetDestinations", function (data) {
return pdfManager.ensureCatalog("destinations"); return pdfManager.ensureCatalog("destinations");
}); });
handler.on("GetDestination", function(data) { handler.on("GetDestination", function (data) {
return pdfManager.ensureCatalog("getDestination", [data.id]); return pdfManager.ensureCatalog("getDestination", [data.id]);
}); });
handler.on("GetPageLabels", function(data) { handler.on("GetPageLabels", function (data) {
return pdfManager.ensureCatalog("pageLabels"); return pdfManager.ensureCatalog("pageLabels");
}); });
handler.on("GetPageLayout", function(data) { handler.on("GetPageLayout", function (data) {
return pdfManager.ensureCatalog("pageLayout"); return pdfManager.ensureCatalog("pageLayout");
}); });
handler.on("GetPageMode", function(data) { handler.on("GetPageMode", function (data) {
return pdfManager.ensureCatalog("pageMode"); return pdfManager.ensureCatalog("pageMode");
}); });
handler.on("GetViewerPreferences", function(data) { handler.on("GetViewerPreferences", function (data) {
return pdfManager.ensureCatalog("viewerPreferences"); return pdfManager.ensureCatalog("viewerPreferences");
}); });
handler.on("GetOpenAction", function(data) { handler.on("GetOpenAction", function (data) {
return pdfManager.ensureCatalog("openAction"); return pdfManager.ensureCatalog("openAction");
}); });
handler.on("GetAttachments", function(data) { handler.on("GetAttachments", function (data) {
return pdfManager.ensureCatalog("attachments"); return pdfManager.ensureCatalog("attachments");
}); });
handler.on("GetDocJSActions", function(data) { handler.on("GetDocJSActions", function (data) {
return pdfManager.ensureCatalog("jsActions"); return pdfManager.ensureCatalog("jsActions");
}); });
handler.on("GetPageJSActions", function({ pageIndex }) { handler.on("GetPageJSActions", function ({ pageIndex }) {
return pdfManager.getPage(pageIndex).then(function(page) { return pdfManager.getPage(pageIndex).then(function (page) {
return pdfManager.ensure(page, "jsActions"); return pdfManager.ensure(page, "jsActions");
}); });
}); });
handler.on("GetOutline", function(data) { handler.on("GetOutline", function (data) {
return pdfManager.ensureCatalog("documentOutline"); return pdfManager.ensureCatalog("documentOutline");
}); });
handler.on("GetOptionalContentConfig", function(data) { handler.on("GetOptionalContentConfig", function (data) {
return pdfManager.ensureCatalog("optionalContentConfig"); return pdfManager.ensureCatalog("optionalContentConfig");
}); });
handler.on("GetPermissions", function(data) { handler.on("GetPermissions", function (data) {
return pdfManager.ensureCatalog("permissions"); return pdfManager.ensureCatalog("permissions");
}); });
handler.on("GetMetadata", function(data) { handler.on("GetMetadata", function (data) {
return Promise.all([ return Promise.all([
pdfManager.ensureDoc("documentInfo"), pdfManager.ensureDoc("documentInfo"),
pdfManager.ensureCatalog("metadata"), pdfManager.ensureCatalog("metadata"),
]); ]);
}); });
handler.on("GetMarkInfo", function(data) { handler.on("GetMarkInfo", function (data) {
return pdfManager.ensureCatalog("markInfo"); return pdfManager.ensureCatalog("markInfo");
}); });
handler.on("GetData", function(data) { handler.on("GetData", function (data) {
return pdfManager.requestLoadedStream().then(function(stream) { return pdfManager.requestLoadedStream().then(function (stream) {
return stream.bytes; return stream.bytes;
}); });
}); });
handler.on("GetPrimitiveByPath", function(path_str) { handler.on("GetPrimitiveByPath", function (path_str) {
return getPrim(path_str, pdfManager.pdfDocument); return getPrim(path_str, pdfManager.pdfDocument);
}); });
handler.on("GetXRefEntries", function(data) { handler.on("GetXRefEntries", function (data) {
return retrieveXref(pdfManager.pdfDocument); return retrieveXref(pdfManager.pdfDocument);
}); });
handler.on("GetPrimTree", function(request) { handler.on("GetPrimTree", function (request) {
return getPrimTree(request, pdfManager.pdfDocument); return getPrimTree(request, pdfManager.pdfDocument);
}); });
handler.on("GetImageData", function(path) { handler.on("GetImageData", function (path) {
return getImageAsBlob(path, pdfManager.pdfDocument); return getImageAsBlob(path, pdfManager.pdfDocument);
}); });
handler.on("GetStreamAsString", function(path) { handler.on("GetStreamAsString", function (path) {
return getStreamAsString(path, pdfManager.pdfDocument); return getStreamAsString(path, pdfManager.pdfDocument);
}); });
handler.on("GetAnnotations", function({ pageIndex, intent }) { handler.on("GetAnnotations", function ({ pageIndex, intent }) {
return pdfManager.getPage(pageIndex).then(function(page) { return pdfManager.getPage(pageIndex).then(function (page) {
const task = new WorkerTask(`GetAnnotations: page ${pageIndex}`); const task = new WorkerTask(`GetAnnotations: page ${pageIndex}`);
startWorkerTask(task); startWorkerTask(task);
@ -529,23 +529,23 @@ class WorkerMessageHandler {
}); });
}); });
handler.on("GetFieldObjects", function(data) { handler.on("GetFieldObjects", function (data) {
return pdfManager return pdfManager
.ensureDoc("fieldObjects") .ensureDoc("fieldObjects")
.then(fieldObjects => fieldObjects?.allFields || null); .then(fieldObjects => fieldObjects?.allFields || null);
}); });
handler.on("HasJSActions", function(data) { handler.on("HasJSActions", function (data) {
return pdfManager.ensureDoc("hasJSActions"); return pdfManager.ensureDoc("hasJSActions");
}); });
handler.on("GetCalculationOrderIds", function(data) { handler.on("GetCalculationOrderIds", function (data) {
return pdfManager.ensureDoc("calculationOrderIds"); return pdfManager.ensureDoc("calculationOrderIds");
}); });
handler.on( handler.on(
"SaveDocument", "SaveDocument",
async function({ isPureXfa, numPages, annotationStorage, filename }) { async function ({ isPureXfa, numPages, annotationStorage, filename }) {
const globalPromises = [ const globalPromises = [
pdfManager.requestLoadedStream(), pdfManager.requestLoadedStream(),
pdfManager.ensureCatalog("acroForm"), pdfManager.ensureCatalog("acroForm"),
@ -615,7 +615,7 @@ class WorkerMessageHandler {
imagePromises, imagePromises,
changes changes
) )
.finally(function() { .finally(function () {
finishWorkerTask(task); finishWorkerTask(task);
}); });
}) })
@ -652,13 +652,13 @@ class WorkerMessageHandler {
} else { } else {
for (let pageIndex = 0; pageIndex < numPages; pageIndex++) { for (let pageIndex = 0; pageIndex < numPages; pageIndex++) {
promises.push( promises.push(
pdfManager.getPage(pageIndex).then(function(page) { pdfManager.getPage(pageIndex).then(function (page) {
const task = new WorkerTask(`Save: page ${pageIndex}`); const task = new WorkerTask(`Save: page ${pageIndex}`);
startWorkerTask(task); startWorkerTask(task);
return page return page
.save(handler, task, annotationStorage, changes) .save(handler, task, annotationStorage, changes)
.finally(function() { .finally(function () {
finishWorkerTask(task); finishWorkerTask(task);
}); });
}) })
@ -748,31 +748,6 @@ class WorkerMessageHandler {
} }
); );
handler.on("StreamContents", function(data, sink) {
const pageIndex = data.pageIndex;
pdfManager.getPage(pageIndex).then(function(page) {
page.getContentStream().then(stream => {
let byte;
let string = "";
while ((byte = stream.getByte()) !== -1) {
string += String.fromCharCode(byte);
}
sink.enqueue(string, string.length);
sink.close();
});
});
});
handler.on("UpdateContents", function (data) {
return new Promise(resolve => {
const pageIndex = data.pageIndex;
pdfManager.getPage(pageIndex).then(function (page) {
page.setContents(data.value);
resolve();
});
});
});
handler.on("GetOperatorList", function (data, sink) { handler.on("GetOperatorList", function (data, sink) {
const pageIndex = data.pageIndex; const pageIndex = data.pageIndex;
pdfManager.getPage(pageIndex).then(function (page) { pdfManager.getPage(pageIndex).then(function (page) {
@ -792,7 +767,6 @@ class WorkerMessageHandler {
cacheKey: data.cacheKey, cacheKey: data.cacheKey,
annotationStorage: data.annotationStorage, annotationStorage: data.annotationStorage,
modifiedIds: data.modifiedIds, modifiedIds: data.modifiedIds,
contentOverride: data.contentOverride,
}) })
.then( .then(
function (operatorListInfo) { function (operatorListInfo) {

View File

@ -35,7 +35,6 @@ import {
AbortException, AbortException,
AnnotationMode, AnnotationMode,
assert, assert,
djb2Hash,
FeatureTest, FeatureTest,
getVerbosityLevel, getVerbosityLevel,
info, info,
@ -1661,37 +1660,6 @@ class PDFPageProxy {
return renderTask; return renderTask;
} }
updateContents(newContents) {
if (!newContents) {
throw new Error("Contents may not be null or undefined");
}
this._intentStates.clear();
return this._transport.updateContents(newContents, this._pageIndex);
}
getContents() {
const readableStream = this._transport.streamContents(this._pageIndex);
return new Promise(function (resolve, reject) {
function pump() {
reader.read().then(function ({ value, done }) {
if (done) {
resolve(textContent.text);
return;
}
textContent.text += value;
pump();
}, reject);
}
const reader = readableStream.getReader();
const textContent = {
text: "",
};
pump();
});
}
/** /**
* @param {GetOperatorListParameters} params - Page getOperatorList * @param {GetOperatorListParameters} params - Page getOperatorList
* parameters. * parameters.
@ -1703,7 +1671,6 @@ class PDFPageProxy {
annotationMode = AnnotationMode.ENABLE, annotationMode = AnnotationMode.ENABLE,
printAnnotationStorage = null, printAnnotationStorage = null,
isEditing = false, isEditing = false,
contentOverride = null,
} = {}) { } = {}) {
if (typeof PDFJSDev !== "undefined" && !PDFJSDev.test("GENERIC")) { if (typeof PDFJSDev !== "undefined" && !PDFJSDev.test("GENERIC")) {
throw new Error("Not implemented: getOperatorList"); throw new Error("Not implemented: getOperatorList");
@ -1721,8 +1688,7 @@ class PDFPageProxy {
annotationMode, annotationMode,
printAnnotationStorage, printAnnotationStorage,
isEditing, isEditing,
/* isOpList = */ true, /* isOpList = */ true
contentOverride
); );
let intentState = this._intentStates.get(intentArgs.cacheKey); let intentState = this._intentStates.get(intentArgs.cacheKey);
if (!intentState) { if (!intentState) {
@ -1944,7 +1910,6 @@ class PDFPageProxy {
cacheKey, cacheKey,
annotationStorageSerializable, annotationStorageSerializable,
modifiedIds, modifiedIds,
contentOverride,
}) { }) {
if (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) { if (typeof PDFJSDev === "undefined" || PDFJSDev.test("TESTING")) {
assert( assert(
@ -1962,7 +1927,6 @@ class PDFPageProxy {
cacheKey, cacheKey,
annotationStorage: map, annotationStorage: map,
modifiedIds, modifiedIds,
contentOverride,
}, },
transfer transfer
); );
@ -2564,8 +2528,7 @@ class WorkerTransport {
annotationMode = AnnotationMode.ENABLE, annotationMode = AnnotationMode.ENABLE,
printAnnotationStorage = null, printAnnotationStorage = null,
isEditing = false, isEditing = false,
isOpList = false, isOpList = false
contentOverride = null
) { ) {
let renderingIntent = RenderingIntentFlag.DISPLAY; // Default value. let renderingIntent = RenderingIntentFlag.DISPLAY; // Default value.
let annotationStorageSerializable = SerializableEmpty; let annotationStorageSerializable = SerializableEmpty;
@ -2623,16 +2586,11 @@ class WorkerTransport {
modifiedIdsHash, modifiedIdsHash,
]; ];
if (contentOverride) {
cacheKeyBuf.push(djb2Hash(contentOverride));
}
return { return {
renderingIntent, renderingIntent,
cacheKey: cacheKeyBuf.join("_"), cacheKey: cacheKeyBuf.join("_"),
annotationStorageSerializable, annotationStorageSerializable,
modifiedIds, modifiedIds,
contentOverride,
}; };
} }
@ -3016,23 +2974,6 @@ class WorkerTransport {
return this.messageHandler.sendWithPromise("GetXRefEntries", null); return this.messageHandler.sendWithPromise("GetXRefEntries", null);
} }
streamContents(pageIndex) {
return this.messageHandler.sendWithStream("StreamContents", {
pageIndex,
});
}
/**
* @returns {Promise<void>} A promise that is resolved once the contents
* are updated.
*/
updateContents(newContents, pageIndex) {
return this.messageHandler.sendWithPromise("UpdateContents", {
value: newContents,
pageIndex,
});
}
saveDocument() { saveDocument() {
if (this.annotationStorage.size <= 0) { if (this.annotationStorage.size <= 0) {
warn( warn(

View File

@ -578,16 +578,6 @@ function objectFromMap(map) {
return obj; return obj;
} }
// fast and easy hash
function djb2Hash(str) {
let hash = 5381;
for (let i = 0; i < str.length; i++) {
hash = (hash << 5) + hash + str.charCodeAt(i);
hash &= hash; // Convert to 32-bit integer
}
return hash >>> 0; // Convert to unsigned
}
// Checks the endianness of the platform. // Checks the endianness of the platform.
function isLittleEndian() { function isLittleEndian() {
const buffer8 = new Uint8Array(4); const buffer8 = new Uint8Array(4);
@ -1146,7 +1136,6 @@ export {
BASELINE_FACTOR, BASELINE_FACTOR,
bytesToString, bytesToString,
createValidAbsoluteUrl, createValidAbsoluteUrl,
djb2Hash,
DocumentActionEventType, DocumentActionEventType,
FeatureTest, FeatureTest,
FONT_IDENTITY_MATRIX, FONT_IDENTITY_MATRIX,