@file-viewer/renderer-pdf 3.2.0 → 3.2.2
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.
- package/README.en.md +77 -3
- package/README.md +74 -3
- package/dist/pdf.js +47 -79
- package/dist/pdfWorkerCache.d.ts +3 -0
- package/dist/pdfWorkerCache.js +47 -0
- package/dist/pdfWorkerProbe.d.ts +2 -0
- package/dist/pdfWorkerProbe.js +4 -0
- package/package.json +6 -2
package/README.en.md
CHANGED
|
@@ -1,7 +1,81 @@
|
|
|
1
1
|
# @file-viewer/renderer-pdf
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Cold-network loading starts the real Worker directly, without a duplicate version-probe request.
|
|
4
|
+
PDF.js checks API compatibility before parsing. Mismatched workers are destroyed and retried
|
|
5
|
+
with the bundled matching handler without losing transferred input. Main-thread fallbacks
|
|
6
|
+
use asynchronous resource fetching instead of synchronous binary XHR.
|
|
4
7
|
|
|
5
|
-
|
|
8
|
+
Standalone PDF renderer package for Flyfish File Viewer. It is powered by PDF.js and provides page rendering, navigation, outline, search, zoom, print, and HTML export support.
|
|
6
9
|
|
|
7
|
-
|
|
10
|
+
## Usage
|
|
11
|
+
|
|
12
|
+
```ts
|
|
13
|
+
import FileViewer from '@file-viewer/vue3'
|
|
14
|
+
import { pdfRenderer } from '@file-viewer/renderer-pdf'
|
|
15
|
+
|
|
16
|
+
const options = {
|
|
17
|
+
rendererMode: 'replace',
|
|
18
|
+
renderers: pdfRenderer,
|
|
19
|
+
}
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
You can combine it with other renderer packages:
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
const options = {
|
|
26
|
+
rendererMode: 'replace',
|
|
27
|
+
renderers: [pdfRenderer],
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Offline Assets
|
|
32
|
+
|
|
33
|
+
PDF preview depends on the PDF.js worker, cMaps, WASM helpers, standard fonts, and an offline fallback for unembedded CJK fonts. Asset paths use the same unified options as `@file-viewer/core`:
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
const options = {
|
|
37
|
+
renderers: pdfRenderer,
|
|
38
|
+
pdf: {
|
|
39
|
+
assetBaseUrl: '/workspace/',
|
|
40
|
+
workerUrl: '/vendor/pdf/pdf.worker.mjs',
|
|
41
|
+
cMapUrl: '/vendor/pdf/cmaps/',
|
|
42
|
+
wasmUrl: '/vendor/pdf/wasm/',
|
|
43
|
+
standardFontDataUrl: '/vendor/pdf/standard_fonts/',
|
|
44
|
+
cjkFontFallbackPath: '/vendor/pdf/fonts/',
|
|
45
|
+
identityFontRepair: true,
|
|
46
|
+
},
|
|
47
|
+
}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
When no explicit PDF asset URL is configured, the renderer first uses the public base exposed by build tools such as Vite and can fall back to the page entry script. An app deployed under `/workspace/` therefore still requests `/workspace/vendor/pdf/pdf.worker.mjs` while its current SPA route is `/workspace/c/`. UMI, custom proxies, and builds whose public path cannot be detected can set `pdf.assetBaseUrl: '/workspace/'` to pin the base for every PDF offline asset. The real Worker checks API compatibility before parsing. An incompatible Worker is destroyed and retried with the packaged matching handler, without a separate version-probe request. If the host app did not run `file-viewer-copy-assets`, does not use `@file-viewer/vite-plugin`, or a local dev server falls back to HTML for that path, the same fallback prevents `Setting up fake worker failed`. For best performance, complete cMap/standard-font/WASM decoding, or strict offline deployments, still copy viewer assets and point these URLs at real static files. The pinned PDF.js 5.4 stable line loads local JBIG2, JPEG 2000, color-management, and related helpers through `wasmUrl`; viewer assets and the Vite plugin copy them without relying on the public internet.
|
|
51
|
+
|
|
52
|
+
`cjkFontFallback` is enabled by default. When a PDF references `MicrosoftYaHei-Bold`, SimSun, SimHei, or another CJK font without embedding the font program, the renderer prefers an installed system font and otherwise aliases the original PDF font name to the local Noto Sans SC variable font supplied by `@file-viewer/assets-standard`. The Vite plugin reuses that standard asset set instead of packing a second font copy into the renderer. Only WOFF2 shards needed by the current page text are loaded. The first page waits for the font before rendering, and later pages are redrawn when they introduce new glyphs. Set the option to `false` to disable this behavior, or point `cjkFontFallbackPath` at a self-hosted directory with the same structure.
|
|
53
|
+
|
|
54
|
+
`identityFontRepair` is also enabled by default for malformed PDFs that write TrueType glyph IDs through `Identity-H`/`Identity-V` but omit `ToUnicode`. The repair module is loaded only after CJK font substitution and multiple control-character glyphs are detected. If the same PDF embeds a usable same-family TrueType font, its cmap is used to rebuild the Unicode mapping for the in-memory preview. The repair is applied only to a preview copy and never overwrites the original file or download source; an unsafe or unsupported repair falls back to the original preview. Set the option to `false` to disable this compatibility path.
|
|
55
|
+
|
|
56
|
+
## Migration Note
|
|
57
|
+
|
|
58
|
+
PDF rendering has moved out of `@file-viewer/core` into this package, and `pdfjs-dist` is now declared only by `@file-viewer/renderer-pdf`. Installing core or a standard component package no longer pulls PDF.js; explicitly assemble this renderer when PDF preview is needed, or use `@file-viewer/preset-all`.
|
|
59
|
+
|
|
60
|
+
The published renderer stages its Apache-2.0 PDF.js runtime under `dist/vendor/pdfjs` and isolates PDF.js' internal webpack bootstrap before packing. `provenance.json` records source hashes after the declared patches, transform counts, and staged output hashes, so webpack 4 consumers do not need a loader for renderer-internal paths.
|
|
61
|
+
|
|
62
|
+
The staged runtime also includes a PDF.js 5.4.624 document-startup cancellation patch. It prevents unhandled promise rejections when switching files during main-thread fallback initialization; active parsing and password errors remain visible. The patch is included under `dist/vendor/pdfjs/patches/` with its hash in `provenance.json`. `pnpm verify:worker-lifecycle` tests cancellation, subsequent rendering, and invalid-file errors in both real and main-thread Workers on Chromium and WebKit.
|
|
63
|
+
|
|
64
|
+
## Mouse panning
|
|
65
|
+
|
|
66
|
+
`options.pdf.handTool: true` enables mouse drag-to-pan in the PDF viewport. It is
|
|
67
|
+
`false` by default, preserving text selection. Touch scrolling/pinch, links, form
|
|
68
|
+
fields, scrollbars, and modified clicks retain their native behavior.
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
const options = { pdf: { handTool: true } }
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Page orientation and print output
|
|
75
|
+
|
|
76
|
+
A page's stored PDF rotation is combined with the viewer's rotation offset in
|
|
77
|
+
fit calculations, sidebar/first-page thumbnails, exported images, and printing.
|
|
78
|
+
The view-state `rotation` field remains the viewer offset, not the stored page
|
|
79
|
+
rotation. Mixed page sizes and orientations use individual CSS page rules for
|
|
80
|
+
printing; no source PDF bytes are modified. Printer-dialog overrides may still
|
|
81
|
+
force a uniform paper size.
|
package/README.md
CHANGED
|
@@ -1,7 +1,78 @@
|
|
|
1
1
|
# @file-viewer/renderer-pdf
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Flyfish File Viewer 的独立 PDF renderer 包,基于 PDF.js,提供 PDF 页面渲染、导航、目录、搜索、缩放、打印和 HTML 导出能力。
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
## 用法
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
```ts
|
|
8
|
+
import FileViewer from '@file-viewer/vue3'
|
|
9
|
+
import { pdfRenderer } from '@file-viewer/renderer-pdf'
|
|
10
|
+
|
|
11
|
+
const options = {
|
|
12
|
+
rendererMode: 'replace',
|
|
13
|
+
renderers: pdfRenderer,
|
|
14
|
+
}
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
也可以和其他 renderer 一起组合:
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
const options = {
|
|
21
|
+
rendererMode: 'replace',
|
|
22
|
+
renderers: [pdfRenderer],
|
|
23
|
+
}
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## 离线资源
|
|
27
|
+
|
|
28
|
+
PDF 预览依赖 PDF.js worker、cMaps、WASM、standard fonts,以及未嵌入中文字体的离线回退资源。资源路径沿用 `@file-viewer/core` 的统一 options:
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
const options = {
|
|
32
|
+
renderers: pdfRenderer,
|
|
33
|
+
pdf: {
|
|
34
|
+
assetBaseUrl: '/workspace/',
|
|
35
|
+
workerUrl: '/vendor/pdf/pdf.worker.mjs',
|
|
36
|
+
cMapUrl: '/vendor/pdf/cmaps/',
|
|
37
|
+
wasmUrl: '/vendor/pdf/wasm/',
|
|
38
|
+
standardFontDataUrl: '/vendor/pdf/standard_fonts/',
|
|
39
|
+
cjkFontFallbackPath: '/vendor/pdf/fonts/',
|
|
40
|
+
identityFontRepair: true,
|
|
41
|
+
},
|
|
42
|
+
}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
默认未显式配置时,渲染器优先使用 Vite 等构建器提供的公开基址,并可从页面入口脚本回退识别部署子路径。因此应用部署在 `/workspace/`、当前 SPA 路由为 `/workspace/c/` 时,仍会请求 `/workspace/vendor/pdf/pdf.worker.mjs`。UMI、自定义代理或无法自动识别的构建环境可以设置 `pdf.assetBaseUrl: '/workspace/'` 固定全部 PDF 离线资源的基址。真实 Worker 在解析前通过 PDF.js API 握手确认版本;旧版本不匹配时会被销毁,并安全重试包内同版本 handler,不额外发送版本探测请求。项目未执行 `file-viewer-copy-assets`、未使用 `@file-viewer/vite-plugin`,或本地临时服务器把该路径回退成 HTML 时,也会使用同一兜底,避免 `Setting up fake worker failed` 直接中断预览。需要最佳性能、完整 cMap/standard fonts/WASM 解码或严格离线部署时,仍建议复制 viewer assets 并配置真实静态地址。当前锁定的 PDF.js 5.4 稳定线会通过 `wasmUrl` 本地加载 JBIG2、JPEG 2000、颜色管理等辅助资源;这些资源由 viewer assets 和 Vite 插件统一复制,不依赖公网。
|
|
46
|
+
|
|
47
|
+
`cjkFontFallback` 默认开启。PDF 引用了 `MicrosoftYaHei-Bold`、宋体、黑体或其他中文字体但没有嵌入字体数据时,渲染器优先使用本机字体;本机缺失时,会把原 PDF 字体名映射到 `@file-viewer/assets-standard` 提供的本地 Noto Sans SC 可变字体,并根据当前页实际文字只加载需要的 WOFF2 分片。Vite 插件会优先复用这份标准资源,避免在 renderer 中重复打包字体。首屏会在字体就绪后再渲染,后续页发现新字形时会自动重绘。可设为 `false` 完全关闭,或用 `cjkFontFallbackPath` 指向同结构的自托管字体目录。
|
|
48
|
+
|
|
49
|
+
`identityFontRepair` 也默认开启,用于少数把 TrueType 字形 ID 写入 `Identity-H`/`Identity-V`、却遗漏 `ToUnicode` 的异常 PDF。只有检测到中文字体替换和多个控制字符乱码时,渲染器才会懒加载修复模块;若文件内同时嵌入了可用的同族 TrueType 字体,就从其 cmap 重建内存预览所需的 Unicode 映射。修复只作用于预览副本,不覆盖原始文件和下载源;无法安全修复时继续使用原预览。可设为 `false` 关闭。
|
|
50
|
+
|
|
51
|
+
## 迁移说明
|
|
52
|
+
|
|
53
|
+
直接启动真实 Worker,不再额外读取版本前缀或重复下载 Worker。
|
|
54
|
+
PDF.js 在解析前通过 API 握手检查版本;不匹配时销毁旧 Worker,并用保留的输入安全重试包内同版本回退。
|
|
55
|
+
主线程回退使用异步资源读取,不依赖窗口中不允许的同步二进制 XHR。
|
|
56
|
+
|
|
57
|
+
PDF 渲染已经从 `@file-viewer/core` 移入本包,`pdfjs-dist` 只由 `@file-viewer/renderer-pdf` 声明。只安装 core 或标准组件包时不会再拉取 PDF.js;需要 PDF 预览时请显式装配本 renderer,或使用 `@file-viewer/preset-all`。
|
|
58
|
+
|
|
59
|
+
发布产物会把 Apache-2.0 的 PDF.js runtime 内封到 `dist/vendor/pdfjs`,并在打包前隔离 PDF.js 内部 webpack bootstrap。`provenance.json` 会记录应用声明补丁后的源文件哈希、变换次数和产物哈希,因此 webpack 4 消费项目不需要再为 renderer 内部路径配置 loader。
|
|
60
|
+
|
|
61
|
+
内封运行时还包含 PDF.js 5.4.624 的文档初始化取消补丁,避免快速切换文件时主线程降级路径产生未处理的 Promise 异常;正常解析和密码错误仍会报告。补丁原文保留在 `dist/vendor/pdfjs/patches/`,其哈希记入 `provenance.json`。`pnpm verify:worker-lifecycle` 使用 Chromium/WebKit 分别验证真实 Worker 和主线程降级路径的取消、后续渲染及损坏文件报错。
|
|
62
|
+
|
|
63
|
+
## 鼠标拖拽浏览
|
|
64
|
+
|
|
65
|
+
设置 `options.pdf.handTool: true`,可在 PDF 阅读区按住鼠标左键拖动页面。默认关闭,
|
|
66
|
+
保留原有文字选择行为。触摸滚动与双指缩放、链接、表单控件、滚动条及带修饰键的操作
|
|
67
|
+
保持原生行为。
|
|
68
|
+
|
|
69
|
+
```ts
|
|
70
|
+
const options = { pdf: { handTool: true } }
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## 页面方向与打印
|
|
74
|
+
|
|
75
|
+
适配缩放、侧栏和首页缩略图、导出图片及打印均叠加 PDF 页面原有旋转角度
|
|
76
|
+
与查看器旋转偏移。视图状态中的 `rotation` 仍表示查看器偏移,不包含文件
|
|
77
|
+
中的原始旋转。混合尺寸和方向的页面使用独立 CSS 页面规则打印,不改写
|
|
78
|
+
源 PDF。打印对话框的纸张覆盖设置仍可能强制统一尺寸。
|
package/dist/pdf.js
CHANGED
|
@@ -10,7 +10,8 @@ import { PDF_FIT_HORIZONTAL_PADDING, PDF_PAGE_BORDER_WIDTH, resolvePdfFitViewpor
|
|
|
10
10
|
import { createPdfBoundingBoxController, } from './pdfBboxController.js';
|
|
11
11
|
import { clampPdfScale, normalizePdfRotation, resolvePdfPageRotation, resolvePdfViewStateUpdate, } from './pdfViewState.js';
|
|
12
12
|
import { capturePdfJsWorkerGlobal, scopePdfJsWorkerMessageHandler, } from './pdfWorkerGlobal.js';
|
|
13
|
-
import {
|
|
13
|
+
import { hasNativePdfWorkerPort, isPdfWorkerVersionMismatch } from './pdfWorkerProbe.js';
|
|
14
|
+
import { scopePdfJsWorkerHandlerCache } from './pdfWorkerCache.js';
|
|
14
15
|
import { getFileViewerPdfIdentityFontRepair } from './optionalCapabilities.js';
|
|
15
16
|
import { isExpectedPdfJsDestroyConsoleError } from './pdfConsoleLifecycle.js';
|
|
16
17
|
export const DEFAULT_FILE_VIEWER_PDF_WORKER_URL = DEFAULT_FILE_VIEWER_PDF_WORKER_PATH;
|
|
@@ -18,8 +19,6 @@ const MIN_SCALE = 0.2;
|
|
|
18
19
|
const MAX_SCALE = 3;
|
|
19
20
|
const SCALE_STEP = 0.1;
|
|
20
21
|
const PDF_EXPORT_MAX_PAGE_PIXELS = 8000000;
|
|
21
|
-
const PDF_WORKER_PROBE_TIMEOUT_MS = 1200;
|
|
22
|
-
const PDF_WORKER_VERSION_PROBE_BYTES = 4096;
|
|
23
22
|
const PDF_JS_DESTROY_CONSOLE_SUPPRESSION_MS = 1500;
|
|
24
23
|
let bundledPdfWorkerModulePromise = null;
|
|
25
24
|
const scopePdfJsRootVariables = (style) => style.replace(/:root(\s*\{)/g, ':root,\n.pdf-shell$1');
|
|
@@ -221,18 +220,6 @@ const suppressPdfJsMissingSystemFontWarnings = (view) => {
|
|
|
221
220
|
const isConfiguredUrl = (value) => {
|
|
222
221
|
return value !== undefined && value !== null && String(value).trim().length > 0;
|
|
223
222
|
};
|
|
224
|
-
const isJavaScriptLikeResponse = (response) => {
|
|
225
|
-
var _a;
|
|
226
|
-
const contentType = ((_a = response.headers.get('content-type')) === null || _a === void 0 ? void 0 : _a.toLowerCase()) || '';
|
|
227
|
-
return !contentType ||
|
|
228
|
-
contentType.includes('javascript') ||
|
|
229
|
-
contentType.includes('ecmascript') ||
|
|
230
|
-
contentType.includes('application/octet-stream') ||
|
|
231
|
-
contentType.includes('text/plain');
|
|
232
|
-
};
|
|
233
|
-
const readResponsePrefix = async (response, maximumBytes = PDF_WORKER_VERSION_PROBE_BYTES) => {
|
|
234
|
-
return (await response.text()).slice(0, maximumBytes);
|
|
235
|
-
};
|
|
236
223
|
const loadBundledPdfWorkerModule = async () => {
|
|
237
224
|
bundledPdfWorkerModulePromise !== null && bundledPdfWorkerModulePromise !== void 0 ? bundledPdfWorkerModulePromise : (bundledPdfWorkerModulePromise = import('./vendor/pdfjs/legacy/build/pdf.worker.mjs'));
|
|
238
225
|
return bundledPdfWorkerModulePromise;
|
|
@@ -242,7 +229,9 @@ const createBundledPdfFakeWorker = async () => {
|
|
|
242
229
|
const hostWorkerGlobal = capturePdfJsWorkerGlobal(workerGlobal);
|
|
243
230
|
const workerModule = await loadBundledPdfWorkerModule();
|
|
244
231
|
const workerHandlerScope = scopePdfJsWorkerMessageHandler(workerGlobal, workerModule.WorkerMessageHandler, hostWorkerGlobal);
|
|
232
|
+
let workerCacheScope;
|
|
245
233
|
try {
|
|
234
|
+
workerCacheScope = scopePdfJsWorkerHandlerCache(PdfJsWorker, workerModule.WorkerMessageHandler);
|
|
246
235
|
const worker = new PdfJsWorker({
|
|
247
236
|
name: 'file-viewer-pdf-worker',
|
|
248
237
|
});
|
|
@@ -250,7 +239,12 @@ const createBundledPdfFakeWorker = async () => {
|
|
|
250
239
|
return worker;
|
|
251
240
|
}
|
|
252
241
|
finally {
|
|
253
|
-
|
|
242
|
+
try {
|
|
243
|
+
workerCacheScope === null || workerCacheScope === void 0 ? void 0 : workerCacheScope.restore();
|
|
244
|
+
}
|
|
245
|
+
finally {
|
|
246
|
+
workerHandlerScope.restore();
|
|
247
|
+
}
|
|
254
248
|
}
|
|
255
249
|
};
|
|
256
250
|
const resolvePdfWorkerUrl = (options, documentBaseUrl) => {
|
|
@@ -312,6 +306,7 @@ export default async function renderPdf(buffer, target, context) {
|
|
|
312
306
|
let fitFrame = 0;
|
|
313
307
|
let pageDimensionFrame = 0;
|
|
314
308
|
let destroyed = false;
|
|
309
|
+
const unverifiedWorkers = new WeakSet();
|
|
315
310
|
let loadVersion = 0;
|
|
316
311
|
let viewStateApplyVersion = 0;
|
|
317
312
|
let activeViewStateApplyVersion = 0;
|
|
@@ -713,52 +708,6 @@ export default async function renderPdf(buffer, target, context) {
|
|
|
713
708
|
targetWindow.requestAnimationFrame(writeLegacyCompatiblePageDimensions);
|
|
714
709
|
});
|
|
715
710
|
};
|
|
716
|
-
const probeResolvedPdfWorkerUrl = async (workerUrl) => {
|
|
717
|
-
var _a, _b;
|
|
718
|
-
const fetcher = ((_a = targetWindow.fetch) === null || _a === void 0 ? void 0 : _a.bind(targetWindow)) || ((_b = globalThis.fetch) === null || _b === void 0 ? void 0 : _b.bind(globalThis));
|
|
719
|
-
const AbortControllerCtor = targetWindow.AbortController || globalThis.AbortController;
|
|
720
|
-
if (!fetcher || !AbortControllerCtor) {
|
|
721
|
-
return { status: 'unavailable', workerVersion: null };
|
|
722
|
-
}
|
|
723
|
-
try {
|
|
724
|
-
const parsed = new URL(workerUrl, documentRef.baseURI || targetWindow.location.href);
|
|
725
|
-
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
726
|
-
return { status: 'unavailable', workerVersion: null };
|
|
727
|
-
}
|
|
728
|
-
}
|
|
729
|
-
catch {
|
|
730
|
-
return { status: 'unavailable', workerVersion: null };
|
|
731
|
-
}
|
|
732
|
-
const controller = new AbortControllerCtor();
|
|
733
|
-
const timer = targetWindow.setTimeout(() => controller.abort(), PDF_WORKER_PROBE_TIMEOUT_MS);
|
|
734
|
-
try {
|
|
735
|
-
const response = await fetcher(workerUrl, {
|
|
736
|
-
method: 'GET',
|
|
737
|
-
cache: 'no-store',
|
|
738
|
-
headers: {
|
|
739
|
-
Range: `bytes=0-${PDF_WORKER_VERSION_PROBE_BYTES - 1}`,
|
|
740
|
-
},
|
|
741
|
-
signal: controller.signal,
|
|
742
|
-
});
|
|
743
|
-
if ((!response.ok && response.status !== 206) || !isJavaScriptLikeResponse(response)) {
|
|
744
|
-
return { status: 'unavailable', workerVersion: null };
|
|
745
|
-
}
|
|
746
|
-
const workerVersion = readPdfJsWorkerVersion(await readResponsePrefix(response));
|
|
747
|
-
if (!workerVersion) {
|
|
748
|
-
return { status: 'unknown', workerVersion: null };
|
|
749
|
-
}
|
|
750
|
-
return {
|
|
751
|
-
status: workerVersion === pdfJsVersion ? 'compatible' : 'incompatible',
|
|
752
|
-
workerVersion,
|
|
753
|
-
};
|
|
754
|
-
}
|
|
755
|
-
catch {
|
|
756
|
-
return { status: 'unavailable', workerVersion: null };
|
|
757
|
-
}
|
|
758
|
-
finally {
|
|
759
|
-
targetWindow.clearTimeout(timer);
|
|
760
|
-
}
|
|
761
|
-
};
|
|
762
711
|
const createPdfWorker = async () => {
|
|
763
712
|
var _a;
|
|
764
713
|
const workerUrl = resolvePdfWorkerUrl(options, pdfRuntimeAssetBaseUrl);
|
|
@@ -771,23 +720,14 @@ export default async function renderPdf(buffer, target, context) {
|
|
|
771
720
|
console.warn('[file-viewer] PDF.js 全局 Worker handler 隔离失败,继续探测静态 Worker。', error);
|
|
772
721
|
}
|
|
773
722
|
}
|
|
774
|
-
|
|
775
|
-
const workerProbe = (targetWindow === null || targetWindow === void 0 ? void 0 : targetWindow.Worker)
|
|
776
|
-
? await probeResolvedPdfWorkerUrl(workerUrl)
|
|
777
|
-
: { status: 'unavailable', workerVersion: null };
|
|
778
|
-
if (workerProbe.status === 'incompatible') {
|
|
779
|
-
console.warn(`[file-viewer] PDF Worker ${workerProbe.workerVersion} 与 PDF.js API ${pdfJsVersion} 不匹配,` +
|
|
780
|
-
'改用包内同版本 PDF.js handler。');
|
|
781
|
-
}
|
|
782
|
-
const shouldUseRealWorker = !!(targetWindow === null || targetWindow === void 0 ? void 0 : targetWindow.Worker) && (workerProbe.status === 'compatible' ||
|
|
783
|
-
(hasExplicitWorkerUrl && workerProbe.status === 'unknown'));
|
|
784
|
-
if (shouldUseRealWorker) {
|
|
723
|
+
if (targetWindow.Worker) {
|
|
785
724
|
GlobalWorkerOptions.workerSrc = workerUrl;
|
|
786
725
|
try {
|
|
787
726
|
const worker = new PdfJsWorker({
|
|
788
727
|
name: 'file-viewer-pdf-worker',
|
|
789
728
|
});
|
|
790
729
|
await worker.promise;
|
|
730
|
+
unverifiedWorkers.add(worker);
|
|
791
731
|
return worker;
|
|
792
732
|
}
|
|
793
733
|
catch (error) {
|
|
@@ -1826,24 +1766,52 @@ export default async function renderPdf(buffer, target, context) {
|
|
|
1826
1766
|
: {
|
|
1827
1767
|
data: buffer,
|
|
1828
1768
|
};
|
|
1829
|
-
const createLoadingResource = async (loadingSource) => {
|
|
1830
|
-
const worker = await createPdfWorker();
|
|
1769
|
+
const createLoadingResource = async (loadingSource, bundledFallback = false) => {
|
|
1770
|
+
const worker = bundledFallback ? await createBundledPdfFakeWorker() : await createPdfWorker();
|
|
1771
|
+
const fallbackSource = worker && unverifiedWorkers.has(worker)
|
|
1772
|
+
? ('data' in loadingSource ? { data: loadingSource.data.slice(0) } : loadingSource)
|
|
1773
|
+
: undefined;
|
|
1831
1774
|
const loadingTask = getDocument({
|
|
1832
1775
|
...loadingSource,
|
|
1833
1776
|
worker: worker || undefined,
|
|
1834
1777
|
cMapUrl: pdfAssets.cMapUrl,
|
|
1835
1778
|
wasmUrl: pdfAssets.wasmUrl,
|
|
1836
1779
|
standardFontDataUrl: pdfAssets.standardFontDataUrl,
|
|
1837
|
-
useWorkerFetch:
|
|
1780
|
+
useWorkerFetch: hasNativePdfWorkerPort(worker === null || worker === void 0 ? void 0 : worker.port, [globalThis.Worker, targetWindow.Worker]),
|
|
1838
1781
|
cMapPacked: true,
|
|
1839
1782
|
enableXfa: true,
|
|
1840
1783
|
fontExtraProperties: fontInspectionEnabled,
|
|
1841
1784
|
});
|
|
1842
|
-
return { loadingTask, worker };
|
|
1785
|
+
return { loadingTask, worker, fallbackSource };
|
|
1786
|
+
};
|
|
1787
|
+
const resolveLoadingDocument = async (currentResource) => {
|
|
1788
|
+
try {
|
|
1789
|
+
return await currentResource.loadingTask.promise;
|
|
1790
|
+
}
|
|
1791
|
+
catch (error) {
|
|
1792
|
+
const retrySource = currentResource.fallbackSource;
|
|
1793
|
+
if (!retrySource || !isPdfWorkerVersionMismatch(error, pdfJsVersion) ||
|
|
1794
|
+
destroyed || requestVersion !== loadVersion)
|
|
1795
|
+
throw error;
|
|
1796
|
+
console.warn(`[file-viewer] PDF Worker 版本不匹配,改用包内同版本 PDF.js ${pdfJsVersion}。`);
|
|
1797
|
+
await destroyPdfResource(currentResource);
|
|
1798
|
+
if (destroyed || requestVersion !== loadVersion)
|
|
1799
|
+
throw error;
|
|
1800
|
+
const replacement = await createLoadingResource(retrySource, true);
|
|
1801
|
+
Object.assign(currentResource, replacement);
|
|
1802
|
+
if (destroyed || requestVersion !== loadVersion) {
|
|
1803
|
+
await destroyPdfResource(currentResource);
|
|
1804
|
+
throw error;
|
|
1805
|
+
}
|
|
1806
|
+
return await currentResource.loadingTask.promise;
|
|
1807
|
+
}
|
|
1808
|
+
finally {
|
|
1809
|
+
delete currentResource.fallbackSource;
|
|
1810
|
+
}
|
|
1843
1811
|
};
|
|
1844
1812
|
resource = await createLoadingResource(source);
|
|
1845
1813
|
pdfContext.resource = resource;
|
|
1846
|
-
let pdfDocument = await resource
|
|
1814
|
+
let pdfDocument = await resolveLoadingDocument(resource);
|
|
1847
1815
|
if (destroyed || requestVersion !== loadVersion || pdfContext.resource !== resource) {
|
|
1848
1816
|
if (pdfContext.resource === resource) {
|
|
1849
1817
|
pdfContext.resource = null;
|
|
@@ -1887,7 +1855,7 @@ export default async function renderPdf(buffer, target, context) {
|
|
|
1887
1855
|
if (repaired.repairedFonts > 0) {
|
|
1888
1856
|
const previousResource = resource;
|
|
1889
1857
|
replacementResource = await createLoadingResource({ data: repaired.bytes });
|
|
1890
|
-
const replacementDocument = await replacementResource
|
|
1858
|
+
const replacementDocument = await resolveLoadingDocument(replacementResource);
|
|
1891
1859
|
const repairedFirstPage = await replacementDocument.getPage(1);
|
|
1892
1860
|
const replacementTextContent = await repairedFirstPage.getTextContent();
|
|
1893
1861
|
if (destroyed ||
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
const workerHandlerScopes = new WeakMap();
|
|
2
|
+
const cacheProperty = '_setupFakeWorkerGlobal';
|
|
3
|
+
export const scopePdfJsWorkerHandlerCache = (workerClass, handler) => {
|
|
4
|
+
var _a;
|
|
5
|
+
const current = Object.getOwnPropertyDescriptor(workerClass, cacheProperty);
|
|
6
|
+
let scope = workerHandlerScopes.get(workerClass);
|
|
7
|
+
if (!scope || scope.handler !== handler || (current === null || current === void 0 ? void 0 : current.value) !== scope.promise) {
|
|
8
|
+
const promise = Promise.resolve(handler);
|
|
9
|
+
const enumerable = (_a = current === null || current === void 0 ? void 0 : current.enumerable) !== null && _a !== void 0 ? _a : true;
|
|
10
|
+
Object.defineProperty(workerClass, cacheProperty, {
|
|
11
|
+
value: promise,
|
|
12
|
+
configurable: true,
|
|
13
|
+
writable: true,
|
|
14
|
+
enumerable,
|
|
15
|
+
});
|
|
16
|
+
scope = { handler, promise, previous: current, enumerable, users: 0 };
|
|
17
|
+
workerHandlerScopes.set(workerClass, scope);
|
|
18
|
+
}
|
|
19
|
+
const ownedScope = scope;
|
|
20
|
+
ownedScope.users += 1;
|
|
21
|
+
let released = false;
|
|
22
|
+
return {
|
|
23
|
+
restore: () => {
|
|
24
|
+
if (released)
|
|
25
|
+
return false;
|
|
26
|
+
released = true;
|
|
27
|
+
ownedScope.users -= 1;
|
|
28
|
+
if (ownedScope.users > 0)
|
|
29
|
+
return false;
|
|
30
|
+
if (workerHandlerScopes.get(workerClass) === ownedScope) {
|
|
31
|
+
workerHandlerScopes.delete(workerClass);
|
|
32
|
+
}
|
|
33
|
+
const installed = Object.getOwnPropertyDescriptor(workerClass, cacheProperty);
|
|
34
|
+
if ((installed === null || installed === void 0 ? void 0 : installed.value) !== ownedScope.promise ||
|
|
35
|
+
installed.configurable !== true || installed.writable !== true ||
|
|
36
|
+
installed.enumerable !== ownedScope.enumerable)
|
|
37
|
+
return false;
|
|
38
|
+
if (ownedScope.previous) {
|
|
39
|
+
Object.defineProperty(workerClass, cacheProperty, ownedScope.previous);
|
|
40
|
+
}
|
|
41
|
+
else {
|
|
42
|
+
Reflect.deleteProperty(workerClass, cacheProperty);
|
|
43
|
+
}
|
|
44
|
+
return true;
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export const isPdfWorkerVersionMismatch = (error, apiVersion) => typeof error === 'object' && error !== null && 'message' in error &&
|
|
2
|
+
typeof error.message === 'string' &&
|
|
3
|
+
error.message.startsWith(`The API version "${apiVersion}" does not match the Worker version "`);
|
|
4
|
+
export const hasNativePdfWorkerPort = (port, constructors) => constructors.some(WorkerClass => typeof WorkerClass === 'function' && port instanceof WorkerClass);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@file-viewer/renderer-pdf",
|
|
3
|
-
"version": "3.2.
|
|
3
|
+
"version": "3.2.2",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Standalone PDF renderer plugin for File Viewer powered by PDF.js.",
|
|
@@ -80,8 +80,12 @@
|
|
|
80
80
|
"dist/pdfStyles.js",
|
|
81
81
|
"dist/pdfViewState.d.ts",
|
|
82
82
|
"dist/pdfViewState.js",
|
|
83
|
+
"dist/pdfWorkerCache.d.ts",
|
|
84
|
+
"dist/pdfWorkerCache.js",
|
|
83
85
|
"dist/pdfWorkerGlobal.d.ts",
|
|
84
86
|
"dist/pdfWorkerGlobal.js",
|
|
87
|
+
"dist/pdfWorkerProbe.d.ts",
|
|
88
|
+
"dist/pdfWorkerProbe.js",
|
|
85
89
|
"dist/pdfWorkerVersion.d.ts",
|
|
86
90
|
"dist/pdfWorkerVersion.js",
|
|
87
91
|
"dist/vendor/pdfjs/cmaps/78-EUC-H.bcmap",
|
|
@@ -291,7 +295,7 @@
|
|
|
291
295
|
"README.md"
|
|
292
296
|
],
|
|
293
297
|
"dependencies": {
|
|
294
|
-
"@file-viewer/core": "3.2.
|
|
298
|
+
"@file-viewer/core": "3.2.2",
|
|
295
299
|
"@fontsource-variable/noto-sans-sc": "5.3.0"
|
|
296
300
|
},
|
|
297
301
|
"peerDependencies": {
|