@yudaocode/univer-pdfs 1.6.216 → 1.6.218

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -313,7 +313,9 @@ function createDefaultPdfUnitData(partial) {
313
313
  nativeTextSpansByPage: partial?.editState?.nativeTextSpansByPage ? Tools.deepClone(partial.editState.nativeTextSpansByPage) : partial?.metadata?.nativeTextSpansByPage ? Tools.deepClone(partial.metadata.nativeTextSpansByPage) : void 0
314
314
  },
315
315
  ...partial?.layers !== void 0 ? { layers: Tools.deepClone(partial.layers) } : {},
316
+ ...partial?.bookmarks !== void 0 ? { bookmarks: Tools.deepClone(partial.bookmarks) } : partial?.metadata?.bookmarks !== void 0 ? { bookmarks: Tools.deepClone(partial.metadata.bookmarks) } : {},
316
317
  ...partial?.attachments !== void 0 ? { attachments: Tools.deepClone(partial.attachments) } : {},
318
+ ...partial?.security !== void 0 ? { security: Tools.deepClone(partial.security) } : partial?.metadata?.security !== void 0 ? { security: Tools.deepClone(partial.metadata.security) } : {},
317
319
  ...partial?.securityPermissions !== void 0 ? { securityPermissions: Tools.deepClone(partial.securityPermissions) } : {},
318
320
  ...partial?.signatureEnvelope !== void 0 ? { signatureEnvelope: Tools.deepClone(partial.signatureEnvelope) } : {},
319
321
  ...partial?.pdfACompliant !== void 0 ? { pdfACompliant: partial.pdfACompliant } : {},
