pdfJsCMapsPlugin.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { readFile, readdir } from "node:fs/promises";
  2. import { createRequire } from "node:module";
  3. import { basename, dirname, join } from "node:path";
  4. import type { Plugin } from "vite";
  5. const require = createRequire(import.meta.url);
  6. const PDFJS_CMAP_OUTPUT_DIRECTORY = "pdfjs/cmaps";
  7. export interface PdfJsCMapAsset {
  8. fileName: string;
  9. source: Uint8Array;
  10. }
  11. export function resolvePdfJsCMapsDirectory(): string {
  12. return join(dirname(require.resolve("pdfjs-dist/package.json")), "cmaps");
  13. }
  14. export async function listPdfJsCMapAssets(): Promise<PdfJsCMapAsset[]> {
  15. const cMapsDirectory = resolvePdfJsCMapsDirectory();
  16. const entries = await readdir(cMapsDirectory, { withFileTypes: true });
  17. return Promise.all(
  18. entries
  19. .filter((entry) => entry.isFile() && entry.name.endsWith(".bcmap"))
  20. .map(async (entry) => ({
  21. fileName: `${PDFJS_CMAP_OUTPUT_DIRECTORY}/${entry.name}`,
  22. source: await readFile(join(cMapsDirectory, entry.name)),
  23. })),
  24. );
  25. }
  26. export function pdfJsCMapsPlugin(): Plugin {
  27. return {
  28. name: "zcode:pdfjs-cmaps",
  29. async buildStart() {
  30. for (const asset of await listPdfJsCMapAssets()) {
  31. this.emitFile({
  32. type: "asset",
  33. fileName: asset.fileName,
  34. source: asset.source,
  35. });
  36. }
  37. },
  38. configureServer(server) {
  39. const cMapsDirectory = resolvePdfJsCMapsDirectory();
  40. server.middlewares.use((request, response, next) => {
  41. const requestPath = request.url?.split("?", 1)[0] ?? "";
  42. const marker = `/${PDFJS_CMAP_OUTPUT_DIRECTORY}/`;
  43. const markerIndex = requestPath.indexOf(marker);
  44. if (markerIndex < 0) {
  45. next();
  46. return;
  47. }
  48. const fileName = requestPath.slice(markerIndex + marker.length);
  49. if (
  50. fileName.length === 0 ||
  51. fileName !== basename(fileName) ||
  52. !fileName.endsWith(".bcmap")
  53. ) {
  54. next();
  55. return;
  56. }
  57. // PDF.js 不会把预定义 CMap 打进 worker;ReportLab 的 STSong-Light
  58. // 又只引用 UniGB-UCS2-H 而不嵌入映射。开发态必须与生产构建一样提供本地 CMap,
  59. // 否则浏览器原生预览正常,但应用内 PDF.js 会直接丢失整段中文。
  60. readFile(join(cMapsDirectory, fileName))
  61. .then((source) => {
  62. response.statusCode = 200;
  63. response.setHeader("Content-Type", "application/octet-stream");
  64. response.end(source);
  65. })
  66. .catch((error: unknown) => {
  67. next(error);
  68. });
  69. });
  70. },
  71. };
  72. }