@@ -546,9 +548,33 @@ var PdfUnitModel = class extends UnitModel {
546
548
  if (patch.layers !== void 0) {
547
549
  this._snapshot.layers = patch.layers ? Tools.deepClone(patch.layers) : void 0;
548
550
  }
551
+ if (patch.bookmarks !== void 0) {
552
+ this._snapshot.bookmarks = patch.bookmarks ? Tools.deepClone(patch.bookmarks) : void 0;
553
+ if (!this._snapshot.metadata) {
554
+ this._snapshot.metadata = {};
555
+ }
556
+ if (patch.bookmarks && patch.bookmarks.length > 0) {
557
+ this._snapshot.metadata.bookmarks = Tools.deepClone(patch.bookmarks);
558
+ } else if (patch.bookmarks === null || Array.isArray(patch.bookmarks) && patch.bookmarks.length === 0) {
559
+ if (patch.bookmarks === null) {
560
+ delete this._snapshot.metadata.bookmarks;
561
+ } else {
562
+ this._snapshot.metadata.bookmarks = [];
563
+ }
564
+ }
565
+ } else if (patch.metadata !== void 0) {
566
+ if (this._snapshot.metadata?.bookmarks !== void 0) {
567
+ this._snapshot.bookmarks = Tools.deepClone(this._snapshot.metadata.bookmarks);
568
+ } else if (patch.replaceMetadata) {
569
+ delete this._snapshot.bookmarks;
570
+ }
571
+ }
549
572
  if (patch.attachments !== void 0) {
550
573
  this._snapshot.attachments = patch.attachments ? Tools.deepClone(patch.attachments) : void 0;
551
574
  }
575
+ if (patch.security !== void 0) {
576
+ this._snapshot.security = patch.security ? Tools.deepClone(patch.security) : void 0;
577
+ }
552
578
  if (patch.securityPermissions !== void 0) {
553
579
  this._snapshot.securityPermissions = patch.securityPermissions ? Tools.deepClone(patch.securityPermissions) : void 0;
554
580
  }
@@ -3202,22 +3228,22 @@ import {
3202
3228
  endText,
3203
3229
  moveText,
3204
3230
  moveTo,
3205
- PDFArray as PDFArray2,
3231
+ PDFArray as PDFArray3,
3206
3232
  PDFBool,
3207
3233
  PDFCheckBox,
3208
- PDFDict as PDFDict2,
3209
- PDFDocument as PDFDocument2,
3234
+ PDFDict as PDFDict3,
3235
+ PDFDocument as PDFDocument3,
3210
3236
  PDFDropdown,
3211
- PDFHexString,
3212
- PDFName as PDFName2,
3213
- PDFNumber as PDFNumber2,
3237
+ PDFHexString as PDFHexString2,
3238
+ PDFName as PDFName3,
3239
+ PDFNumber as PDFNumber3,
3214
3240
  PDFOperator,
3215
3241
  PDFOptionList,
3216
3242
  PDFRadioGroup,
3217
- PDFRawStream as PDFRawStream2,
3218
- PDFRef as PDFRef2,
3219
- PDFStream as PDFStream2,
3220
- PDFString,
3243
+ PDFRawStream as PDFRawStream3,
3244
+ PDFRef as PDFRef3,
3245
+ PDFStream as PDFStream3,
3246
+ PDFString as PDFString2,
3221
3247
  PDFTextField,
3222
3248
  popGraphicsState as popGraphicsState2,
3223
3249
  pushGraphicsState as pushGraphicsState2,
@@ -5943,6 +5969,1019 @@ async function organizePdfBytes(pdfBytes, planOrOptions) {
5943
5969
  return await outDoc.save();
5944
5970
  }
5945
5971
 
5972
+ // src/exporter/pdf-security.ts
5973
+ import {
5974
+ PDFArray as PDFArray2,
5975
+ PDFDict as PDFDict2,
5976
+ PDFDocument as PDFDocument2,
5977
+ PDFHexString,
5978
+ PDFName as PDFName2,
5979
+ PDFNumber as PDFNumber2,
5980
+ PDFRawStream as PDFRawStream2,
5981
+ PDFRef as PDFRef2,
5982
+ PDFStream as PDFStream2,
5983
+ PDFString
5984
+ } from "pdf-lib";
5985
+ var PdfSecurityError = class extends Error {
5986
+ constructor(code, message) {
5987
+ super(message);
5988
+ this.name = "PdfSecurityError";
5989
+ this.code = code;
5990
+ }
5991
+ };
5992
+ var PDF_PASSWORD_PADDING = new Uint8Array([
5993
+ 40,
5994
+ 191,
5995
+ 78,
5996
+ 94,
5997
+ 78,
5998
+ 117,
5999
+ 138,
6000
+ 65,
6001
+ 100,
6002
+ 0,
6003
+ 78,
6004
+ 86,
6005
+ 255,
6006
+ 250,
6007
+ 1,
6008
+ 8,
6009
+ 46,
6010
+ 46,
6011
+ 0,
6012
+ 182,
6013
+ 208,
6014
+ 104,
6015
+ 62,
6016
+ 128,
6017
+ 47,
6018
+ 12,
6019
+ 169,
6020
+ 254,
6021
+ 100,
6022
+ 83,
6023
+ 105,
6024
+ 122
6025
+ ]);
6026
+ var DEFAULT_ALL_PERMISSIONS = Object.freeze({
6027
+ print: true,
6028
+ highResPrint: true,
6029
+ modify: true,
6030
+ copy: true,
6031
+ annotate: true,
6032
+ fillForms: true,
6033
+ assemble: true
6034
+ });
6035
+ var MD5_SHIFTS = [
6036
+ 7,
6037
+ 12,
6038
+ 17,
6039
+ 22,
6040
+ 7,
6041
+ 12,
6042
+ 17,
6043
+ 22,
6044
+ 7,
6045
+ 12,
6046
+ 17,
6047
+ 22,
6048
+ 7,
6049
+ 12,
6050
+ 17,
6051
+ 22,
6052
+ 5,
6053
+ 9,
6054
+ 14,
6055
+ 20,
6056
+ 5,
6057
+ 9,
6058
+ 14,
6059
+ 20,
6060
+ 5,
6061
+ 9,
6062
+ 14,
6063
+ 20,
6064
+ 5,
6065
+ 9,
6066
+ 14,
6067
+ 20,
6068
+ 4,
6069
+ 11,
6070
+ 16,
6071
+ 23,
6072
+ 4,
6073
+ 11,
6074
+ 16,
6075
+ 23,
6076
+ 4,
6077
+ 11,
6078
+ 16,
6079
+ 23,
6080
+ 4,
6081
+ 11,
6082
+ 16,
6083
+ 23,
6084
+ 6,
6085
+ 10,
6086
+ 15,
6087
+ 21,
6088
+ 6,
6089
+ 10,
6090
+ 15,
6091
+ 21,
6092
+ 6,
6093
+ 10,
6094
+ 15,
6095
+ 21,
6096
+ 6,
6097
+ 10,
6098
+ 15,
6099
+ 21
6100
+ ];
6101
+ var MD5_K = (() => {
6102
+ const table = new Uint32Array(64);
6103
+ for (let i = 0; i < 64; i++) {
6104
+ table[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296) >>> 0;
6105
+ }
6106
+ return table;
6107
+ })();
6108
+ function rotl32(x, n) {
6109
+ return (x << n | x >>> 32 - n) >>> 0;
6110
+ }
6111
+ function md5Bytes(data) {
6112
+ const msgLen = data.byteLength;
6113
+ const rem = (msgLen + 9) % 64;
6114
+ const padZeroes = rem === 0 ? 0 : 64 - rem;
6115
+ const totalLen = msgLen + 9 + padZeroes;
6116
+ const buf = new Uint8Array(totalLen);
6117
+ buf.set(data, 0);
6118
+ buf[msgLen] = 128;
6119
+ const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
6120
+ const bitLenLow = msgLen * 8 >>> 0;
6121
+ const bitLenHigh = Math.floor(msgLen * 8 / 4294967296) >>> 0;
6122
+ view.setUint32(totalLen - 8, bitLenLow, true);
6123
+ view.setUint32(totalLen - 4, bitLenHigh, true);
6124
+ let a0 = 1732584193;
6125
+ let b0 = 4023233417;
6126
+ let c0 = 2562383102;
6127
+ let d0 = 271733878;
6128
+ const M = new Uint32Array(16);
6129
+ for (let offset = 0; offset < totalLen; offset += 64) {
6130
+ for (let j = 0; j < 16; j++) {
6131
+ M[j] = view.getUint32(offset + j * 4, true);
6132
+ }
6133
+ let A = a0;
6134
+ let B = b0;
6135
+ let C = c0;
6136
+ let D = d0;
6137
+ for (let i = 0; i < 64; i++) {
6138
+ let F;
6139
+ let g;
6140
+ if (i < 16) {
6141
+ F = B & C | ~B & D;
6142
+ g = i;
6143
+ } else if (i < 32) {
6144
+ F = D & B | ~D & C;
6145
+ g = (5 * i + 1) % 16;
6146
+ } else if (i < 48) {
6147
+ F = B ^ C ^ D;
6148
+ g = (3 * i + 5) % 16;
6149
+ } else {
6150
+ F = C ^ (B | ~D);
6151
+ g = 7 * i % 16;
6152
+ }
6153
+ const sum = A + F + MD5_K[i] + M[g] >>> 0;
6154
+ A = D;
6155
+ D = C;
6156
+ C = B;
6157
+ B = B + rotl32(sum, MD5_SHIFTS[i]) >>> 0;
6158
+ }
6159
+ a0 = a0 + A >>> 0;
6160
+ b0 = b0 + B >>> 0;
6161
+ c0 = c0 + C >>> 0;
6162
+ d0 = d0 + D >>> 0;
6163
+ }
6164
+ const out = new Uint8Array(16);
6165
+ const outView = new DataView(out.buffer);
6166
+ outView.setUint32(0, a0, true);
6167
+ outView.setUint32(4, b0, true);
6168
+ outView.setUint32(8, c0, true);
6169
+ outView.setUint32(12, d0, true);
6170
+ return out;
6171
+ }
6172
+ function rc4Bytes(key, data) {
6173
+ const keyLen = key.byteLength;
6174
+ if (keyLen === 0) return data.slice();
6175
+ const S = new Uint8Array(256);
6176
+ for (let i2 = 0; i2 < 256; i2++) {
6177
+ S[i2] = i2;
6178
+ }
6179
+ let j = 0;
6180
+ for (let i2 = 0; i2 < 256; i2++) {
6181
+ j = j + S[i2] + key[i2 % keyLen] & 255;
6182
+ const tmp = S[i2];
6183
+ S[i2] = S[j];
6184
+ S[j] = tmp;
6185
+ }
6186
+ const out = new Uint8Array(data.byteLength);
6187
+ let i = 0;
6188
+ j = 0;
6189
+ for (let k = 0; k < data.byteLength; k++) {
6190
+ i = i + 1 & 255;
6191
+ j = j + S[i] & 255;
6192
+ const tmp = S[i];
6193
+ S[i] = S[j];
6194
+ S[j] = tmp;
6195
+ out[k] = data[k] ^ S[S[i] + S[j] & 255];
6196
+ }
6197
+ return out;
6198
+ }
6199
+ function bytesToHex(bytes) {
6200
+ let hex = "";
6201
+ for (let i = 0; i < bytes.byteLength; i++) {
6202
+ hex += bytes[i].toString(16).padStart(2, "0").toUpperCase();
6203
+ }
6204
+ return hex;
6205
+ }
6206
+ function hexToBytes(hexRaw) {
6207
+ const cleaned = hexRaw.replace(/\s+/g, "");
6208
+ const padded = cleaned.length % 2 === 1 ? `${cleaned}0` : cleaned;
6209
+ const out = new Uint8Array(padded.length / 2);
6210
+ for (let i = 0; i < out.byteLength; i++) {
6211
+ out[i] = parseInt(padded.slice(i * 2, i * 2 + 2), 16) || 0;
6212
+ }
6213
+ return out;
6214
+ }
6215
+ function encodePasswordToBytes(password) {
6216
+ if (!password) return new Uint8Array(0);
6217
+ let hasHighCodePoint = false;
6218
+ for (let i = 0; i < password.length; i++) {
6219
+ if (password.charCodeAt(i) > 255) {
6220
+ hasHighCodePoint = true;
6221
+ break;
6222
+ }
6223
+ }
6224
+ if (hasHighCodePoint) {
6225
+ return new TextEncoder().encode(password);
6226
+ }
6227
+ const out = new Uint8Array(password.length);
6228
+ for (let i = 0; i < password.length; i++) {
6229
+ out[i] = password.charCodeAt(i) & 255;
6230
+ }
6231
+ return out;
6232
+ }
6233
+ function padPdfPassword(password) {
6234
+ const raw = password instanceof Uint8Array ? password : encodePasswordToBytes(password);
6235
+ const out = new Uint8Array(32);
6236
+ const copyLen = Math.min(32, raw.byteLength);
6237
+ out.set(raw.subarray(0, copyLen), 0);
6238
+ if (copyLen < 32) {
6239
+ out.set(PDF_PASSWORD_PADDING.subarray(0, 32 - copyLen), copyLen);
6240
+ }
6241
+ return out;
6242
+ }
6243
+ function encodePdfPermissionFlags(permissions, revision = 3) {
6244
+ const allowPrint = permissions?.print !== false;
6245
+ const allowModify = permissions?.modify !== false;
6246
+ const allowCopy = permissions?.copy !== false;
6247
+ const allowAnnotate = permissions?.annotate !== false;
6248
+ const allowFillForms = permissions?.fillForms !== false;
6249
+ const allowAssemble = permissions?.assemble !== false;
6250
+ const allowHighResPrint = permissions?.highResPrint !== void 0 ? Boolean(permissions.highResPrint) : allowPrint;
6251
+ let mask = 4294963392 | 1 << 9;
6252
+ if (allowPrint) mask |= 1 << 2;
6253
+ if (allowModify) mask |= 1 << 3;
6254
+ if (allowCopy) mask |= 1 << 4;
6255
+ if (allowAnnotate) mask |= 1 << 5;
6256
+ if (revision >= 3) {
6257
+ if (allowFillForms) mask |= 1 << 8;
6258
+ if (allowAssemble) mask |= 1 << 10;
6259
+ if (allowHighResPrint && allowPrint) mask |= 1 << 11;
6260
+ } else {
6261
+ mask |= 1 << 8 | 1 << 10 | 1 << 11;
6262
+ }
6263
+ return mask | 0;
6264
+ }
6265
+ function decodePdfPermissionFlags(pMask, revision = 3) {
6266
+ const print = (pMask & 1 << 2) !== 0;
6267
+ const modify = (pMask & 1 << 3) !== 0;
6268
+ const copy = (pMask & 1 << 4) !== 0;
6269
+ const annotate = (pMask & 1 << 5) !== 0;
6270
+ const fillForms = revision >= 3 ? (pMask & 1 << 8) !== 0 : annotate;
6271
+ const assemble = revision >= 3 ? (pMask & 1 << 10) !== 0 : modify;
6272
+ const highResPrint = revision >= 3 ? print && (pMask & 1 << 11) !== 0 : print;
6273
+ return {
6274
+ print,
6275
+ highResPrint,
6276
+ modify,
6277
+ copy,
6278
+ annotate,
6279
+ fillForms,
6280
+ assemble
6281
+ };
6282
+ }
6283
+ function isPdfSecurityActive(security) {
6284
+ if (!security || security.enabled === false) return false;
6285
+ if (security.enabled === true) return true;
6286
+ if (security.userPassword && security.userPassword.length > 0) return true;
6287
+ if (security.ownerPassword && security.ownerPassword.length > 0) return true;
6288
+ if (security.permissions && Object.keys(security.permissions).length > 0) return true;
6289
+ return false;
6290
+ }
6291
+ function computeOwnerPasswordValue(userPassword, ownerPassword, revision, keyLengthBits) {
6292
+ const effectiveOwner = ownerPassword || userPassword || "";
6293
+ const ownerPad = padPdfPassword(effectiveOwner);
6294
+ let hash = md5Bytes(ownerPad);
6295
+ if (revision >= 3) {
6296
+ for (let i = 0; i < 50; i++) {
6297
+ hash = md5Bytes(hash);
6298
+ }
6299
+ }
6300
+ const keyByteLen = revision >= 3 ? Math.max(5, Math.min(16, keyLengthBits >>> 3)) : 5;
6301
+ const userPad = padPdfPassword(userPassword);
6302
+ let encrypted = rc4Bytes(hash.subarray(0, keyByteLen), userPad);
6303
+ if (revision >= 3) {
6304
+ const derivedKey = new Uint8Array(keyByteLen);
6305
+ for (let iter = 1; iter <= 19; iter++) {
6306
+ for (let k = 0; k < keyByteLen; k++) {
6307
+ derivedKey[k] = hash[k] ^ iter;
6308
+ }
6309
+ encrypted = rc4Bytes(derivedKey, encrypted);
6310
+ }
6311
+ }
6312
+ return encrypted;
6313
+ }
6314
+ function computeFileEncryptionKeyFromPadded(paddedUserPassword, oValue, pFlagsSigned, fileId, revision, keyLengthBits) {
6315
+ const buf = new Uint8Array(32 + oValue.byteLength + 4 + fileId.byteLength);
6316
+ let offset = 0;
6317
+ buf.set(paddedUserPassword.subarray(0, 32), offset);
6318
+ offset += 32;
6319
+ buf.set(oValue, offset);
6320
+ offset += oValue.byteLength;
6321
+ buf[offset++] = pFlagsSigned & 255;
6322
+ buf[offset++] = pFlagsSigned >>> 8 & 255;
6323
+ buf[offset++] = pFlagsSigned >>> 16 & 255;
6324
+ buf[offset++] = pFlagsSigned >>> 24 & 255;
6325
+ buf.set(fileId, offset);
6326
+ let hash = md5Bytes(buf);
6327
+ const keyByteLen = revision >= 3 ? Math.max(5, Math.min(16, keyLengthBits >>> 3)) : 5;
6328
+ if (revision >= 3) {
6329
+ for (let i = 0; i < 50; i++) {
6330
+ hash = md5Bytes(hash.subarray(0, keyByteLen));
6331
+ }
6332
+ }
6333
+ return hash.subarray(0, keyByteLen);
6334
+ }
6335
+ function computeUserPasswordValue(encryptionKey, fileId, revision) {
6336
+ if (revision === 2) {
6337
+ return rc4Bytes(encryptionKey, PDF_PASSWORD_PADDING);
6338
+ }
6339
+ const hashInput = new Uint8Array(32 + fileId.byteLength);
6340
+ hashInput.set(PDF_PASSWORD_PADDING, 0);
6341
+ hashInput.set(fileId, 32);
6342
+ let check = rc4Bytes(encryptionKey, md5Bytes(hashInput));
6343
+ const keyLen = encryptionKey.byteLength;
6344
+ const derivedKey = new Uint8Array(keyLen);
6345
+ for (let iter = 1; iter <= 19; iter++) {
6346
+ for (let k = 0; k < keyLen; k++) {
6347
+ derivedKey[k] = encryptionKey[k] ^ iter;
6348
+ }
6349
+ check = rc4Bytes(derivedKey, check);
6350
+ }
6351
+ const out = new Uint8Array(32);
6352
+ out.set(check.subarray(0, 16), 0);
6353
+ out.set(PDF_PASSWORD_PADDING.subarray(0, 16), 16);
6354
+ return out;
6355
+ }
6356
+ function authenticatePaddedUserPassword(paddedPassword, oValue, uValue, pFlagsSigned, fileId, revision, keyLengthBits) {
6357
+ const candidateKey = computeFileEncryptionKeyFromPadded(
6358
+ paddedPassword,
6359
+ oValue,
6360
+ pFlagsSigned,
6361
+ fileId,
6362
+ revision,
6363
+ keyLengthBits
6364
+ );
6365
+ const expectedU = computeUserPasswordValue(candidateKey, fileId, revision);
6366
+ const compareLen = revision >= 3 ? 16 : 32;
6367
+ if (uValue.byteLength < compareLen) return null;
6368
+ let diff = 0;
6369
+ for (let i = 0; i < compareLen; i++) {
6370
+ diff |= expectedU[i] ^ uValue[i];
6371
+ }
6372
+ return diff === 0 ? candidateKey : null;
6373
+ }
6374
+ function authenticateOwnerPassword(ownerPassword, oValue, uValue, pFlagsSigned, fileId, revision, keyLengthBits) {
6375
+ const ownerPad = padPdfPassword(ownerPassword);
6376
+ let hash = md5Bytes(ownerPad);
6377
+ if (revision >= 3) {
6378
+ for (let i = 0; i < 50; i++) {
6379
+ hash = md5Bytes(hash);
6380
+ }
6381
+ }
6382
+ const keyByteLen = revision >= 3 ? Math.max(5, Math.min(16, keyLengthBits >>> 3)) : 5;
6383
+ let recoveredUserPad;
6384
+ if (revision >= 3) {
6385
+ recoveredUserPad = oValue.slice(0, 32);
6386
+ const derivedKey = new Uint8Array(keyByteLen);
6387
+ for (let iter = 19; iter >= 0; iter--) {
6388
+ for (let k = 0; k < keyByteLen; k++) {
6389
+ derivedKey[k] = hash[k] ^ iter;
6390
+ }
6391
+ recoveredUserPad = rc4Bytes(derivedKey, recoveredUserPad);
6392
+ }
6393
+ } else {
6394
+ recoveredUserPad = rc4Bytes(hash.subarray(0, 5), oValue.subarray(0, 32));
6395
+ }
6396
+ return authenticatePaddedUserPassword(
6397
+ recoveredUserPad,
6398
+ oValue,
6399
+ uValue,
6400
+ pFlagsSigned,
6401
+ fileId,
6402
+ revision,
6403
+ keyLengthBits
6404
+ );
6405
+ }
6406
+ function buildObjectEncryptionKey(encryptionKey, objectNumber, generationNumber) {
6407
+ const n = encryptionKey.byteLength;
6408
+ const buf = new Uint8Array(n + 5);
6409
+ buf.set(encryptionKey, 0);
6410
+ buf[n] = objectNumber & 255;
6411
+ buf[n + 1] = objectNumber >>> 8 & 255;
6412
+ buf[n + 2] = objectNumber >>> 16 & 255;
6413
+ buf[n + 3] = generationNumber & 255;
6414
+ buf[n + 4] = generationNumber >>> 8 & 255;
6415
+ const digest = md5Bytes(buf);
6416
+ return digest.subarray(0, Math.min(n + 5, 16));
6417
+ }
6418
+ function decodePdfLiteralBodyBytes(body) {
6419
+ const bytes = [];
6420
+ for (let i = 0; i < body.length; i++) {
6421
+ const ch = body.charCodeAt(i) & 255;
6422
+ if (ch !== 92) {
6423
+ bytes.push(ch);
6424
+ continue;
6425
+ }
6426
+ if (i + 1 >= body.length) break;
6427
+ const next = body.charCodeAt(++i) & 255;
6428
+ if (next === 13) {
6429
+ if (i + 1 < body.length && (body.charCodeAt(i + 1) & 255) === 10) i++;
6430
+ } else if (next === 10) {
6431
+ } else if (next === 110) {
6432
+ bytes.push(10);
6433
+ } else if (next === 114) {
6434
+ bytes.push(13);
6435
+ } else if (next === 116) {
6436
+ bytes.push(9);
6437
+ } else if (next === 98) {
6438
+ bytes.push(8);
6439
+ } else if (next === 102) {
6440
+ bytes.push(12);
6441
+ } else if (next >= 48 && next <= 55) {
6442
+ let oct = String.fromCharCode(next);
6443
+ for (let k = 0; k < 2 && i + 1 < body.length; k++) {
6444
+ const peek = body.charCodeAt(i + 1) & 255;
6445
+ if (peek >= 48 && peek <= 55) {
6446
+ oct += String.fromCharCode(peek);
6447
+ i++;
6448
+ } else {
6449
+ break;
6450
+ }
6451
+ }
6452
+ bytes.push(parseInt(oct, 8) & 255);
6453
+ } else {
6454
+ bytes.push(next);
6455
+ }
6456
+ }
6457
+ return new Uint8Array(bytes);
6458
+ }
6459
+ function extractPdfStringRawBytes(strObj) {
6460
+ if (strObj instanceof PDFHexString) {
6461
+ return strObj.asBytes();
6462
+ }
6463
+ const serialized = strObj.asString();
6464
+ const inner = serialized.startsWith("(") && serialized.endsWith(")") ? serialized.slice(1, -1) : serialized;
6465
+ return decodePdfLiteralBodyBytes(inner);
6466
+ }
6467
+ function isSignatureDict(dict) {
6468
+ const typeVal = dict.get(PDFName2.of("Type"));
6469
+ if (typeVal instanceof PDFName2 && typeVal.asString() === "/Sig") return true;
6470
+ const ftVal = dict.get(PDFName2.of("FT"));
6471
+ if (ftVal instanceof PDFName2 && ftVal.asString() === "/Sig") return true;
6472
+ return false;
6473
+ }
6474
+ function transformPdfObjectStringsWithRc4(obj, objKey) {
6475
+ if (obj instanceof PDFHexString || obj instanceof PDFString) {
6476
+ const raw = extractPdfStringRawBytes(obj);
6477
+ const transformed = rc4Bytes(objKey, raw);
6478
+ return PDFHexString.of(bytesToHex(transformed));
6479
+ }
6480
+ if (obj instanceof PDFArray2) {
6481
+ for (let i = 0; i < obj.size(); i++) {
6482
+ const item = obj.get(i);
6483
+ const next = transformPdfObjectStringsWithRc4(item, objKey);
6484
+ if (next !== item) {
6485
+ obj.set(i, next);
6486
+ }
6487
+ }
6488
+ return obj;
6489
+ }
6490
+ if (obj instanceof PDFDict2) {
6491
+ const isSig = isSignatureDict(obj);
6492
+ for (const [key, val] of obj.entries()) {
6493
+ if (isSig && key.asString() === "/Contents") {
6494
+ continue;
6495
+ }
6496
+ const next = transformPdfObjectStringsWithRc4(val, objKey);
6497
+ if (next !== val) {
6498
+ obj.set(key, next);
6499
+ }
6500
+ }
6501
+ return obj;
6502
+ }
6503
+ return obj;
6504
+ }
6505
+ function extractOrCreateDocumentFileId(pdfDoc) {
6506
+ const existingId = pdfDoc.context.trailerInfo.ID;
6507
+ if (existingId) {
6508
+ const idArr = existingId instanceof PDFArray2 ? existingId : pdfDoc.context.lookupMaybe(existingId, PDFArray2);
6509
+ if (idArr && idArr.size() > 0) {
6510
+ const first = idArr.get(0);
6511
+ if (first instanceof PDFHexString || first instanceof PDFString) {
6512
+ const bytes = extractPdfStringRawBytes(first);
6513
+ if (bytes.byteLength > 0) {
6514
+ const hex = bytesToHex(bytes);
6515
+ pdfDoc.context.trailerInfo.ID = pdfDoc.context.obj([
6516
+ PDFHexString.of(hex),
6517
+ PDFHexString.of(hex)
6518
+ ]);
6519
+ return bytes;
6520
+ }
6521
+ }
6522
+ }
6523
+ }
6524
+ const seedBytes = new Uint8Array(32);
6525
+ if (typeof globalThis.crypto !== "undefined" && typeof globalThis.crypto.getRandomValues === "function") {
6526
+ globalThis.crypto.getRandomValues(seedBytes);
6527
+ } else {
6528
+ const fallbackText = `univer-pdf-${Date.now()}-${Math.random()}-${pdfDoc.getPageCount()}`;
6529
+ const enc = new TextEncoder().encode(fallbackText);
6530
+ seedBytes.set(enc.subarray(0, Math.min(32, enc.byteLength)));
6531
+ }
6532
+ const fileId = md5Bytes(seedBytes);
6533
+ const idHex = bytesToHex(fileId);
6534
+ pdfDoc.context.trailerInfo.ID = pdfDoc.context.obj([
6535
+ PDFHexString.of(idHex),
6536
+ PDFHexString.of(idHex)
6537
+ ]);
6538
+ return fileId;
6539
+ }
6540
+ async function applyPdfSecurityToDocument(pdfDoc, security) {
6541
+ if (security.enabled === false) return;
6542
+ await pdfDoc.flush();
6543
+ const keyLength = security.keyLength === 40 ? 40 : 128;
6544
+ const version = keyLength === 40 ? 1 : 2;
6545
+ const revision = keyLength === 40 ? 2 : 3;
6546
+ const userPassword = security.userPassword ?? "";
6547
+ const ownerPassword = security.ownerPassword && security.ownerPassword.length > 0 ? security.ownerPassword : userPassword.length > 0 ? userPassword : "univer-pdf-owner-guard";
6548
+ const fileId = extractOrCreateDocumentFileId(pdfDoc);
6549
+ const pSigned = encodePdfPermissionFlags(security.permissions, revision);
6550
+ const oBytes = computeOwnerPasswordValue(userPassword, ownerPassword, revision, keyLength);
6551
+ const encryptionKey = computeFileEncryptionKeyFromPadded(
6552
+ padPdfPassword(userPassword),
6553
+ oBytes,
6554
+ pSigned,
6555
+ fileId,
6556
+ revision,
6557
+ keyLength
6558
+ );
6559
+ const uBytes = computeUserPasswordValue(encryptionKey, fileId, revision);
6560
+ const idRef = pdfDoc.context.trailerInfo.ID instanceof PDFRef2 ? pdfDoc.context.trailerInfo.ID : null;
6561
+ for (const [ref, obj] of pdfDoc.context.enumerateIndirectObjects()) {
6562
+ if (idRef && ref.objectNumber === idRef.objectNumber && ref.generationNumber === idRef.generationNumber) {
6563
+ continue;
6564
+ }
6565
+ const objKey = buildObjectEncryptionKey(encryptionKey, ref.objectNumber, ref.generationNumber);
6566
+ if (obj instanceof PDFRawStream2) {
6567
+ transformPdfObjectStringsWithRc4(obj.dict, objKey);
6568
+ const encryptedStream = rc4Bytes(objKey, obj.contents);
6569
+ obj.dict.set(PDFName2.of("Length"), PDFNumber2.of(encryptedStream.byteLength));
6570
+ pdfDoc.context.assign(ref, PDFRawStream2.of(obj.dict, encryptedStream));
6571
+ } else if (obj instanceof PDFStream2) {
6572
+ transformPdfObjectStringsWithRc4(obj.dict, objKey);
6573
+ const encodedContents = obj.getContents();
6574
+ const encryptedStream = rc4Bytes(objKey, encodedContents);
6575
+ obj.dict.set(PDFName2.of("Length"), PDFNumber2.of(encryptedStream.byteLength));
6576
+ pdfDoc.context.assign(ref, PDFRawStream2.of(obj.dict, encryptedStream));
6577
+ } else {
6578
+ const next = transformPdfObjectStringsWithRc4(obj, objKey);
6579
+ if (next !== obj) {
6580
+ pdfDoc.context.assign(ref, next);
6581
+ }
6582
+ }
6583
+ }
6584
+ const encryptDict = pdfDoc.context.obj({
6585
+ Filter: PDFName2.of("Standard"),
6586
+ V: PDFNumber2.of(version),
6587
+ R: PDFNumber2.of(revision),
6588
+ Length: PDFNumber2.of(keyLength),
6589
+ P: PDFNumber2.of(pSigned),
6590
+ O: PDFHexString.of(bytesToHex(oBytes)),
6591
+ U: PDFHexString.of(bytesToHex(uBytes))
6592
+ });
6593
+ const encryptRef = pdfDoc.context.register(encryptDict);
6594
+ pdfDoc.context.trailerInfo.Encrypt = encryptRef;
6595
+ }
6596
+ async function encryptPdfBytes(pdfBytes, security) {
6597
+ if (!security || security.enabled === false) {
6598
+ return pdfBytes.slice();
6599
+ }
6600
+ const cleanBytes = inspectPdfEncryption(pdfBytes).encrypted ? await decryptPdfBytes(pdfBytes, security.ownerPassword || security.userPassword || "") : pdfBytes;
6601
+ const pdfDoc = await PDFDocument2.load(cleanBytes, { updateMetadata: false });
6602
+ await applyPdfSecurityToDocument(pdfDoc, security);
6603
+ return await pdfDoc.save({ useObjectStreams: false, updateFieldAppearances: false });
6604
+ }
6605
+ function bytesToLatin1(bytes) {
6606
+ let out = "";
6607
+ const chunk = 32768;
6608
+ for (let i = 0; i < bytes.byteLength; i += chunk) {
6609
+ out += String.fromCharCode(...bytes.subarray(i, i + chunk));
6610
+ }
6611
+ return out;
6612
+ }
6613
+ function extractBalancedPdfDict(text, startIdx) {
6614
+ const openIdx = text.indexOf("<<", startIdx);
6615
+ if (openIdx < 0) return null;
6616
+ let depth = 0;
6617
+ let inLiteral = false;
6618
+ let literalDepth = 0;
6619
+ for (let i = openIdx; i < text.length; i++) {
6620
+ const ch = text.charCodeAt(i);
6621
+ if (inLiteral) {
6622
+ if (ch === 92) {
6623
+ i++;
6624
+ continue;
6625
+ }
6626
+ if (ch === 40) literalDepth++;
6627
+ else if (ch === 41) {
6628
+ literalDepth--;
6629
+ if (literalDepth <= 0) {
6630
+ inLiteral = false;
6631
+ }
6632
+ }
6633
+ continue;
6634
+ }
6635
+ if (ch === 40) {
6636
+ inLiteral = true;
6637
+ literalDepth = 1;
6638
+ continue;
6639
+ }
6640
+ if (ch === 37) {
6641
+ while (i < text.length && text.charCodeAt(i) !== 10 && text.charCodeAt(i) !== 13) {
6642
+ i++;
6643
+ }
6644
+ continue;
6645
+ }
6646
+ if (ch === 60 && text.charCodeAt(i + 1) === 60) {
6647
+ depth++;
6648
+ i++;
6649
+ continue;
6650
+ }
6651
+ if (ch === 62 && text.charCodeAt(i + 1) === 62) {
6652
+ depth--;
6653
+ i++;
6654
+ if (depth === 0) {
6655
+ return text.slice(openIdx, i + 1);
6656
+ }
6657
+ }
6658
+ }
6659
+ return null;
6660
+ }
6661
+ function parsePdfStringTokenAfterKey(dictText, keyName) {
6662
+ const re = new RegExp(`\\/${keyName}(?![A-Za-z0-9_.+-])\\s*`);
6663
+ const match = re.exec(dictText);
6664
+ if (!match) return null;
6665
+ let pos = match.index + match[0].length;
6666
+ while (pos < dictText.length && /\s/.test(dictText[pos])) pos++;
6667
+ if (pos >= dictText.length) return null;
6668
+ if (dictText[pos] === "<" && dictText[pos + 1] !== "<") {
6669
+ const close = dictText.indexOf(">", pos + 1);
6670
+ if (close < 0) return null;
6671
+ return hexToBytes(dictText.slice(pos + 1, close));
6672
+ }
6673
+ if (dictText[pos] === "(") {
6674
+ let depth = 1;
6675
+ let i = pos + 1;
6676
+ while (i < dictText.length && depth > 0) {
6677
+ const ch = dictText.charCodeAt(i);
6678
+ if (ch === 92) {
6679
+ i += 2;
6680
+ continue;
6681
+ }
6682
+ if (ch === 40) depth++;
6683
+ else if (ch === 41) depth--;
6684
+ i++;
6685
+ }
6686
+ if (depth === 0) {
6687
+ return decodePdfLiteralBodyBytes(dictText.slice(pos + 1, i - 1));
6688
+ }
6689
+ }
6690
+ return null;
6691
+ }
6692
+ function parseFirstPdfArrayStringBytes(dictText, keyName) {
6693
+ const re = new RegExp(`\\/${keyName}(?![A-Za-z0-9_.+-])\\s*\\[`);
6694
+ const match = re.exec(dictText);
6695
+ if (!match) return null;
6696
+ let pos = match.index + match[0].length;
6697
+ while (pos < dictText.length && /\s/.test(dictText[pos])) pos++;
6698
+ if (pos >= dictText.length) return null;
6699
+ if (dictText[pos] === "<" && dictText[pos + 1] !== "<") {
6700
+ const close = dictText.indexOf(">", pos + 1);
6701
+ if (close >= 0) return hexToBytes(dictText.slice(pos + 1, close));
6702
+ } else if (dictText[pos] === "(") {
6703
+ let depth = 1;
6704
+ let i = pos + 1;
6705
+ while (i < dictText.length && depth > 0) {
6706
+ const ch = dictText.charCodeAt(i);
6707
+ if (ch === 92) {
6708
+ i += 2;
6709
+ continue;
6710
+ }
6711
+ if (ch === 40) depth++;
6712
+ else if (ch === 41) depth--;
6713
+ i++;
6714
+ }
6715
+ if (depth === 0) {
6716
+ return decodePdfLiteralBodyBytes(dictText.slice(pos + 1, i - 1));
6717
+ }
6718
+ }
6719
+ return null;
6720
+ }
6721
+ function parseRawEncryptFromPdfBytes(pdfBytes) {
6722
+ if (!pdfBytes || pdfBytes.byteLength < 16) return null;
6723
+ const rawText = bytesToLatin1(pdfBytes);
6724
+ let containerDict = null;
6725
+ let searchEnd = rawText.length;
6726
+ while (searchEnd > 0) {
6727
+ const trailerIdx = rawText.lastIndexOf("trailer", searchEnd - 1);
6728
+ if (trailerIdx < 0) break;
6729
+ const prevCh = trailerIdx > 0 ? rawText[trailerIdx - 1] : "\n";
6730
+ const afterCh = rawText[trailerIdx + 7] ?? " ";
6731
+ if (/[\s\r\n>]/.test(prevCh) && /[\s\r\n<]/.test(afterCh)) {
6732
+ const candidate = extractBalancedPdfDict(rawText, trailerIdx + 7);
6733
+ if (candidate && /\/Encrypt\b/.test(candidate)) {
6734
+ containerDict = candidate;
6735
+ break;
6736
+ }
6737
+ if (candidate && !containerDict) {
6738
+ containerDict = candidate;
6739
+ }
6740
+ }
6741
+ searchEnd = trailerIdx;
6742
+ }
6743
+ if (!containerDict || !/\/Encrypt\b/.test(containerDict)) {
6744
+ const xrefMatch = /<<[\s\S]{0,2048}?\/Type\s*\/XRef[\s\S]{0,2048}?>>/.exec(rawText);
6745
+ if (xrefMatch && /\/Encrypt\b/.test(xrefMatch[0])) {
6746
+ containerDict = xrefMatch[0];
6747
+ }
6748
+ }
6749
+ if (!containerDict || !/\/Encrypt\b/.test(containerDict)) {
6750
+ return null;
6751
+ }
6752
+ let encryptDictText = null;
6753
+ const refMatch = /\/Encrypt\s+(\d+)\s+(\d+)\s+R\b/.exec(containerDict);
6754
+ if (refMatch) {
6755
+ const objNum = refMatch[1];
6756
+ const genNum = refMatch[2];
6757
+ const objRe = new RegExp(`(?:^|[\\r\\n\\s])${objNum}\\s+${genNum}\\s+obj\\b`, "g");
6758
+ let lastObjMatch = null;
6759
+ let m;
6760
+ while ((m = objRe.exec(rawText)) !== null) {
6761
+ lastObjMatch = m;
6762
+ }
6763
+ if (lastObjMatch) {
6764
+ encryptDictText = extractBalancedPdfDict(rawText, lastObjMatch.index + lastObjMatch[0].length);
6765
+ }
6766
+ } else if (/\/Encrypt\s*<</.test(containerDict)) {
6767
+ const inlineIdx = containerDict.search(/\/Encrypt\s*<</);
6768
+ encryptDictText = extractBalancedPdfDict(containerDict, inlineIdx);
6769
+ }
6770
+ if (!encryptDictText) return null;
6771
+ const filterMatch = /\/Filter\s*\/([A-Za-z0-9_.+-]+)/.exec(encryptDictText);
6772
+ const vMatch = /\/V\s+(-?\d+)/.exec(encryptDictText);
6773
+ const rMatch = /\/R\s+(-?\d+)/.exec(encryptDictText);
6774
+ const lenMatch = /\/Length\s+(\d+)/.exec(encryptDictText);
6775
+ const pMatch = /\/P\s+(-?\d+)/.exec(encryptDictText);
6776
+ const filter = filterMatch ? filterMatch[1] : "Standard";
6777
+ const version = vMatch ? parseInt(vMatch[1], 10) : 1;
6778
+ const revision = rMatch ? parseInt(rMatch[1], 10) : version >= 2 ? 3 : 2;
6779
+ const keyLength = lenMatch ? parseInt(lenMatch[1], 10) : version >= 2 ? 128 : 40;
6780
+ const pSigned = pMatch ? parseInt(pMatch[1], 10) | 0 : -4;
6781
+ const oBytes = parsePdfStringTokenAfterKey(encryptDictText, "O") ?? new Uint8Array(0);
6782
+ const uBytes = parsePdfStringTokenAfterKey(encryptDictText, "U") ?? new Uint8Array(0);
6783
+ let fileId = parseFirstPdfArrayStringBytes(containerDict, "ID");
6784
+ if (!fileId) {
6785
+ const idRefMatch = /\/ID\s+(\d+)\s+(\d+)\s+R\b/.exec(containerDict);
6786
+ if (idRefMatch) {
6787
+ const idObjRe = new RegExp(`(?:^|[\\r\\n\\s])${idRefMatch[1]}\\s+${idRefMatch[2]}\\s+obj\\b([\\s\\S]{0,512}?)endobj`);
6788
+ const idObjM = idObjRe.exec(rawText);
6789
+ if (idObjM) {
6790
+ fileId = parseFirstPdfArrayStringBytes(`/ID ${idObjM[1]}`, "ID");
6791
+ }
6792
+ }
6793
+ }
6794
+ return {
6795
+ filter,
6796
+ version,
6797
+ revision,
6798
+ keyLength,
6799
+ pSigned,
6800
+ oBytes,
6801
+ uBytes,
6802
+ fileId: fileId ?? new Uint8Array(0)
6803
+ };
6804
+ }
6805
+ function extractEncryptMetadataFromDoc(doc) {
6806
+ const encEntry = doc.context.trailerInfo.Encrypt;
6807
+ if (!encEntry) return null;
6808
+ const encDict = encEntry instanceof PDFDict2 ? encEntry : doc.context.lookupMaybe(encEntry, PDFDict2);
6809
+ if (!encDict) return null;
6810
+ const filterObj = encDict.get(PDFName2.of("Filter"));
6811
+ const filter = filterObj instanceof PDFName2 ? filterObj.decodeText() : "Standard";
6812
+ const vObj = encDict.get(PDFName2.of("V"));
6813
+ const version = vObj instanceof PDFNumber2 ? vObj.asNumber() : 1;
6814
+ const rObj = encDict.get(PDFName2.of("R"));
6815
+ const revision = rObj instanceof PDFNumber2 ? rObj.asNumber() : version >= 2 ? 3 : 2;
6816
+ const lenObj = encDict.get(PDFName2.of("Length"));
6817
+ const keyLength = lenObj instanceof PDFNumber2 ? lenObj.asNumber() : version >= 2 ? 128 : 40;
6818
+ const pObj = encDict.get(PDFName2.of("P"));
6819
+ const pSigned = pObj instanceof PDFNumber2 ? pObj.asNumber() | 0 : -4;
6820
+ const oObj = encDict.get(PDFName2.of("O"));
6821
+ const oBytes = oObj instanceof PDFHexString || oObj instanceof PDFString ? extractPdfStringRawBytes(oObj) : new Uint8Array(0);
6822
+ const uObj = encDict.get(PDFName2.of("U"));
6823
+ const uBytes = uObj instanceof PDFHexString || uObj instanceof PDFString ? extractPdfStringRawBytes(uObj) : new Uint8Array(0);
6824
+ let fileId = new Uint8Array(0);
6825
+ const idEntry = doc.context.trailerInfo.ID;
6826
+ const idArr = idEntry instanceof PDFArray2 ? idEntry : doc.context.lookupMaybe(idEntry, PDFArray2);
6827
+ if (idArr && idArr.size() > 0) {
6828
+ const first = idArr.get(0);
6829
+ if (first instanceof PDFHexString || first instanceof PDFString) {
6830
+ fileId = extractPdfStringRawBytes(first);
6831
+ }
6832
+ }
6833
+ return {
6834
+ filter,
6835
+ version,
6836
+ revision,
6837
+ keyLength,
6838
+ pSigned,
6839
+ oBytes,
6840
+ uBytes,
6841
+ fileId
6842
+ };
6843
+ }
6844
+ function inspectPdfEncryption(pdfBytes) {
6845
+ const meta = parseRawEncryptFromPdfBytes(pdfBytes);
6846
+ if (!meta) {
6847
+ return {
6848
+ encrypted: false,
6849
+ requiresOpenPassword: false,
6850
+ permissions: { ...DEFAULT_ALL_PERMISSIONS }
6851
+ };
6852
+ }
6853
+ let requiresOpenPassword = true;
6854
+ if (meta.filter === "Standard" && (meta.version === 1 || meta.version === 2) && (meta.revision === 2 || meta.revision === 3) && meta.oBytes.byteLength >= 32 && meta.uBytes.byteLength >= 16) {
6855
+ const emptyKey = authenticatePaddedUserPassword(
6856
+ padPdfPassword(""),
6857
+ meta.oBytes,
6858
+ meta.uBytes,
6859
+ meta.pSigned,
6860
+ meta.fileId,
6861
+ meta.revision,
6862
+ meta.keyLength
6863
+ );
6864
+ requiresOpenPassword = emptyKey === null;
6865
+ }
6866
+ return {
6867
+ encrypted: true,
6868
+ requiresOpenPassword,
6869
+ filter: meta.filter,
6870
+ version: meta.version,
6871
+ revision: meta.revision,
6872
+ keyLength: meta.keyLength,
6873
+ permissionFlagsRaw: meta.pSigned,
6874
+ permissions: decodePdfPermissionFlags(meta.pSigned, meta.revision)
6875
+ };
6876
+ }
6877
+ async function decryptPdfBytes(pdfBytes, password) {
6878
+ let meta = parseRawEncryptFromPdfBytes(pdfBytes);
6879
+ const doc = await PDFDocument2.load(pdfBytes, {
6880
+ ignoreEncryption: true,
6881
+ updateMetadata: false
6882
+ });
6883
+ if (!meta && doc.isEncrypted) {
6884
+ meta = extractEncryptMetadataFromDoc(doc);
6885
+ }
6886
+ if (!meta) {
6887
+ return pdfBytes.slice();
6888
+ }
6889
+ if (meta.filter !== "Standard" || meta.version !== 1 && meta.version !== 2 || meta.revision !== 2 && meta.revision !== 3) {
6890
+ throw new PdfSecurityError(
6891
+ "PDF_UNSUPPORTED_ENCRYPTION",
6892
+ `Unsupported PDF encryption handler (Filter=/${meta.filter}, V=${meta.version}, R=${meta.revision}).`
6893
+ );
6894
+ }
6895
+ const rev = meta.revision;
6896
+ const emptyOpenKey = authenticatePaddedUserPassword(
6897
+ padPdfPassword(""),
6898
+ meta.oBytes,
6899
+ meta.uBytes,
6900
+ meta.pSigned,
6901
+ meta.fileId,
6902
+ rev,
6903
+ meta.keyLength
6904
+ );
6905
+ const requiresOpenPassword = emptyOpenKey === null;
6906
+ const candidatePw = password ?? "";
6907
+ if (requiresOpenPassword && candidatePw.length === 0) {
6908
+ throw new PdfSecurityError(
6909
+ "PDF_PASSWORD_REQUIRED",
6910
+ "Encrypted PDF document requires an open password."
6911
+ );
6912
+ }
6913
+ let encryptionKey = null;
6914
+ if (candidatePw.length === 0 && emptyOpenKey) {
6915
+ encryptionKey = emptyOpenKey;
6916
+ } else {
6917
+ encryptionKey = authenticatePaddedUserPassword(
6918
+ padPdfPassword(candidatePw),
6919
+ meta.oBytes,
6920
+ meta.uBytes,
6921
+ meta.pSigned,
6922
+ meta.fileId,
6923
+ rev,
6924
+ meta.keyLength
6925
+ );
6926
+ if (!encryptionKey) {
6927
+ encryptionKey = authenticateOwnerPassword(
6928
+ candidatePw,
6929
+ meta.oBytes,
6930
+ meta.uBytes,
6931
+ meta.pSigned,
6932
+ meta.fileId,
6933
+ rev,
6934
+ meta.keyLength
6935
+ );
6936
+ }
6937
+ }
6938
+ if (!encryptionKey) {
6939
+ throw new PdfSecurityError(
6940
+ "PDF_INVALID_PASSWORD",
6941
+ "Incorrect password for encrypted PDF document."
6942
+ );
6943
+ }
6944
+ const encryptRef = doc.context.trailerInfo.Encrypt instanceof PDFRef2 ? doc.context.trailerInfo.Encrypt : null;
6945
+ const idRef = doc.context.trailerInfo.ID instanceof PDFRef2 ? doc.context.trailerInfo.ID : null;
6946
+ for (const [ref, obj] of doc.context.enumerateIndirectObjects()) {
6947
+ if (encryptRef && ref.objectNumber === encryptRef.objectNumber && ref.generationNumber === encryptRef.generationNumber) {
6948
+ continue;
6949
+ }
6950
+ if (idRef && ref.objectNumber === idRef.objectNumber && ref.generationNumber === idRef.generationNumber) {
6951
+ continue;
6952
+ }
6953
+ const objKey = buildObjectEncryptionKey(encryptionKey, ref.objectNumber, ref.generationNumber);
6954
+ if (obj instanceof PDFRawStream2) {
6955
+ transformPdfObjectStringsWithRc4(obj.dict, objKey);
6956
+ const decryptedStream = rc4Bytes(objKey, obj.contents);
6957
+ obj.dict.set(PDFName2.of("Length"), PDFNumber2.of(decryptedStream.byteLength));
6958
+ doc.context.assign(ref, PDFRawStream2.of(obj.dict, decryptedStream));
6959
+ } else if (obj instanceof PDFStream2) {
6960
+ transformPdfObjectStringsWithRc4(obj.dict, objKey);
6961
+ const decryptedStream = rc4Bytes(objKey, obj.getContents());
6962
+ obj.dict.set(PDFName2.of("Length"), PDFNumber2.of(decryptedStream.byteLength));
6963
+ doc.context.assign(ref, PDFRawStream2.of(obj.dict, decryptedStream));
6964
+ } else {
6965
+ const next = transformPdfObjectStringsWithRc4(obj, objKey);
6966
+ if (next !== obj) {
6967
+ doc.context.assign(ref, next);
6968
+ }
6969
+ }
6970
+ }
6971
+ delete doc.context.trailerInfo.Encrypt;
6972
+ if (encryptRef) {
6973
+ doc.context.delete(encryptRef);
6974
+ }
6975
+ return await doc.save({ useObjectStreams: false, updateFieldAppearances: false });
6976
+ }
6977
+ async function verifyAndDecryptPdfBytes(pdfBytes, password) {
6978
+ const inspection = inspectPdfEncryption(pdfBytes);
6979
+ if (!inspection.encrypted) {
6980
+ return pdfBytes;
6981
+ }
6982
+ return decryptPdfBytes(pdfBytes, password);
6983
+ }
6984
+
5946
6985
  // src/exporter/pdf-svg-vector.ts
5947
6986
  import {
5948
6987
  clip,
@@ -7068,8 +8107,8 @@ function registerSubsetType0FontInDoc(pdfDoc, fontBytes, usedCodePoints, fontTag
7068
8107
  Subtype: "CIDFontType2",
7069
8108
  BaseFont: fontTag,
7070
8109
  CIDSystemInfo: {
7071
- Registry: PDFString.of("Adobe"),
7072
- Ordering: PDFString.of("Identity"),
8110
+ Registry: PDFString2.of("Adobe"),
8111
+ Ordering: PDFString2.of("Identity"),
7073
8112
  Supplement: 0
7074
8113
  },
7075
8114
  FontDescriptor: fontDescriptorRef,
@@ -7465,8 +8504,8 @@ function initVectorCjkEmbedState(pdfDoc, snapshot, effectiveData, options, preRe
7465
8504
  Subtype: "CIDFontType2",
7466
8505
  BaseFont: "STSong-Light",
7467
8506
  CIDSystemInfo: {
7468
- Registry: PDFString.of("Adobe"),
7469
- Ordering: PDFString.of("GB1"),
8507
+ Registry: PDFString2.of("Adobe"),
8508
+ Ordering: PDFString2.of("GB1"),
7470
8509
  Supplement: 4
7471
8510
  },
7472
8511
  FontDescriptor: fontDescriptorRef,
@@ -7661,7 +8700,7 @@ function drawVectorCjkTextBox(page, pageHeight, text, left, top, width, height,
7661
8700
  return setFillingCmykColor(cm.c, cm.m, cm.y, cm.k);
7662
8701
  })() : setFillingRgbColor(color.r, color.g, color.b);
7663
8702
  const syntheticBoldOps = wantBold && !usedDedicatedBold ? [
7664
- PDFOperator.of("Tr", [PDFNumber2.of(2)]),
8703
+ PDFOperator.of("Tr", [PDFNumber3.of(2)]),
7665
8704
  setLineWidth(Math.max(0.25, fontSize * 0.032)),
7666
8705
  colorType === "cmyk" ? (() => {
7667
8706
  const cm = rgbToCmyk(color.r, color.g, color.b);
@@ -7705,12 +8744,12 @@ function drawVectorCjkTextBox(page, pageHeight, text, left, top, width, height,
7705
8744
  const hexStr = encodeVectorCjkLineHex(line, state, activeSubset);
7706
8745
  const totalTc = charSpacing + extraJustifyTc;
7707
8746
  const posOp = style?.italic ? PDFOperator.of("Tm", [
7708
- PDFNumber2.of(1),
7709
- PDFNumber2.of(0),
7710
- PDFNumber2.of(0.2126),
7711
- PDFNumber2.of(1),
7712
- PDFNumber2.of(drawX),
7713
- PDFNumber2.of(drawY)
8747
+ PDFNumber3.of(1),
8748
+ PDFNumber3.of(0),
8749
+ PDFNumber3.of(0.2126),
8750
+ PDFNumber3.of(1),
8751
+ PDFNumber3.of(drawX),
8752
+ PDFNumber3.of(drawY)
7714
8753
  ]) : moveText(drawX, drawY);
7715
8754
  page.pushOperators(
7716
8755
  pushGraphicsState2(),
@@ -7720,7 +8759,7 @@ function drawVectorCjkTextBox(page, pageHeight, text, left, top, width, height,
7720
8759
  setFontAndSize(fontKey, fontSize),
7721
8760
  ...totalTc !== 0 ? [setCharacterSpacing(totalTc)] : [],
7722
8761
  posOp,
7723
- showText(PDFHexString.of(hexStr)),
8762
+ showText(PDFHexString2.of(hexStr)),
7724
8763
  endText(),
7725
8764
  popGraphicsState2()
7726
8765
  );
@@ -8301,7 +9340,7 @@ async function drawTextBox(pdfDoc, page, pageHeight, text, left, top, width, hei
8301
9340
  const ops = [pushGraphicsState2()];
8302
9341
  if (totalTc !== 0) ops.push(setCharacterSpacing(totalTc));
8303
9342
  if (extraWordSpacing !== 0) {
8304
- ops.push(PDFOperator.of("Tw", [PDFNumber2.of(extraWordSpacing)]));
9343
+ ops.push(PDFOperator.of("Tw", [PDFNumber3.of(extraWordSpacing)]));
8305
9344
  }
8306
9345
  page.pushOperators(...ops);
8307
9346
  page.drawText(lineText, {
@@ -9143,7 +10182,7 @@ async function drawRichOrColumnTextBox(pdfDoc, page, pageHeight, spans, left, to
9143
10182
  return setFillingCmykColor(cm.c, cm.m, cm.y, cm.k);
9144
10183
  })() : setFillingRgbColor(col.r, col.g, col.b);
9145
10184
  const boldOps = seg.bold && !usedDedicatedBold ? [
9146
- PDFOperator.of("Tr", [PDFNumber2.of(2)]),
10185
+ PDFOperator.of("Tr", [PDFNumber3.of(2)]),
9147
10186
  setLineWidth(Math.max(0.25, seg.fontSize * 0.032)),
9148
10187
  colorType === "cmyk" ? (() => {
9149
10188
  const cm = rgbToCmyk(col.r, col.g, col.b);
@@ -9151,12 +10190,12 @@ async function drawRichOrColumnTextBox(pdfDoc, page, pageHeight, spans, left, to
9151
10190
  })() : setStrokingRgbColor(col.r, col.g, col.b)
9152
10191
  ] : [];
9153
10192
  const posOp = seg.italic ? PDFOperator.of("Tm", [
9154
- PDFNumber2.of(1),
9155
- PDFNumber2.of(0),
9156
- PDFNumber2.of(0.2126),
9157
- PDFNumber2.of(1),
9158
- PDFNumber2.of(segX),
9159
- PDFNumber2.of(baselineY)
10193
+ PDFNumber3.of(1),
10194
+ PDFNumber3.of(0),
10195
+ PDFNumber3.of(0.2126),
10196
+ PDFNumber3.of(1),
10197
+ PDFNumber3.of(segX),
10198
+ PDFNumber3.of(baselineY)
9160
10199
  ]) : moveText(segX, baselineY);
9161
10200
  page.pushOperators(
9162
10201
  pushGraphicsState2(),
@@ -9165,7 +10204,7 @@ async function drawRichOrColumnTextBox(pdfDoc, page, pageHeight, spans, left, to
9165
10204
  ...boldOps,
9166
10205
  setFontAndSize(fontKey, seg.fontSize),
9167
10206
  posOp,
9168
- showText(PDFHexString.of(hexStr)),
10207
+ showText(PDFHexString2.of(hexStr)),
9169
10208
  endText(),
9170
10209
  popGraphicsState2()
9171
10210
  );
@@ -9307,10 +10346,11 @@ function attachPdfOutlinesTree(pdfDoc, bookmarks) {
9307
10346
  const selfRef = itemRefs[i];
9308
10347
  const clampedPageIdx = Math.max(0, Math.min(allPages.length - 1, Math.floor(item.pageIndex || 0)));
9309
10348
  const targetPage = allPages[clampedPageIdx];
9310
- const destY = item.topOffsetPt !== void 0 ? Math.round(Math.max(0, targetPage.getHeight() - item.topOffsetPt) * 100) / 100 : null;
9311
- const destArray = pdfDoc.context.obj([targetPage.ref, PDFName2.of("XYZ"), null, destY, null]);
10349
+ const effectiveTopOffset = item.topPt ?? item.topOffsetPt;
10350
+ const destY = effectiveTopOffset !== void 0 ? Math.round(Math.max(0, targetPage.getHeight() - effectiveTopOffset) * 100) / 100 : null;
10351
+ const destArray = pdfDoc.context.obj([targetPage.ref, PDFName3.of("XYZ"), null, destY, null]);
9312
10352
  const dictObj = {
9313
- Title: PDFHexString.fromText(item.title || "Bookmark"),
10353
+ Title: PDFHexString2.fromText(item.title || "Bookmark"),
9314
10354
  Parent: parentRef,
9315
10355
  Dest: destArray
9316
10356
  };
@@ -9343,15 +10383,15 @@ function attachPdfOutlinesTree(pdfDoc, bookmarks) {
9343
10383
  Count: rootChain.totalCount
9344
10384
  })
9345
10385
  );
9346
- pdfDoc.catalog.set(PDFName2.of("Outlines"), outlinesRef);
10386
+ pdfDoc.catalog.set(PDFName3.of("Outlines"), outlinesRef);
9347
10387
  }
9348
10388
  function ensurePagePropertiesDict(pdfDoc, pdfPage) {
9349
10389
  pdfPage.node.normalize();
9350
10390
  const res = pdfPage.node.Resources();
9351
- let props = pdfDoc.context.lookupMaybe(res.get(PDFName2.of("Properties")), PDFDict2);
10391
+ let props = pdfDoc.context.lookupMaybe(res.get(PDFName3.of("Properties")), PDFDict3);
9352
10392
  if (!props) {
9353
10393
  props = pdfDoc.context.obj({});
9354
- res.set(PDFName2.of("Properties"), props);
10394
+ res.set(PDFName3.of("Properties"), props);
9355
10395
  }
9356
10396
  return props;
9357
10397
  }
@@ -9367,11 +10407,11 @@ function attachOptionalContentLayers(pdfDoc, layers) {
9367
10407
  const isPrint = layer.printable !== false;
9368
10408
  const ocgDict = pdfDoc.context.obj({
9369
10409
  Type: "OCG",
9370
- Name: PDFHexString.fromText(layer.name || layer.id),
9371
- Intent: [PDFName2.of("View"), PDFName2.of("Design")],
10410
+ Name: PDFHexString2.fromText(layer.name || layer.id),
10411
+ Intent: [PDFName3.of("View"), PDFName3.of("Design")],
9372
10412
  Usage: {
9373
- View: { ViewState: PDFName2.of(isVis ? "ON" : "OFF") },
9374
- Print: { PrintState: PDFName2.of(isPrint ? "ON" : "OFF") }
10413
+ View: { ViewState: PDFName3.of(isVis ? "ON" : "OFF") },
10414
+ Print: { PrintState: PDFName3.of(isPrint ? "ON" : "OFF") }
9375
10415
  }
9376
10416
  });
9377
10417
  const ocgRef = pdfDoc.context.register(ocgDict);
@@ -9386,11 +10426,11 @@ function attachOptionalContentLayers(pdfDoc, layers) {
9386
10426
  });
9387
10427
  });
9388
10428
  pdfDoc.catalog.set(
9389
- PDFName2.of("OCProperties"),
10429
+ PDFName3.of("OCProperties"),
9390
10430
  pdfDoc.context.obj({
9391
10431
  OCGs: allRefs,
9392
10432
  D: {
9393
- BaseState: PDFName2.of("ON"),
10433
+ BaseState: PDFName3.of("ON"),
9394
10434
  ON: onRefs,
9395
10435
  OFF: offRefs,
9396
10436
  Order: allRefs,
@@ -9409,7 +10449,7 @@ function attachEmbeddedFileAttachments(pdfDoc, attachments) {
9409
10449
  const subtypeSafe = (att.mimeType || "application/octet-stream").replace(/\//g, "#2F");
9410
10450
  const efStream = pdfDoc.context.flateStream(fileBytes, {
9411
10451
  Type: "EmbeddedFile",
9412
- Subtype: PDFName2.of(subtypeSafe),
10452
+ Subtype: PDFName3.of(subtypeSafe),
9413
10453
  Params: {
9414
10454
  Size: fileBytes.byteLength
9415
10455
  }
@@ -9417,30 +10457,30 @@ function attachEmbeddedFileAttachments(pdfDoc, attachments) {
9417
10457
  const efRef = pdfDoc.context.register(efStream);
9418
10458
  const filespecObj = {
9419
10459
  Type: "Filespec",
9420
- F: PDFString.of((att.fileName || "attachment.bin").replace(/[^\x20-\x7E]/g, "_")),
9421
- UF: PDFHexString.fromText(att.fileName || "attachment.bin"),
10460
+ F: PDFString2.of((att.fileName || "attachment.bin").replace(/[^\x20-\x7E]/g, "_")),
10461
+ UF: PDFHexString2.fromText(att.fileName || "attachment.bin"),
9422
10462
  EF: {
9423
10463
  F: efRef,
9424
10464
  UF: efRef
9425
10465
  }
9426
10466
  };
9427
10467
  if (att.description) {
9428
- filespecObj.Desc = PDFHexString.fromText(att.description);
10468
+ filespecObj.Desc = PDFHexString2.fromText(att.description);
9429
10469
  }
9430
10470
  const filespecRef = pdfDoc.context.register(pdfDoc.context.obj(filespecObj));
9431
- namesArr.push(PDFHexString.fromText(att.fileName || "attachment.bin"), filespecRef);
10471
+ namesArr.push(PDFHexString2.fromText(att.fileName || "attachment.bin"), filespecRef);
9432
10472
  }
9433
10473
  const efTreeRef = pdfDoc.context.register(
9434
10474
  pdfDoc.context.obj({
9435
10475
  Names: namesArr
9436
10476
  })
9437
10477
  );
9438
- const existingNames = pdfDoc.context.lookupMaybe(pdfDoc.catalog.get(PDFName2.of("Names")), PDFDict2);
10478
+ const existingNames = pdfDoc.context.lookupMaybe(pdfDoc.catalog.get(PDFName3.of("Names")), PDFDict3);
9439
10479
  if (existingNames) {
9440
- existingNames.set(PDFName2.of("EmbeddedFiles"), efTreeRef);
10480
+ existingNames.set(PDFName3.of("EmbeddedFiles"), efTreeRef);
9441
10481
  } else {
9442
10482
  pdfDoc.catalog.set(
9443
- PDFName2.of("Names"),
10483
+ PDFName3.of("Names"),
9444
10484
  pdfDoc.context.obj({
9445
10485
  EmbeddedFiles: efTreeRef
9446
10486
  })
@@ -9484,7 +10524,7 @@ function attachPdfAComplianceMetadata(pdfDoc, snapshot, includePdfUa) {
9484
10524
  Length: xmpBytes.byteLength
9485
10525
  });
9486
10526
  const metadataRef = pdfDoc.context.register(metadataStream);
9487
- pdfDoc.catalog.set(PDFName2.of("Metadata"), metadataRef);
10527
+ pdfDoc.catalog.set(PDFName3.of("Metadata"), metadataRef);
9488
10528
  const srgbHeaderBytes = new TextEncoder().encode("sRGB IEC61966-2.1 ICC Output Profile");
9489
10529
  const iccStream = pdfDoc.context.flateStream(srgbHeaderBytes, {
9490
10530
  N: 3,
@@ -9495,13 +10535,13 @@ function attachPdfAComplianceMetadata(pdfDoc, snapshot, includePdfUa) {
9495
10535
  pdfDoc.context.obj({
9496
10536
  Type: "OutputIntent",
9497
10537
  S: "GTS_PDFA1",
9498
- OutputConditionIdentifier: PDFString.of("sRGB IEC61966-2.1"),
9499
- RegistryName: PDFString.of("http://www.color.org"),
9500
- Info: PDFString.of("sRGB IEC61966-2.1"),
10538
+ OutputConditionIdentifier: PDFString2.of("sRGB IEC61966-2.1"),
10539
+ RegistryName: PDFString2.of("http://www.color.org"),
10540
+ Info: PDFString2.of("sRGB IEC61966-2.1"),
9501
10541
  DestOutputProfile: iccRef
9502
10542
  })
9503
10543
  );
9504
- pdfDoc.catalog.set(PDFName2.of("OutputIntents"), pdfDoc.context.obj([outputIntentRef]));
10544
+ pdfDoc.catalog.set(PDFName3.of("OutputIntents"), pdfDoc.context.obj([outputIntentRef]));
9505
10545
  }
9506
10546
  function resolveElementStructRole(el) {
9507
10547
  switch (el.type) {
@@ -9533,9 +10573,9 @@ function resolveElementStructRole(el) {
9533
10573
  }
9534
10574
  }
9535
10575
  function attachTaggedStructTreeRoot(pdfDoc, snapshot, items, totalPages) {
9536
- pdfDoc.catalog.set(PDFName2.of("Lang"), PDFString.of(snapshot.locale ? String(snapshot.locale) : "zh-CN"));
9537
- pdfDoc.catalog.set(PDFName2.of("MarkInfo"), pdfDoc.context.obj({ Marked: PDFBool.True }));
9538
- pdfDoc.catalog.set(PDFName2.of("ViewerPreferences"), pdfDoc.context.obj({ DisplayDocTitle: PDFBool.True }));
10576
+ pdfDoc.catalog.set(PDFName3.of("Lang"), PDFString2.of(snapshot.locale ? String(snapshot.locale) : "zh-CN"));
10577
+ pdfDoc.catalog.set(PDFName3.of("MarkInfo"), pdfDoc.context.obj({ Marked: PDFBool.True }));
10578
+ pdfDoc.catalog.set(PDFName3.of("ViewerPreferences"), pdfDoc.context.obj({ DisplayDocTitle: PDFBool.True }));
9539
10579
  if (!snapshot.metadata?.sanitized && snapshot.name) {
9540
10580
  pdfDoc.setTitle(snapshot.name);
9541
10581
  }
@@ -9547,16 +10587,16 @@ function attachTaggedStructTreeRoot(pdfDoc, snapshot, items, totalPages) {
9547
10587
  const elemRef = pdfDoc.context.nextRef();
9548
10588
  const elemDict = {
9549
10589
  Type: "StructElem",
9550
- S: PDFName2.of(item.role),
10590
+ S: PDFName3.of(item.role),
9551
10591
  P: docElemRef,
9552
10592
  Pg: item.pageRef,
9553
- K: PDFNumber2.of(item.mcid)
10593
+ K: PDFNumber3.of(item.mcid)
9554
10594
  };
9555
10595
  if (item.altText) {
9556
- elemDict.Alt = PDFHexString.fromText(item.altText);
10596
+ elemDict.Alt = PDFHexString2.fromText(item.altText);
9557
10597
  }
9558
10598
  if (item.title) {
9559
- elemDict.T = PDFHexString.fromText(item.title);
10599
+ elemDict.T = PDFHexString2.fromText(item.title);
9560
10600
  }
9561
10601
  pdfDoc.context.assign(elemRef, pdfDoc.context.obj(elemDict));
9562
10602
  childElemRefs.push(elemRef);
@@ -9571,7 +10611,7 @@ function attachTaggedStructTreeRoot(pdfDoc, snapshot, items, totalPages) {
9571
10611
  docElemRef,
9572
10612
  pdfDoc.context.obj({
9573
10613
  Type: "StructElem",
9574
- S: PDFName2.of("Document"),
10614
+ S: PDFName3.of("Document"),
9575
10615
  P: structTreeRootRef,
9576
10616
  K: childElemRefs
9577
10617
  })
@@ -9579,7 +10619,7 @@ function attachTaggedStructTreeRoot(pdfDoc, snapshot, items, totalPages) {
9579
10619
  const numsList = [];
9580
10620
  for (let p = 0; p < totalPages; p++) {
9581
10621
  const refsForPage = (byPageMcid.get(p) ?? []).filter(Boolean);
9582
- numsList.push(PDFNumber2.of(p), pdfDoc.context.obj(refsForPage));
10622
+ numsList.push(PDFNumber3.of(p), pdfDoc.context.obj(refsForPage));
9583
10623
  }
9584
10624
  const parentTreeRef = pdfDoc.context.register(pdfDoc.context.obj({ Nums: numsList }));
9585
10625
  pdfDoc.context.assign(
@@ -9591,14 +10631,14 @@ function attachTaggedStructTreeRoot(pdfDoc, snapshot, items, totalPages) {
9591
10631
  ParentTreeNextKey: totalPages
9592
10632
  })
9593
10633
  );
9594
- pdfDoc.catalog.set(PDFName2.of("StructTreeRoot"), structTreeRootRef);
10634
+ pdfDoc.catalog.set(PDFName3.of("StructTreeRoot"), structTreeRootRef);
9595
10635
  }
9596
10636
  function pruneUnreferencedObjectsAndCompressStreams(pdfDoc) {
9597
10637
  for (const [ref, obj] of pdfDoc.context.enumerateIndirectObjects()) {
9598
- if (obj instanceof PDFRawStream2) {
9599
- const typeName = obj.dict.get(PDFName2.of("Type"));
9600
- const isMetadata = typeName instanceof PDFName2 && typeName.decodeText() === "Metadata";
9601
- const hasFilter = Boolean(obj.dict.get(PDFName2.of("Filter")));
10638
+ if (obj instanceof PDFRawStream3) {
10639
+ const typeName = obj.dict.get(PDFName3.of("Type"));
10640
+ const isMetadata = typeName instanceof PDFName3 && typeName.decodeText() === "Metadata";
10641
+ const hasFilter = Boolean(obj.dict.get(PDFName3.of("Filter")));
9602
10642
  if (!isMetadata && !hasFilter && obj.contents.byteLength > 64) {
9603
10643
  const compressed = pdfDoc.context.flateStream(obj.contents);
9604
10644
  for (const [k, v] of obj.dict.entries()) {
@@ -9615,26 +10655,26 @@ function pruneUnreferencedObjectsAndCompressStreams(pdfDoc) {
9615
10655
  const refToString = (r) => `${r.objectNumber}:${r.generationNumber}`;
9616
10656
  const visit = (node) => {
9617
10657
  if (!node) return;
9618
- if (node instanceof PDFRef2) {
10658
+ if (node instanceof PDFRef3) {
9619
10659
  const key = refToString(node);
9620
10660
  if (reachable.has(key)) return;
9621
10661
  reachable.add(key);
9622
10662
  visit(pdfDoc.context.lookup(node));
9623
10663
  return;
9624
10664
  }
9625
- if (node instanceof PDFDict2) {
10665
+ if (node instanceof PDFDict3) {
9626
10666
  for (const [, val] of node.entries()) {
9627
10667
  visit(val);
9628
10668
  }
9629
10669
  return;
9630
10670
  }
9631
- if (node instanceof PDFArray2) {
10671
+ if (node instanceof PDFArray3) {
9632
10672
  for (let i = 0; i < node.size(); i++) {
9633
10673
  visit(node.get(i));
9634
10674
  }
9635
10675
  return;
9636
10676
  }
9637
- if (node instanceof PDFRawStream2 || node instanceof PDFStream2) {
10677
+ if (node instanceof PDFRawStream3 || node instanceof PDFStream3) {
9638
10678
  visit(node.dict);
9639
10679
  }
9640
10680
  };
@@ -9667,10 +10707,10 @@ async function drawInvisibleSearchableOcrSpans(pdfDoc, pdfPage, pageHeight, span
9667
10707
  pdfPage.pushOperators(
9668
10708
  pushGraphicsState2(),
9669
10709
  beginText(),
9670
- PDFOperator.of("Tr", [PDFNumber2.of(3)]),
10710
+ PDFOperator.of("Tr", [PDFNumber3.of(3)]),
9671
10711
  setFontAndSize(fontKey, fs),
9672
10712
  moveText(span.left, baselineY),
9673
- showText(PDFHexString.of(hexStr)),
10713
+ showText(PDFHexString2.of(hexStr)),
9674
10714
  endText(),
9675
10715
  popGraphicsState2()
9676
10716
  );
@@ -9683,10 +10723,10 @@ async function drawInvisibleSearchableOcrSpans(pdfDoc, pdfPage, pageHeight, span
9683
10723
  pdfPage.pushOperators(
9684
10724
  pushGraphicsState2(),
9685
10725
  beginText(),
9686
- PDFOperator.of("Tr", [PDFNumber2.of(3)]),
10726
+ PDFOperator.of("Tr", [PDFNumber3.of(3)]),
9687
10727
  setFontAndSize(fontKey, fs),
9688
10728
  moveText(span.left, baselineY),
9689
- showText(PDFHexString.of(asciiHex)),
10729
+ showText(PDFHexString2.of(asciiHex)),
9690
10730
  endText(),
9691
10731
  popGraphicsState2()
9692
10732
  );
@@ -9757,7 +10797,7 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
9757
10797
  const optimizeSize = Boolean(options?.optimizeSize);
9758
10798
  const preResolvedFonts = await resolveRenderFontsForExport(snapshot, effectiveData, options);
9759
10799
  throwIfExportAborted();
9760
- const pdfDoc = await PDFDocument2.create();
10800
+ const pdfDoc = await PDFDocument3.create();
9761
10801
  if (snapshot.metadata?.sanitized) {
9762
10802
  pdfDoc.setTitle("");
9763
10803
  pdfDoc.setAuthor("");
@@ -9957,7 +10997,7 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
9957
10997
  if (!excludeBasePdf && snapshot.sourceDocumentRef?.dataUri) {
9958
10998
  try {
9959
10999
  const srcBytes = dataUriToBytes(snapshot.sourceDocumentRef.dataUri);
9960
- sourcePdfDoc = await PDFDocument2.load(srcBytes);
11000
+ sourcePdfDoc = await PDFDocument3.load(srcBytes);
9961
11001
  } catch {
9962
11002
  sourcePdfDoc = null;
9963
11003
  }
@@ -10171,21 +11211,21 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10171
11211
  const [copied] = await pdfDoc.copyPages(sourcePdfDoc, [pageMeta.sourcePageNumber - 1]);
10172
11212
  pdfPage = pdfDoc.addPage(copied);
10173
11213
  if (snapshot.metadata?.importedAcroFormBase) {
10174
- const existingAnnots = pdfDoc.context.lookupMaybe(pdfPage.node.get(PDFName2.of("Annots")), PDFArray2);
11214
+ const existingAnnots = pdfDoc.context.lookupMaybe(pdfPage.node.get(PDFName3.of("Annots")), PDFArray3);
10175
11215
  if (existingAnnots) {
10176
11216
  const filtered = [];
10177
11217
  for (let ai = 0; ai < existingAnnots.size(); ai++) {
10178
11218
  const aRef = existingAnnots.get(ai);
10179
- const aDict = pdfDoc.context.lookupMaybe(aRef, PDFDict2);
10180
- const sub = aDict?.get(PDFName2.of("Subtype"));
10181
- if (!(sub instanceof PDFName2 && sub.decodeText() === "Widget")) {
11219
+ const aDict = pdfDoc.context.lookupMaybe(aRef, PDFDict3);
11220
+ const sub = aDict?.get(PDFName3.of("Subtype"));
11221
+ if (!(sub instanceof PDFName3 && sub.decodeText() === "Widget")) {
10182
11222
  filtered.push(aRef);
10183
11223
  }
10184
11224
  }
10185
11225
  if (filtered.length > 0) {
10186
- pdfPage.node.set(PDFName2.of("Annots"), pdfDoc.context.obj(filtered));
11226
+ pdfPage.node.set(PDFName3.of("Annots"), pdfDoc.context.obj(filtered));
10187
11227
  } else {
10188
- pdfPage.node.delete(PDFName2.of("Annots"));
11228
+ pdfPage.node.delete(PDFName3.of("Annots"));
10189
11229
  }
10190
11230
  }
10191
11231
  }
@@ -10196,7 +11236,7 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10196
11236
  let size = pageMeta.pageSize ?? snapshot.document.pageSize;
10197
11237
  if (excludeBasePdf && snapshot.sourceDocumentRef?.dataUri && !pageMeta.pageSize) {
10198
11238
  try {
10199
- const tempSrc = await PDFDocument2.load(dataUriToBytes(snapshot.sourceDocumentRef.dataUri));
11239
+ const tempSrc = await PDFDocument3.load(dataUriToBytes(snapshot.sourceDocumentRef.dataUri));
10200
11240
  const pIdx0 = Math.max(0, (pageMeta.sourcePageNumber ?? 1) - 1);
10201
11241
  if (pIdx0 < tempSrc.getPageCount()) {
10202
11242
  const refSz = tempSrc.getPage(pIdx0).getSize();
@@ -10240,8 +11280,8 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10240
11280
  }
10241
11281
  }
10242
11282
  if (accessibilityTagged) {
10243
- pdfPage.node.set(PDFName2.of("StructParents"), PDFNumber2.of(pIndex));
10244
- pdfPage.node.set(PDFName2.of("Tabs"), PDFName2.of("S"));
11283
+ pdfPage.node.set(PDFName3.of("StructParents"), PDFNumber3.of(pIndex));
11284
+ pdfPage.node.set(PDFName3.of("Tabs"), PDFName3.of("S"));
10245
11285
  }
10246
11286
  let nextPageMcid = 0;
10247
11287
  const activeDynamicRange = planItem.dynamicSplitRanges ? planItem.dynamicSplitRanges[chunkIndex] : void 0;
@@ -10296,9 +11336,9 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10296
11336
  let hasOpenCenterTransform = false;
10297
11337
  if (ocgEntry) {
10298
11338
  const propsDict = ensurePagePropertiesDict(pdfDoc, pdfPage);
10299
- propsDict.set(PDFName2.of(ocgEntry.propName), ocgEntry.ocgRef);
11339
+ propsDict.set(PDFName3.of(ocgEntry.propName), ocgEntry.ocgRef);
10300
11340
  pdfPage.pushOperators(
10301
- PDFOperator.of("BDC", [PDFName2.of("OC"), PDFName2.of(ocgEntry.propName)])
11341
+ PDFOperator.of("BDC", [PDFName3.of("OC"), PDFName3.of(ocgEntry.propName)])
10302
11342
  );
10303
11343
  openBdcCount++;
10304
11344
  }
@@ -10306,10 +11346,10 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10306
11346
  const mcid = nextPageMcid++;
10307
11347
  const mcPropName = `MC_${mcid}`;
10308
11348
  const propsDict = ensurePagePropertiesDict(pdfDoc, pdfPage);
10309
- propsDict.set(PDFName2.of(mcPropName), pdfDoc.context.obj({ MCID: PDFNumber2.of(mcid) }));
11349
+ propsDict.set(PDFName3.of(mcPropName), pdfDoc.context.obj({ MCID: PDFNumber3.of(mcid) }));
10310
11350
  const role = resolveElementStructRole(el);
10311
11351
  pdfPage.pushOperators(
10312
- PDFOperator.of("BDC", [PDFName2.of(role), PDFName2.of(mcPropName)])
11352
+ PDFOperator.of("BDC", [PDFName3.of(role), PDFName3.of(mcPropName)])
10313
11353
  );
10314
11354
  openBdcCount++;
10315
11355
  taggedStructItems.push({
@@ -10664,9 +11704,9 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10664
11704
  if (textEl.locked) tf.enableReadOnly();
10665
11705
  if (textEl.required) tf.enableRequired();
10666
11706
  tf.acroField.dict.set(
10667
- PDFName2.of("YudaoMeta"),
11707
+ PDFName3.of("YudaoMeta"),
10668
11708
  pdfDoc.context.obj({
10669
- ElementType: PDFName2.of("text"),
11709
+ ElementType: PDFName3.of("text"),
10670
11710
  Left: left,
10671
11711
  Top: top,
10672
11712
  Width: width,
@@ -10686,10 +11726,10 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10686
11726
  txtCol
10687
11727
  });
10688
11728
  const daStr = `/FCjk ${fmtPdfNum(fsVal)} Tf ${fmtPdfNum(txtCol.r)} ${fmtPdfNum(txtCol.g)} ${fmtPdfNum(txtCol.b)} rg`;
10689
- tf.acroField.dict.set(PDFName2.of("DA"), PDFString.of(daStr));
11729
+ tf.acroField.dict.set(PDFName3.of("DA"), PDFString2.of(daStr));
10690
11730
  for (const w of tf.acroField.getWidgets()) {
10691
- w.dict.set(PDFName2.of("AP"), pdfDoc.context.obj({ N: apRef }));
10692
- w.dict.set(PDFName2.of("DA"), PDFString.of(daStr));
11731
+ w.dict.set(PDFName3.of("AP"), pdfDoc.context.obj({ N: apRef }));
11732
+ w.dict.set(PDFName3.of("DA"), PDFString2.of(daStr));
10693
11733
  }
10694
11734
  } else {
10695
11735
  tf.defaultUpdateAppearances(await ensureAcroHelvetica());
@@ -10894,21 +11934,21 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10894
11934
  if (dtEl.locked) tf.enableReadOnly();
10895
11935
  if (dtEl.required) tf.enableRequired();
10896
11936
  tf.acroField.dict.set(
10897
- PDFName2.of("TU"),
10898
- PDFHexString.fromText(
11937
+ PDFName3.of("TU"),
11938
+ PDFHexString2.fromText(
10899
11939
  `dateTime:${dtEl.dateKind || "date"}|${dtEl.format || "YYYY-MM-DD"}|${dtEl.locale || ""}`
10900
11940
  )
10901
11941
  );
10902
11942
  tf.acroField.dict.set(
10903
- PDFName2.of("YudaoMeta"),
11943
+ PDFName3.of("YudaoMeta"),
10904
11944
  pdfDoc.context.obj({
10905
- ElementType: PDFName2.of("dateTime"),
10906
- DateKind: PDFString.of(dtEl.dateKind || "date"),
10907
- Format: PDFHexString.fromText(dtEl.format || "YYYY-MM-DD"),
10908
- ...dtEl.locale ? { Locale: PDFString.of(dtEl.locale) } : {},
10909
- RawValue: PDFHexString.fromText(rawDtVal),
11945
+ ElementType: PDFName3.of("dateTime"),
11946
+ DateKind: PDFString2.of(dtEl.dateKind || "date"),
11947
+ Format: PDFHexString2.fromText(dtEl.format || "YYYY-MM-DD"),
11948
+ ...dtEl.locale ? { Locale: PDFString2.of(dtEl.locale) } : {},
11949
+ RawValue: PDFHexString2.fromText(rawDtVal),
10910
11950
  FontSize: dtFontSize,
10911
- Align: PDFString.of(dtAlign),
11951
+ Align: PDFString2.of(dtAlign),
10912
11952
  ...dtEl.characterSpacing !== void 0 ? { CharacterSpacing: dtEl.characterSpacing } : {},
10913
11953
  Left: left,
10914
11954
  Top: top,
@@ -10929,10 +11969,10 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10929
11969
  txtCol
10930
11970
  });
10931
11971
  const daStr = `/FCjk ${fmtPdfNum(dtFontSize)} Tf ${fmtPdfNum(txtCol.r)} ${fmtPdfNum(txtCol.g)} ${fmtPdfNum(txtCol.b)} rg`;
10932
- tf.acroField.dict.set(PDFName2.of("DA"), PDFString.of(daStr));
11972
+ tf.acroField.dict.set(PDFName3.of("DA"), PDFString2.of(daStr));
10933
11973
  for (const w of tf.acroField.getWidgets()) {
10934
- w.dict.set(PDFName2.of("AP"), pdfDoc.context.obj({ N: apRef }));
10935
- w.dict.set(PDFName2.of("DA"), PDFString.of(daStr));
11974
+ w.dict.set(PDFName3.of("AP"), pdfDoc.context.obj({ N: apRef }));
11975
+ w.dict.set(PDFName3.of("DA"), PDFString2.of(daStr));
10936
11976
  }
10937
11977
  } else {
10938
11978
  tf.defaultUpdateAppearances(await ensureAcroHelvetica());
@@ -10995,14 +12035,14 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
10995
12035
  if (cbEl.required) cb.enableRequired();
10996
12036
  cb.defaultUpdateAppearances();
10997
12037
  cb.acroField.dict.set(
10998
- PDFName2.of("TU"),
10999
- PDFHexString.fromText(cbEl.label || fieldName)
12038
+ PDFName3.of("TU"),
12039
+ PDFHexString2.fromText(cbEl.label || fieldName)
11000
12040
  );
11001
12041
  cb.acroField.dict.set(
11002
- PDFName2.of("YudaoMeta"),
12042
+ PDFName3.of("YudaoMeta"),
11003
12043
  pdfDoc.context.obj({
11004
- ElementType: PDFName2.of("checkbox"),
11005
- Label: PDFHexString.fromText(cbEl.label || ""),
12044
+ ElementType: PDFName3.of("checkbox"),
12045
+ Label: PDFHexString2.fromText(cbEl.label || ""),
11006
12046
  BoxWidth: boxSz,
11007
12047
  Left: left,
11008
12048
  Top: top,
@@ -11133,10 +12173,10 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11133
12173
  if (rgEl.required) rg.enableRequired();
11134
12174
  rg.defaultUpdateAppearances();
11135
12175
  rg.acroField.dict.set(
11136
- PDFName2.of("YudaoMeta"),
12176
+ PDFName3.of("YudaoMeta"),
11137
12177
  pdfDoc.context.obj({
11138
- ElementType: PDFName2.of("radioGroup"),
11139
- Direction: PDFString.of(rgEl.direction || "horizontal"),
12178
+ ElementType: PDFName3.of("radioGroup"),
12179
+ Direction: PDFString2.of(rgEl.direction || "horizontal"),
11140
12180
  Left: left,
11141
12181
  Top: top,
11142
12182
  Width: width,
@@ -11204,10 +12244,10 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11204
12244
  if (selEl.locked) dd.enableReadOnly();
11205
12245
  if (selEl.required) dd.enableRequired();
11206
12246
  dd.acroField.dict.set(
11207
- PDFName2.of("YudaoMeta"),
12247
+ PDFName3.of("YudaoMeta"),
11208
12248
  pdfDoc.context.obj({
11209
- ElementType: PDFName2.of("select"),
11210
- ...selEl.placeholder ? { Placeholder: PDFHexString.fromText(selEl.placeholder) } : {},
12249
+ ElementType: PDFName3.of("select"),
12250
+ ...selEl.placeholder ? { Placeholder: PDFHexString2.fromText(selEl.placeholder) } : {},
11211
12251
  Left: left,
11212
12252
  Top: top,
11213
12253
  Width: width,
@@ -11227,10 +12267,10 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11227
12267
  txtCol
11228
12268
  });
11229
12269
  const daStr = `/FCjk ${fmtPdfNum(fsVal)} Tf ${fmtPdfNum(txtCol.r)} ${fmtPdfNum(txtCol.g)} ${fmtPdfNum(txtCol.b)} rg`;
11230
- dd.acroField.dict.set(PDFName2.of("DA"), PDFString.of(daStr));
12270
+ dd.acroField.dict.set(PDFName3.of("DA"), PDFString2.of(daStr));
11231
12271
  for (const w of dd.acroField.getWidgets()) {
11232
- w.dict.set(PDFName2.of("AP"), pdfDoc.context.obj({ N: apRef }));
11233
- w.dict.set(PDFName2.of("DA"), PDFString.of(daStr));
12272
+ w.dict.set(PDFName3.of("AP"), pdfDoc.context.obj({ N: apRef }));
12273
+ w.dict.set(PDFName3.of("DA"), PDFString2.of(daStr));
11234
12274
  }
11235
12275
  } else {
11236
12276
  dd.defaultUpdateAppearances(await ensureAcroHelvetica());
@@ -11270,8 +12310,8 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11270
12310
  Type: "Annot",
11271
12311
  Subtype: "Widget",
11272
12312
  FT: "Sig",
11273
- T: PDFHexString.fromText(fieldName),
11274
- TU: PDFHexString.fromText(sigEl.label || fieldName),
12313
+ T: PDFHexString2.fromText(fieldName),
12314
+ TU: PDFHexString2.fromText(sigEl.label || fieldName),
11275
12315
  Rect: [left, pdfY, left + width, pdfY + height],
11276
12316
  P: pdfPage.ref,
11277
12317
  F: 4,
@@ -11279,12 +12319,12 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11279
12319
  AP: { N: sigApRef },
11280
12320
  MK: { R: rotDeg },
11281
12321
  YudaoMeta: {
11282
- ElementType: PDFName2.of("signature"),
11283
- Label: PDFHexString.fromText(sigEl.label || "Signature"),
11284
- ...sigEl.signerName ? { SignerName: PDFHexString.fromText(sigEl.signerName) } : {},
11285
- ...sigEl.signedAt ? { SignedAt: PDFString.of(sigEl.signedAt) } : {},
11286
- ...sigEl.reason ? { Reason: PDFHexString.fromText(sigEl.reason) } : {},
11287
- ...sigEl.signatureDataUri ? { SignatureDataUri: PDFString.of(sigEl.signatureDataUri) } : {},
12322
+ ElementType: PDFName3.of("signature"),
12323
+ Label: PDFHexString2.fromText(sigEl.label || "Signature"),
12324
+ ...sigEl.signerName ? { SignerName: PDFHexString2.fromText(sigEl.signerName) } : {},
12325
+ ...sigEl.signedAt ? { SignedAt: PDFString2.of(sigEl.signedAt) } : {},
12326
+ ...sigEl.reason ? { Reason: PDFHexString2.fromText(sigEl.reason) } : {},
12327
+ ...sigEl.signatureDataUri ? { SignatureDataUri: PDFString2.of(sigEl.signatureDataUri) } : {},
11288
12328
  Left: left,
11289
12329
  Top: top,
11290
12330
  Width: width,
@@ -11295,11 +12335,11 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11295
12335
  if (sigEl.signerName || sigEl.signatureDataUri) {
11296
12336
  sigWidgetObj.V = pdfDoc.context.obj({
11297
12337
  Type: "Sig",
11298
- Filter: PDFName2.of("Adobe.PPKLite"),
11299
- SubFilter: PDFName2.of("adbe.pkcs7.detached"),
11300
- Name: PDFHexString.fromText(sigEl.signerName || sigEl.label || "Signed"),
11301
- ...sigEl.signedAt ? { M: PDFString.of(sigEl.signedAt) } : {},
11302
- ...sigEl.reason ? { Reason: PDFHexString.fromText(sigEl.reason) } : {}
12338
+ Filter: PDFName3.of("Adobe.PPKLite"),
12339
+ SubFilter: PDFName3.of("adbe.pkcs7.detached"),
12340
+ Name: PDFHexString2.fromText(sigEl.signerName || sigEl.label || "Signed"),
12341
+ ...sigEl.signedAt ? { M: PDFString2.of(sigEl.signedAt) } : {},
12342
+ ...sigEl.reason ? { Reason: PDFHexString2.fromText(sigEl.reason) } : {}
11303
12343
  });
11304
12344
  }
11305
12345
  const sigRef = pdfDoc.context.register(pdfDoc.context.obj(sigWidgetObj));
@@ -11629,8 +12669,8 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11629
12669
  Rect: [left, pdfY, left + width, pdfY + height],
11630
12670
  C: [col.r, col.g, col.b],
11631
12671
  CA: op,
11632
- T: PDFHexString.fromText(annotEl.author || "Reviewer"),
11633
- Contents: PDFHexString.fromText(threadSummary)
12672
+ T: PDFHexString2.fromText(annotEl.author || "Reviewer"),
12673
+ Contents: PDFHexString2.fromText(threadSummary)
11634
12674
  };
11635
12675
  if (pdfSubtype !== "Text") {
11636
12676
  annotDictEntries.QuadPoints = [
@@ -11801,7 +12841,7 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11801
12841
  setFillingRgbColor(0.78, 0.81, 0.86),
11802
12842
  setFontAndSize(fontKey, wmSize),
11803
12843
  rotateAndSkewTextDegreesAndTranslate(wmAngle, 0, 0, wx, wy),
11804
- showText(PDFHexString.of(hexWm)),
12844
+ showText(PDFHexString2.of(hexWm)),
11805
12845
  endText(),
11806
12846
  popGraphicsState2()
11807
12847
  );
@@ -11849,7 +12889,7 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11849
12889
  }
11850
12890
  return void 0;
11851
12891
  };
11852
- return walk(snapshot.metadata?.bookmarks);
12892
+ return walk(snapshot.bookmarks ?? snapshot.metadata?.bookmarks);
11853
12893
  };
11854
12894
  for (const linkItem of deferredLinkAnnotations) {
11855
12895
  const hostPage = allPages[linkItem.hostPageIndex];
@@ -11864,9 +12904,9 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11864
12904
  const targetPage = allPages[clampedIdx];
11865
12905
  const destArr = pdfDoc.context.obj([
11866
12906
  targetPage.ref,
11867
- PDFName2.of("XYZ"),
11868
- PDFNumber2.of(elDest.x),
11869
- PDFNumber2.of(elDest.topY),
12907
+ PDFName3.of("XYZ"),
12908
+ PDFNumber3.of(elDest.x),
12909
+ PDFNumber3.of(elDest.topY),
11870
12910
  null
11871
12911
  ]);
11872
12912
  const actionDict = pdfDoc.context.obj({
@@ -11895,9 +12935,9 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11895
12935
  const targetPage = allPages[clampedIdx];
11896
12936
  const destArr = pdfDoc.context.obj([
11897
12937
  targetPage.ref,
11898
- PDFName2.of("XYZ"),
11899
- PDFNumber2.of(0),
11900
- PDFNumber2.of(targetPage.getHeight()),
12938
+ PDFName3.of("XYZ"),
12939
+ PDFNumber3.of(0),
12940
+ PDFNumber3.of(targetPage.getHeight()),
11901
12941
  null
11902
12942
  ]);
11903
12943
  const actionDict = pdfDoc.context.obj({
@@ -11925,7 +12965,7 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11925
12965
  const actionDict = pdfDoc.context.obj({
11926
12966
  Type: "Action",
11927
12967
  S: "URI",
11928
- URI: PDFString.of(trimmedUrl)
12968
+ URI: PDFString2.of(trimmedUrl)
11929
12969
  });
11930
12970
  const linkAnnot = pdfDoc.context.obj({
11931
12971
  Type: "Annot",
@@ -11938,7 +12978,7 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11938
12978
  } else if (typeof linkItem.linkPageIndex === "number" && linkItem.linkPageIndex >= 0 && allPages.length > 0) {
11939
12979
  const clampedIdx = Math.min(allPages.length - 1, Math.floor(linkItem.linkPageIndex));
11940
12980
  const targetPage = allPages[clampedIdx];
11941
- const destArr = pdfDoc.context.obj([targetPage.ref, PDFName2.of("XYZ"), null, null, null]);
12981
+ const destArr = pdfDoc.context.obj([targetPage.ref, PDFName3.of("XYZ"), null, null, null]);
11942
12982
  const linkAnnot = pdfDoc.context.obj({
11943
12983
  Type: "Annot",
11944
12984
  Subtype: "Link",
@@ -11950,8 +12990,9 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11950
12990
  }
11951
12991
  }
11952
12992
  }
11953
- if (snapshot.metadata?.bookmarks && snapshot.metadata.bookmarks.length > 0) {
11954
- attachPdfOutlinesTree(pdfDoc, snapshot.metadata.bookmarks);
12993
+ const effectiveBookmarks = snapshot.bookmarks ?? snapshot.metadata?.bookmarks;
12994
+ if (effectiveBookmarks && effectiveBookmarks.length > 0) {
12995
+ attachPdfOutlinesTree(pdfDoc, effectiveBookmarks);
11955
12996
  }
11956
12997
  const attachments = snapshot.attachments ?? snapshot.metadata?.attachments ?? [];
11957
12998
  if (attachments.length > 0) {
@@ -11963,28 +13004,28 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11963
13004
  const pieceDict = {};
11964
13005
  if (sigEnv) {
11965
13006
  pieceDict.UniverSignature = {
11966
- LastModified: PDFString.of(sigEnv.signedAt || (/* @__PURE__ */ new Date()).toISOString()),
13007
+ LastModified: PDFString2.of(sigEnv.signedAt || (/* @__PURE__ */ new Date()).toISOString()),
11967
13008
  Private: pdfDoc.context.obj({
11968
- Algorithm: PDFName2.of("SHA-256"),
11969
- Signer: PDFHexString.fromText(sigEnv.signerName),
11970
- CertificateSubject: PDFHexString.fromText(sigEnv.certificateSubject),
11971
- ContentDigest: PDFString.of(sigEnv.contentDigestHex),
11972
- EnvelopeDigest: PDFString.of(sigEnv.envelopeDigestHex)
13009
+ Algorithm: PDFName3.of("SHA-256"),
13010
+ Signer: PDFHexString2.fromText(sigEnv.signerName),
13011
+ CertificateSubject: PDFHexString2.fromText(sigEnv.certificateSubject),
13012
+ ContentDigest: PDFString2.of(sigEnv.contentDigestHex),
13013
+ EnvelopeDigest: PDFString2.of(sigEnv.envelopeDigestHex)
11973
13014
  })
11974
13015
  };
11975
13016
  }
11976
13017
  if (secPerms) {
11977
13018
  pieceDict.UniverSecurity = {
11978
- LastModified: PDFString.of((/* @__PURE__ */ new Date()).toISOString()),
13019
+ LastModified: PDFString2.of((/* @__PURE__ */ new Date()).toISOString()),
11979
13020
  Private: pdfDoc.context.obj({
11980
13021
  AllowPrint: secPerms.allowPrint !== false ? PDFBool.True : PDFBool.False,
11981
13022
  AllowCopy: secPerms.allowCopy !== false ? PDFBool.True : PDFBool.False,
11982
13023
  AllowModify: secPerms.allowModify !== false ? PDFBool.True : PDFBool.False,
11983
- ...secPerms.openPasswordHash ? { OpenPasswordHash: PDFString.of(secPerms.openPasswordHash) } : {}
13024
+ ...secPerms.openPasswordHash ? { OpenPasswordHash: PDFString2.of(secPerms.openPasswordHash) } : {}
11984
13025
  })
11985
13026
  };
11986
13027
  }
11987
- pdfDoc.catalog.set(PDFName2.of("PieceInfo"), pdfDoc.context.obj(pieceDict));
13028
+ pdfDoc.catalog.set(PDFName3.of("PieceInfo"), pdfDoc.context.obj(pieceDict));
11988
13029
  }
11989
13030
  if (accessibilityTagged) {
11990
13031
  attachTaggedStructTreeRoot(pdfDoc, snapshot, taggedStructItems, totalPhysicalPages);
@@ -11995,66 +13036,76 @@ async function exportPdfBytes(snapshot, runtimeData, options) {
11995
13036
  if (interactiveForm && hasAnyAcroWidget) {
11996
13037
  const acroDict = pdfDoc.getForm().acroForm.dict;
11997
13038
  const helv = await ensureAcroHelvetica();
11998
- let drDict = pdfDoc.context.lookupMaybe(acroDict.get(PDFName2.of("DR")), PDFDict2);
13039
+ let drDict = pdfDoc.context.lookupMaybe(acroDict.get(PDFName3.of("DR")), PDFDict3);
11999
13040
  if (!drDict) {
12000
13041
  drDict = pdfDoc.context.obj({});
12001
- acroDict.set(PDFName2.of("DR"), drDict);
13042
+ acroDict.set(PDFName3.of("DR"), drDict);
12002
13043
  }
12003
- let fontDict = pdfDoc.context.lookupMaybe(drDict.get(PDFName2.of("Font")), PDFDict2);
13044
+ let fontDict = pdfDoc.context.lookupMaybe(drDict.get(PDFName3.of("Font")), PDFDict3);
12004
13045
  if (!fontDict) {
12005
13046
  fontDict = pdfDoc.context.obj({});
12006
- drDict.set(PDFName2.of("Font"), fontDict);
13047
+ drDict.set(PDFName3.of("Font"), fontDict);
12007
13048
  }
12008
- fontDict.set(PDFName2.of("Helv"), helv.ref);
13049
+ fontDict.set(PDFName3.of("Helv"), helv.ref);
12009
13050
  if (acroCjkState) {
12010
- fontDict.set(PDFName2.of("FCjk"), acroCjkState.type0FontRef);
13051
+ fontDict.set(PDFName3.of("FCjk"), acroCjkState.type0FontRef);
12011
13052
  }
12012
13053
  acroDict.set(
12013
- PDFName2.of("DA"),
12014
- PDFString.of(acroCjkState ? "/FCjk 11 Tf 0 0 0 rg" : "/Helv 11 Tf 0 0 0 rg")
13054
+ PDFName3.of("DA"),
13055
+ PDFString2.of(acroCjkState ? "/FCjk 11 Tf 0 0 0 rg" : "/Helv 11 Tf 0 0 0 rg")
12015
13056
  );
12016
- acroDict.delete(PDFName2.of("NeedAppearances"));
13057
+ acroDict.delete(PDFName3.of("NeedAppearances"));
12017
13058
  }
12018
13059
  if (optimizeSize) {
12019
13060
  pruneUnreferencedObjectsAndCompressStreams(pdfDoc);
12020
13061
  }
13062
+ const effectiveSecurity = options?.security ?? snapshot.security ?? snapshot.metadata?.security;
13063
+ const shouldEncrypt = isPdfSecurityActive(effectiveSecurity);
12021
13064
  throwIfExportAborted();
13065
+ if (shouldEncrypt && !options?.diagnosticGridOverlay) {
13066
+ await applyPdfSecurityToDocument(pdfDoc, effectiveSecurity);
13067
+ const encryptedSavedBytes = interactiveForm && hasAnyAcroWidget ? await pdfDoc.save({ useObjectStreams: false, updateFieldAppearances: false }) : await pdfDoc.save({ useObjectStreams: false });
13068
+ throwIfExportAborted();
13069
+ return encryptedSavedBytes;
13070
+ }
12022
13071
  const savedPdfBytes = interactiveForm && hasAnyAcroWidget ? await pdfDoc.save({ updateFieldAppearances: false }) : await pdfDoc.save();
12023
13072
  throwIfExportAborted();
12024
13073
  if (options?.diagnosticGridOverlay) {
12025
13074
  const gridOpts = typeof options.diagnosticGridOverlay === "object" ? options.diagnosticGridOverlay : void 0;
12026
- return await overlayDiagnosticGridOnPdfBytes(savedPdfBytes, snapshot, gridOpts);
13075
+ const overlaidBytes = await overlayDiagnosticGridOnPdfBytes(savedPdfBytes, snapshot, gridOpts);
13076
+ return shouldEncrypt ? await encryptPdfBytes(overlaidBytes, effectiveSecurity) : overlaidBytes;
12027
13077
  }
12028
13078
  return savedPdfBytes;
12029
13079
  }
13080
+ var exportPdfUnitToBytes = exportPdfBytes;
12030
13081
  function decodePdfObjAsString(obj) {
12031
13082
  if (!obj) return "";
12032
- if (obj instanceof PDFHexString || obj instanceof PDFString || obj instanceof PDFName2) {
13083
+ if (obj instanceof PDFHexString2 || obj instanceof PDFString2 || obj instanceof PDFName3) {
12033
13084
  return obj.decodeText();
12034
13085
  }
12035
13086
  return "";
12036
13087
  }
12037
13088
  function extractSigDictValue(doc, fieldOrWidgetDict) {
12038
- const metaDict = doc.context.lookupMaybe(fieldOrWidgetDict.get(PDFName2.of("YudaoMeta")), PDFDict2);
13089
+ const metaDict = doc.context.lookupMaybe(fieldOrWidgetDict.get(PDFName3.of("YudaoMeta")), PDFDict3);
12039
13090
  if (metaDict) {
12040
- const dataUri = decodePdfObjAsString(metaDict.get(PDFName2.of("SignatureDataUri")));
13091
+ const dataUri = decodePdfObjAsString(metaDict.get(PDFName3.of("SignatureDataUri")));
12041
13092
  if (dataUri) return dataUri;
12042
- const signer = decodePdfObjAsString(metaDict.get(PDFName2.of("SignerName")));
13093
+ const signer = decodePdfObjAsString(metaDict.get(PDFName3.of("SignerName")));
12043
13094
  if (signer) return signer;
12044
13095
  }
12045
- const vDict = doc.context.lookupMaybe(fieldOrWidgetDict.get(PDFName2.of("V")), PDFDict2);
13096
+ const vDict = doc.context.lookupMaybe(fieldOrWidgetDict.get(PDFName3.of("V")), PDFDict3);
12046
13097
  if (vDict) {
12047
- const signerName = decodePdfObjAsString(vDict.get(PDFName2.of("Name")));
13098
+ const signerName = decodePdfObjAsString(vDict.get(PDFName3.of("Name")));
12048
13099
  if (signerName) return signerName;
12049
- if (vDict.get(PDFName2.of("Contents")) || vDict.get(PDFName2.of("Type"))) {
13100
+ if (vDict.get(PDFName3.of("Contents")) || vDict.get(PDFName3.of("Type"))) {
12050
13101
  return "signed";
12051
13102
  }
12052
13103
  }
12053
- const vStr = decodePdfObjAsString(fieldOrWidgetDict.get(PDFName2.of("V")));
13104
+ const vStr = decodePdfObjAsString(fieldOrWidgetDict.get(PDFName3.of("V")));
12054
13105
  return vStr || "";
12055
13106
  }
12056
13107
  async function extractAcroFormValuesFromPdfBytes(pdfBytes) {
12057
- const doc = await PDFDocument2.load(pdfBytes, { ignoreEncryption: true });
13108
+ const doc = await PDFDocument3.load(pdfBytes, { ignoreEncryption: true });
12058
13109
  const form = doc.getForm();
12059
13110
  const fields = form.getFields();
12060
13111
  const values = {};
@@ -12073,7 +13124,7 @@ async function extractAcroFormValuesFromPdfBytes(pdfBytes) {
12073
13124
  } else if (field instanceof PDFRadioGroup) {
12074
13125
  values[name] = field.getSelected() ?? "";
12075
13126
  } else {
12076
- const ft = decodePdfObjAsString(field.acroField.dict.get(PDFName2.of("FT")));
13127
+ const ft = decodePdfObjAsString(field.acroField.dict.get(PDFName3.of("FT")));
12077
13128
  if (ft === "Sig") {
12078
13129
  values[name] = extractSigDictValue(doc, field.acroField.dict);
12079
13130
  }
@@ -12083,17 +13134,17 @@ async function extractAcroFormValuesFromPdfBytes(pdfBytes) {
12083
13134
  const annots = page.node.Annots();
12084
13135
  if (!annots) continue;
12085
13136
  for (let i = 0; i < annots.size(); i++) {
12086
- const wDict = doc.context.lookupMaybe(annots.get(i), PDFDict2);
13137
+ const wDict = doc.context.lookupMaybe(annots.get(i), PDFDict3);
12087
13138
  if (!wDict) continue;
12088
- if (decodePdfObjAsString(wDict.get(PDFName2.of("Subtype"))) !== "Widget") continue;
12089
- const tName = decodePdfObjAsString(wDict.get(PDFName2.of("T")));
13139
+ if (decodePdfObjAsString(wDict.get(PDFName3.of("Subtype"))) !== "Widget") continue;
13140
+ const tName = decodePdfObjAsString(wDict.get(PDFName3.of("T")));
12090
13141
  if (!tName || Object.prototype.hasOwnProperty.call(values, tName)) continue;
12091
- const ft = decodePdfObjAsString(wDict.get(PDFName2.of("FT")));
13142
+ const ft = decodePdfObjAsString(wDict.get(PDFName3.of("FT")));
12092
13143
  if (ft === "Sig") {
12093
13144
  values[tName] = extractSigDictValue(doc, wDict);
12094
13145
  } else if (ft === "Ch") {
12095
- const vObj = wDict.get(PDFName2.of("V"));
12096
- const vArr = doc.context.lookupMaybe(vObj, PDFArray2);
13146
+ const vObj = wDict.get(PDFName3.of("V"));
13147
+ const vArr = doc.context.lookupMaybe(vObj, PDFArray3);
12097
13148
  if (vArr) {
12098
13149
  const items = [];
12099
13150
  for (let k = 0; k < vArr.size(); k++) {
@@ -12179,14 +13230,18 @@ async function exportBatchPdfBytes(snapshot, records, options) {
12179
13230
  if (records.length === 1) {
12180
13231
  return exportPdfBytes(snapshot, records[0], options);
12181
13232
  }
12182
- const mergedPdf = await PDFDocument2.create();
13233
+ const mergedPdf = await PDFDocument3.create();
12183
13234
  let runningStartPage = Math.max(1, Number(snapshot.metadata?.startPageNumber ?? 1) || 1);
12184
13235
  let runningBatesNumber = Math.max(0, Math.floor(snapshot.metadata?.batesConfig?.startNumber ?? 1));
13236
+ const effectiveSecurity = options?.security ?? snapshot.security ?? snapshot.metadata?.security;
13237
+ const recordOptions = isPdfSecurityActive(effectiveSecurity) ? { ...options ?? {}, security: { enabled: false } } : options;
12185
13238
  for (let i = 0; i < records.length; i++) {
12186
13239
  const recordSnap = {
12187
13240
  ...snapshot,
13241
+ ...isPdfSecurityActive(effectiveSecurity) ? { security: { enabled: false } } : {},
12188
13242
  metadata: {
12189
13243
  ...snapshot.metadata ?? {},
13244
+ ...isPdfSecurityActive(effectiveSecurity) ? { security: { enabled: false } } : {},
12190
13245
  startPageNumber: runningStartPage,
12191
13246
  ...snapshot.metadata?.batesConfig ? {
12192
13247
  batesConfig: {
@@ -12196,8 +13251,8 @@ async function exportBatchPdfBytes(snapshot, records, options) {
12196
13251
  } : {}
12197
13252
  }
12198
13253
  };
12199
- const subBytes = await exportPdfBytes(recordSnap, records[i], options);
12200
- const subDoc = await PDFDocument2.load(subBytes);
13254
+ const subBytes = await exportPdfBytes(recordSnap, records[i], recordOptions);
13255
+ const subDoc = await PDFDocument3.load(subBytes);
12201
13256
  const copiedPages = await mergedPdf.copyPages(subDoc, subDoc.getPageIndices());
12202
13257
  for (const page of copiedPages) {
12203
13258
  mergedPdf.addPage(page);
@@ -12206,11 +13261,15 @@ async function exportBatchPdfBytes(snapshot, records, options) {
12206
13261
  runningStartPage += subPageCount;
12207
13262
  runningBatesNumber += subPageCount;
12208
13263
  }
13264
+ if (isPdfSecurityActive(effectiveSecurity)) {
13265
+ await applyPdfSecurityToDocument(mergedPdf, effectiveSecurity);
13266
+ return await mergedPdf.save({ useObjectStreams: false });
13267
+ }
12209
13268
  return await mergedPdf.save();
12210
13269
  }
12211
13270
  async function exportCalibrationGridPdfBytes(pageSize) {
12212
13271
  const sz = pageSize ?? PDF_PAGE_PRESETS.A4;
12213
- const pdfDoc = await PDFDocument2.create();
13272
+ const pdfDoc = await PDFDocument3.create();
12214
13273
  const page = pdfDoc.addPage([sz.width, sz.height]);
12215
13274
  const fontRegular = await pdfDoc.embedFont(StandardFonts.Helvetica);
12216
13275
  const fontBold = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
@@ -12377,7 +13436,7 @@ async function exportCalibrationGridPdfBytes(pageSize) {
12377
13436
  return await pdfDoc.save();
12378
13437
  }
12379
13438
  async function overlayDiagnosticGridOnPdfBytes(pdfBytes, snapshot, options) {
12380
- const pdfDoc = await PDFDocument2.load(pdfBytes, { ignoreEncryption: true });
13439
+ const pdfDoc = await PDFDocument3.load(pdfBytes, { ignoreEncryption: true });
12381
13440
  const pages = pdfDoc.getPages();
12382
13441
  if (pages.length === 0) {
12383
13442
  return await pdfDoc.save({ updateFieldAppearances: false });
@@ -16257,6 +17316,25 @@ export {
16257
17316
  rotatePdfPagesBytes,
16258
17317
  movePdfPageBytes,
16259
17318
  organizePdfBytes,
17319
+ PdfSecurityError,
17320
+ PDF_PASSWORD_PADDING,
17321
+ md5Bytes,
17322
+ rc4Bytes,
17323
+ bytesToHex,
17324
+ hexToBytes,
17325
+ padPdfPassword,
17326
+ encodePdfPermissionFlags,
17327
+ decodePdfPermissionFlags,
17328
+ isPdfSecurityActive,
17329
+ computeOwnerPasswordValue,
17330
+ computeFileEncryptionKeyFromPadded,
17331
+ computeUserPasswordValue,
17332
+ buildObjectEncryptionKey,
17333
+ applyPdfSecurityToDocument,
17334
+ encryptPdfBytes,
17335
+ inspectPdfEncryption,
17336
+ decryptPdfBytes,
17337
+ verifyAndDecryptPdfBytes,
16260
17338
  parseObjectPositionRatios,
16261
17339
  computeImageFitPlacement,
16262
17340
  computeElementCenterTransformMatrix,
@@ -16287,6 +17365,7 @@ export {
16287
17365
  paginatePdfTableRows,
16288
17366
  formatBatesNumber,
16289
17367
  exportPdfBytes,
17368
+ exportPdfUnitToBytes,
16290
17369
  extractAcroFormValuesFromPdfBytes,
16291
17370
  extractPdfFormValues,
16292
17371
  fillPdfFormValues,
@@ -16337,4 +17416,4 @@ export {
16337
17416
  renderJsxToPdfmeTemplate,
16338
17417
  exportJsxToPdfBytes
16339
17418
  };
16340
- //# sourceMappingURL=chunk-EMSHTYYU.js.map
17419
+ //# sourceMappingURL=chunk-SUXA7HBV.js.map