PdfViewer.vue 30.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
<!--
 * @Date: 2025-01-21
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-10-22 14:11:50
 * @FilePath: /mlaj/src/components/ui/PdfViewer.vue
 * @Description: PDF预览组件 - 使用pdf-vue3库
-->
<template>
    <van-popup v-if="show" :show="show" @update:show="emit('update:show', $event)" position="right"
        :style="{ height: '100%', width: '100%' }">
        <div class="pdf-viewer-container">
            <!-- PDF内容区域 -->
            <div id="pdf-content" class="pdf-content" :class="{ 'pdf-no-select': preventSave }">
                <PDF v-if="url && show && !loadingError"
                    ref="pdfRef"
                    :src="url"
                    :showProgress="true"
                    :progressColor="'#1989fa'"
                    :showPageTooltip="true"
                    :showBackToTopBtn="false"
                    :scrollThreshold="300"
                    :pdfWidth="`${Math.round(100 * zoomLevel)}%`"
                    :rowGap="8"
                    :page="currentPage"
                    :cMapUrl="'https://unpkg.com/pdfjs-dist@3.7.107/cmaps/'"
                    :withCredentials="false"
                    :useSystemFonts="true"
                    :stopAtErrors="false"
                    :disableFontFace="false"
                    :disableRange="false"
                    :disableStream="false"
                    :disableAutoFetch="false"
                    @onProgress="handleProgress"
                    @onComplete="handleComplete"
                    @onScroll="handleScroll"
                    @onPageChange="handlePageChange"
                    @onPdfInit="handlePdfInit"
                    @onError="handlePdfError" />

                <!-- 错误状态显示 -->
                <div v-if="loadingError" class="error-container">
                    <div class="error-content">
                        <van-icon name="warning-o" size="48" color="#ff4444" />
                        <div class="error-title">加载失败</div>
                        <div class="error-message">{{ errorMessage }}</div>
                        <van-button type="primary" size="small" @click="retryLoad" class="retry-btn">
                            重新加载
                        </van-button>
                    </div>
                </div>
            </div>

            <!-- 已移除顶部关闭按钮,关闭功能迁移至控制栏 -->

            <!-- 缩放控制按钮 -->
            <div 
                v-if="!loading && !loadingError" 
                class="zoom-controls"
                :class="{ 'dragging': isDragging }"
                :style="{ bottom: controlsY + 'px' }"
                @mousedown="handleDragStart"
                @touchstart="handleTouchStart"
                @touchmove="handleTouchMove"
                @touchend="handleTouchEnd"
            >
                <van-button class="zoom-btn zoom-close-btn" type="default" icon="cross" round @click="handleClose" />
                <!-- <van-button class="zoom-btn zoom-in-btn" type="default" icon="plus" round @click="zoomIn" /> -->
                <font-awesome-icon icon="magnifying-glass-plus" class="text-2xl text-gray-600 ml-2 mr-2" @click="zoomIn" />
                <div class="page-jump" @click="focusPageInput">
                    <span class="page-display">{{ currentPage }} / {{ totalPages || 0 }}</span>
                    <input
                        ref="pageInputRef"
                        class="page-input"
                        type="number"
                        :min="1"
                        :max="totalPages || 1"
                        v-model="pageInput"
                        @blur="handlePageInputBlur"
                        @keyup.enter="handlePageInputBlur"
                        v-show="isEditingPage"
                    />
                </div>
                <!-- <van-button class="zoom-btn zoom-out-btn" type="default" icon="minus" round @click="zoomOut" /> -->
                <font-awesome-icon icon="magnifying-glass-minus" class="text-2xl text-gray-600 ml-2 mr-2" @click="zoomOut" />
                <van-button class="zoom-btn zoom-reset-btn" type="default" round @click="resetZoom">
                    <van-icon name="replay" size="16" />
                </van-button>
            </div>

            <!-- 加载遮罩 -->
            <van-overlay :show="loading && !loadingError">
                <div class="wrapper" @click.stop>
                    <div class="loading-content">
                        <!-- 进度环形图 -->
                        <div class="progress-circle">
                            <div class="progress-percent">{{ loadingProgress }}%</div>
                        </div>

                        <!-- 加载文字 -->
                        <div class="loading-text">
                            <div class="loading-title">{{ title }}</div>
                            <div class="loading-subtitle">
                                {{ loadingProgress < 10 ? '正在连接服务器...' : loadingProgress < 50 ? '正在下载文件...' :
                                    loadingProgress < 90 ? '正在解析文档...' : '即将完成...' }} </div>
                            </div>
                        </div>
                    </div>
            </van-overlay>
        </div>
    </van-popup>
</template>

<script setup>
import { ref, watch, nextTick, onUnmounted } from 'vue';
import PDF from "pdf-vue3";

/**
 * 组件属性定义
 */
const props = defineProps({
    // 是否显示弹窗
    show: {
        type: Boolean,
        default: false
    },
    // PDF文件URL
    url: {
        type: String,
        default: ''
    },
    // PDF标题
    title: {
        type: String,
        default: ''
    },
    // 是否防止保存(禁用右键、长按等)
    preventSave: {
        type: Boolean,
        default: true
    }
});

/**
 * 事件定义
 */
const emit = defineEmits(['update:show', 'onLoad', 'onProgress', 'onComplete', 'onClose', 'onDestroy']);

// 响应式数据
const loading = ref(true);
const loadingProgress = ref(0);
const loadingError = ref(false);
const errorMessage = ref('');
const zoomLevel = ref(1); // 缩放级别,1为100%
const scrollPosition = ref({ x: 0, y: 0 }); // 记录滚动位置
const pdfRef = ref(null); // PDF组件引用

// 页码控制
const currentPage = ref(1);
const totalPages = ref(0);
const pageInput = ref('');
const isEditingPage = ref(false);
const pageInputRef = ref(null);

// 拖动控制相关变量
const isDragging = ref(false); // 是否正在拖动
const dragStartY = ref(0); // 拖动开始时的Y坐标
const controlsY = ref(20); // 控制栏距离底部的距离(px)
const dragOffset = ref(0); // 拖动偏移量
const initialControlsY = ref(20); // 拖动开始时控制栏的初始位置
const dragThreshold = 5; // 拖动阈值,超过这个距离才认为是拖动

/**
 * 处理页码输入框失焦事件
 */
const handlePageInputBlur = () => {
    const inputValue = parseInt(pageInput.value);
    if (!isNaN(inputValue)) {
        const validPage = Math.max(1, Math.min(inputValue, totalPages.value || 1));
        currentPage.value = validPage;
    }
    pageInput.value = '';
    isEditingPage.value = false;
};

/**
 * 点击页码显示区域,切换到编辑模式
 */
const focusPageInput = () => {
    if (!isEditingPage.value) {
        isEditingPage.value = true;
        pageInput.value = currentPage.value.toString();
        nextTick(() => {
            if (pageInputRef.value) {
                pageInputRef.value.focus();
                pageInputRef.value.select();
            }
        });
    }
};

/**
 * 处理拖动开始事件(鼠标)
 */
const handleDragStart = (e) => {
    // 如果点击的是按钮,不处理拖动
    if (e.target.closest('.zoom-btn') || e.target.closest('.page-jump')) {
        return;
    }
    
    dragStartY.value = e.clientY;
    initialControlsY.value = controlsY.value; // 记录拖动开始时的位置
    dragOffset.value = 0;
    document.addEventListener('mousemove', handleDragMove);
    document.addEventListener('mouseup', handleDragEnd);
    // 不立即调用preventDefault,等确认是拖动后再阻止
};

/**
 * 处理拖动移动事件(鼠标)
 */
const handleDragMove = (e) => {
    const deltaY = Math.abs(dragStartY.value - e.clientY);
    
    // 只有移动距离超过阈值才开始拖动
    if (!isDragging.value && deltaY > dragThreshold) {
        isDragging.value = true;
        e.preventDefault();
    }
    
    if (!isDragging.value) return;
    
    const actualDeltaY = dragStartY.value - e.clientY; // 向上为正,向下为负
    const dampingFactor = 0.3; // 阻尼系数,降低移动速度
    const dampedDelta = actualDeltaY * dampingFactor;
    
    const newY = Math.max(20, Math.min(window.innerHeight - 100, initialControlsY.value + dampedDelta));
    controlsY.value = newY;
    dragOffset.value = dampedDelta;
    e.preventDefault();
};

/**
 * 处理拖动结束事件(鼠标)
 */
const handleDragEnd = () => {
    isDragging.value = false;
    dragStartY.value = 0;
    dragOffset.value = 0;
    document.removeEventListener('mousemove', handleDragMove);
    document.removeEventListener('mouseup', handleDragEnd);
};

/**
 * 处理触摸开始事件(移动端)
 */
const handleTouchStart = (e) => {
    if (e.touches.length === 1) {
        // 如果触摸的是按钮,不处理拖动
        if (e.target.closest('.zoom-btn') || e.target.closest('.page-jump')) {
            return;
        }
        
        dragStartY.value = e.touches[0].clientY;
        initialControlsY.value = controlsY.value; // 记录拖动开始时的位置
        dragOffset.value = 0;
        // 不立即调用preventDefault,等确认是拖动后再阻止
    }
};

/**
 * 处理触摸移动事件(移动端)
 */
const handleTouchMove = (e) => {
    if (e.touches.length !== 1) return;
    
    const deltaY = Math.abs(dragStartY.value - e.touches[0].clientY);
    
    // 只有移动距离超过阈值才开始拖动
    if (!isDragging.value && deltaY > dragThreshold) {
        isDragging.value = true;
        e.preventDefault();
    }
    
    if (!isDragging.value) return;
    
    const actualDeltaY = dragStartY.value - e.touches[0].clientY; // 向上为正,向下为负
    const dampingFactor = 0.4; // 移动端稍微高一点的阻尼系数
    const dampedDelta = actualDeltaY * dampingFactor;
    
    const newY = Math.max(20, Math.min(window.innerHeight - 100, initialControlsY.value + dampedDelta));
    controlsY.value = newY;
    dragOffset.value = dampedDelta;
    e.preventDefault();
};

/**
 * 处理触摸结束事件(移动端)
 */
const handleTouchEnd = () => {
    isDragging.value = false;
    dragStartY.value = 0;
    dragOffset.value = 0;
};

// 超时处理相关
const loadingTimeout = ref(30000); // 超时时间,默认30秒
const timeoutTimer = ref(null); // 超时计时器
const lastProgressTime = ref(0); // 最后一次进度更新时间
const progressCheckInterval = ref(null); // 进度检查间隔器

/**
 * 监听show属性变化,控制PDF加载
 */
watch(() => props.show, (newVal) => {
    if (newVal && props.url) {
        // 重置所有状态
        clearAllTimers(); // 清除之前的计时器
        loading.value = true;
        loadingError.value = false;
        loadingProgress.value = 0;
        errorMessage.value = '';
        zoomLevel.value = 1; // 重置缩放级别
    } else if (!newVal) {
        // 弹窗关闭时重置状态并清理资源
        clearAllTimers(); // 清除计时器

        // 延迟清理,确保PDF组件有时间完成内部清理
        setTimeout(() => {
            loading.value = false;
            loadingError.value = false;
            loadingProgress.value = 0;
            errorMessage.value = '';
            zoomLevel.value = 1; // 重置缩放级别
            scrollPosition.value = { x: 0, y: 0 }; // 重置滚动位置

            // 触发关闭销毁事件,通知父组件清理引用
            emit('onClose');
        }, 100); // 100ms延迟,给PDF组件时间清理
    }
});

/**
 * 监听URL变化,重新加载PDF
 */
watch(() => props.url, (newUrl) => {
    if (newUrl && props.show) {
        // URL变化时重置状态
        clearAllTimers(); // 清除之前的计时器
        loading.value = true;
        loadingError.value = false;
        loadingProgress.value = 0;
        errorMessage.value = '';
        zoomLevel.value = 1; // 重置缩放级别
    }
});

/**
 * 处理PDF下载进度
 * @param {number} loadRatio - 加载进度 0-100
 */
const handleProgress = (loadRatio) => {
    loadingProgress.value = Math.round(loadRatio);
    // 更新最后进度时间
    lastProgressTime.value = Date.now();
    emit('onProgress', loadRatio);
};

/**
 * 处理PDF下载完成
 */
const handleComplete = () => {
    // 清除所有计时器
    clearAllTimers();
    loading.value = false;
    loadingError.value = false;
    loadingProgress.value = 100;
    emit('onLoad', false);
    emit('onComplete');
};

/**
 * 清除所有计时器
 */
const clearAllTimers = () => {
    if (timeoutTimer.value) {
        clearTimeout(timeoutTimer.value);
        timeoutTimer.value = null;
    }
    if (progressCheckInterval.value) {
        clearInterval(progressCheckInterval.value);
        progressCheckInterval.value = null;
    }
};

/**
 * 启动超时监控
 */
const startTimeoutMonitoring = () => {
    // 清除之前的计时器
    clearAllTimers();

    // 记录开始时间
    lastProgressTime.value = Date.now();

    // 启动进度检查间隔器,每5秒检查一次
    progressCheckInterval.value = setInterval(() => {
        const now = Date.now();
        const timeSinceLastProgress = now - lastProgressTime.value;

        // 如果超过设定的超时时间且进度没有变化,则触发超时
        if (timeSinceLastProgress > loadingTimeout.value && loading.value) {
            clearAllTimers();
            loadingError.value = true;
            errorMessage.value = 'PDF加载超时,请检查网络连接或文件是否存在';
            loading.value = false;
        }
    }, 5000); // 每5秒检查一次

    // 设置总体超时计时器(作为备用)
    timeoutTimer.value = setTimeout(() => {
        if (loading.value) {
            clearAllTimers();
            loadingError.value = true;
            errorMessage.value = 'PDF加载超时,请检查网络连接或文件是否存在';
            loading.value = false;
        }
    }, loadingTimeout.value + 5000); // 比进度检查多5秒作为缓冲
};
const handleScroll = (scrollOffset) => {
    // 记录当前滚动位置
    const pdfContainer = document.querySelector('.pdf-viewer-container .pdf-content');
    if (pdfContainer) {
        scrollPosition.value = {
            x: pdfContainer.scrollLeft,
            y: pdfContainer.scrollTop
        };
    }
};

/**
 * 处理页面变化事件
 * @param {number} page - 当前页码
 */
const handlePageChange = (page) => {
    const p = Number(page) || 1;
    currentPage.value = p;
};

/**
 * 处理PDF初始化完成
 * @param {Object} pdf - PDF文档对象
 */
const handlePdfInit = (pdf) => {
    // 启动超时监控
    startTimeoutMonitoring();

    // PDF初始化完成后的处理
    loadingError.value = false;

    // 记录总页数
    try {
        const num = (pdf && typeof pdf.numPages === 'number') ? pdf.numPages : 0;
        if (num > 0) {
            totalPages.value = num;
            if (currentPage.value > num) currentPage.value = num;
        }
    } catch (e) {
        // 忽略无法获取页数的情况
    }

    nextTick(() => {
        if (props.preventSave) {
            // 添加防止保存的事件监听器
            addPreventSaveListeners();
        }
    });
};

/**
 * 处理PDF加载错误
 * @param {Error} error - 错误对象
 */
const handlePdfError = (error) => {
    console.error('PDF加载失败:', error);
    loading.value = false;
    loadingError.value = true;
    loadingProgress.value = 0;

    // 根据错误类型设置不同的错误信息
    if (error.name === 'NetworkError' || error.message.includes('network')) {
        errorMessage.value = '网络连接失败,请检查网络后重试';
    } else if (error.name === 'InvalidPDFException' || error.message.includes('Invalid PDF')) {
        errorMessage.value = 'PDF文件格式错误或已损坏';
    } else if (error.message.includes('404') || error.message.includes('Not Found')) {
        errorMessage.value = '文件不存在或已被删除';
    } else if (error.message.includes('403') || error.message.includes('Forbidden')) {
        errorMessage.value = '没有权限访问此文件';
    } else {
        errorMessage.value = '文件加载失败,请重试';
    }
};

/**
 * 重试加载PDF
 */
const retryLoad = () => {
    clearAllTimers(); // 清除之前的计时器
    loadingError.value = false;
    loading.value = true;
    loadingProgress.value = 0;
    errorMessage.value = '';
    zoomLevel.value = 1; // 重置缩放级别
};

/**
 * 处理关闭弹窗
 */
const handleClose = () => {
    // 先清理所有计时器
    clearAllTimers();

    // 如果PDF组件存在,尝试清理其内部状态
    if (pdfRef.value && typeof pdfRef.value.destroy === 'function') {
        try {
            pdfRef.value.destroy();
        } catch (error) {
            console.warn('PDF组件销毁时出现警告:', error);
        }
    }

    // 使用nextTick确保在DOM更新前完成清理
    nextTick(() => {
        emit('onClose', true);
    });
};

/**
 * 放大PDF
 */
const zoomIn = () => {
    if (zoomLevel.value < 3) { // 最大放大到300%
        const pdfContainer = document.querySelector('.pdf-viewer-container .pdf-content');
        if (pdfContainer) {
            const oldW = pdfContainer.scrollWidth;
            const oldH = pdfContainer.scrollHeight;
            const viewportW = pdfContainer.clientWidth;
            const viewportH = pdfContainer.clientHeight;

            const centerX = pdfContainer.scrollLeft + viewportW / 2;
            const centerY = pdfContainer.scrollTop + viewportH / 2;

            const anchorRatioX = oldW > 0 ? centerX / oldW : 0;
            const anchorRatioY = oldH > 0 ? centerY / oldH : 0;

            zoomLevel.value = Math.min(3, zoomLevel.value + 0.25);

            nextTick(() => {
                const newW = pdfContainer.scrollWidth;
                const newH = pdfContainer.scrollHeight;

                let targetCenterX = newW * anchorRatioX;
                let targetCenterY = newH * anchorRatioY;

                let newScrollLeft = Math.max(0, targetCenterX - viewportW / 2);
                let newScrollTop = Math.max(0, targetCenterY - viewportH / 2);

                newScrollLeft = Math.min(newScrollLeft, Math.max(0, newW - viewportW));
                newScrollTop = Math.min(newScrollTop, Math.max(0, newH - viewportH));

                // 直接赋值避免平滑滚动导致的偏移抖动
                pdfContainer.scrollLeft = newScrollLeft;
                pdfContainer.scrollTop = newScrollTop;
            });
        } else {
            zoomLevel.value = Math.min(3, zoomLevel.value + 0.25);
        }
    }
};

/**
 * 缩小PDF
 */
const zoomOut = () => {
    if (zoomLevel.value > 0.5) { // 最小缩小到50%
        const pdfContainer = document.querySelector('.pdf-viewer-container .pdf-content');
        if (pdfContainer) {
            const oldW = pdfContainer.scrollWidth;
            const oldH = pdfContainer.scrollHeight;
            const viewportW = pdfContainer.clientWidth;
            const viewportH = pdfContainer.clientHeight;

            const centerX = pdfContainer.scrollLeft + viewportW / 2;
            const centerY = pdfContainer.scrollTop + viewportH / 2;

            const anchorRatioX = oldW > 0 ? centerX / oldW : 0;
            const anchorRatioY = oldH > 0 ? centerY / oldH : 0;

            zoomLevel.value = Math.max(0.5, zoomLevel.value - 0.25);

            nextTick(() => {
                const newW = pdfContainer.scrollWidth;
                const newH = pdfContainer.scrollHeight;

                let targetCenterX = newW * anchorRatioX;
                let targetCenterY = newH * anchorRatioY;

                let newScrollLeft = Math.max(0, targetCenterX - viewportW / 2);
                let newScrollTop = Math.max(0, targetCenterY - viewportH / 2);

                newScrollLeft = Math.min(newScrollLeft, Math.max(0, newW - viewportW));
                newScrollTop = Math.min(newScrollTop, Math.max(0, newH - viewportH));

                pdfContainer.scrollLeft = newScrollLeft;
                pdfContainer.scrollTop = newScrollTop;
            });
        } else {
            zoomLevel.value = Math.max(0.5, zoomLevel.value - 0.25);
        }
    }
};

/**
 * 重置缩放
 */
const resetZoom = () => {
    const pdfContainer = document.querySelector('.pdf-viewer-container .pdf-content');
    if (pdfContainer) {
        zoomLevel.value = 1;
        nextTick(() => {
            pdfContainer.scrollLeft = 0;
            pdfContainer.scrollTop = 0;
        });
    } else {
        zoomLevel.value = 1;
    }
};

/**
 * 添加防止保存的事件监听器
 */
const addPreventSaveListeners = () => {
    const pdfContainer = document.querySelector('.pdf-viewer-container .pdf-content');
    if (pdfContainer) {
        // 防止上下文菜单(右键菜单)
        pdfContainer.addEventListener('contextmenu', (e) => {
            e.preventDefault();
            return false;
        });

        // 防止长按选择
        pdfContainer.addEventListener('selectstart', (e) => {
            e.preventDefault();
            return false;
        });

        // 防止拖拽
        pdfContainer.addEventListener('dragstart', (e) => {
            e.preventDefault();
            return false;
        });

        // 添加双指缩放手势支持
        addPinchZoomListeners(pdfContainer);
    }
};

// 双指缩放相关变量
let initialDistance = 0;
let initialZoom = 1;
let isZooming = false;

/**
 * 添加双指缩放手势监听器
 */
const addPinchZoomListeners = (container) => {
    let touches = [];

    // 计算两点间距离
    const getDistance = (touch1, touch2) => {
        const dx = touch1.clientX - touch2.clientX;
        const dy = touch1.clientY - touch2.clientY;
        return Math.sqrt(dx * dx + dy * dy);
    };

    // 获取两点中心位置
    const getCenter = (touch1, touch2) => {
        return {
            x: (touch1.clientX + touch2.clientX) / 2,
            y: (touch1.clientY + touch2.clientY) / 2
        };
    };

    // 触摸开始
    container.addEventListener('touchstart', (e) => {
        touches = Array.from(e.touches);

        if (touches.length === 2) {
            // 双指触摸开始
            e.preventDefault();
            isZooming = true;
            initialDistance = getDistance(touches[0], touches[1]);
            initialZoom = zoomLevel.value;
        } else if (touches.length > 2) {
            // 超过两指时阻止默认行为
            e.preventDefault();
        }
    }, { passive: false });

    // 触摸移动
    container.addEventListener('touchmove', (e) => {
        if (e.touches.length === 2 && isZooming) {
            e.preventDefault();

            const currentTouches = Array.from(e.touches);
            const currentDistance = getDistance(currentTouches[0], currentTouches[1]);
            const scale = currentDistance / initialDistance;

            // 计算新的缩放级别
            let newZoom = initialZoom * scale;
            newZoom = Math.max(0.5, Math.min(3, newZoom)); // 限制缩放范围

            // 获取缩放中心点
            const center = getCenter(currentTouches[0], currentTouches[1]);
            const rect = container.getBoundingClientRect();
            const centerX = center.x - rect.left;
            const centerY = center.y - rect.top;

            // 应用缩放
            applyPinchZoom(newZoom, centerX, centerY, container);
        }
    }, { passive: false });

    // 触摸结束
    container.addEventListener('touchend', (e) => {
        if (isZooming && e.touches.length < 2) {
            isZooming = false;
            initialDistance = 0;
            initialZoom = zoomLevel.value;
        }
    });

    // 触摸取消
    container.addEventListener('touchcancel', (e) => {
        isZooming = false;
        initialDistance = 0;
        initialZoom = zoomLevel.value;
    });
};

/**
 * 应用双指缩放
 */
const applyPinchZoom = (newZoom, centerX, centerY, container) => {
    const oldZoom = zoomLevel.value;
    const oldScrollLeft = container.scrollLeft;
    const oldScrollTop = container.scrollTop;

    // 更新缩放级别
    zoomLevel.value = newZoom;

    // 等待DOM更新后调整滚动位置
    nextTick(() => {
        const zoomRatio = newZoom / oldZoom;

        // 计算新的滚动位置,以缩放中心为锚点
        const newScrollLeft = (oldScrollLeft + centerX) * zoomRatio - centerX;
        const newScrollTop = (oldScrollTop + centerY) * zoomRatio - centerY;

        // 应用新的滚动位置
        container.scrollLeft = Math.max(0, newScrollLeft);
        container.scrollTop = Math.max(0, newScrollTop);
    });
};
</script>

<style scoped>
.pdf-viewer-container {
    width: 100%;
    height: 100%;
    position: relative;
    background-color: #f5f5f5;
}

.pdf-content {
    width: 100%;
    height: 100%;
    overflow: auto;
}

/* 防止PDF内容被选择和保存的样式 */
.pdf-no-select {
    -webkit-user-select: none;
    /* Safari */
    -moz-user-select: none;
    /* Firefox */
    -ms-user-select: none;
    /* IE10+/Edge */
    user-select: none;
    /* Standard */
    -webkit-touch-callout: none;
    /* iOS Safari */
    -webkit-tap-highlight-color: transparent;
    /* 移除点击高亮 */
    pointer-events: auto;
    /* 保持可点击 */
}

/* 深度选择器,防止PDF内部元素被保存 */
:deep(.pdf-no-select img) {
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    -webkit-touch-callout: none;
    -webkit-tap-highlight-color: transparent;
    pointer-events: none;
    /* 禁用图片的所有交互 */
    -webkit-user-drag: none;
    /* 禁止拖拽 */
    -khtml-user-drag: none;
    -moz-user-drag: none;
    -o-user-drag: none;
    user-drag: none;
}

/* 防止Canvas元素被保存 */
:deep(.pdf-no-select canvas) {
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    -webkit-touch-callout: none;
    -webkit-tap-highlight-color: transparent;
    pointer-events: none;
    -webkit-user-drag: none;
    -khtml-user-drag: none;
    -moz-user-drag: none;
    -o-user-drag: none;
    user-drag: none;
}

/* 关闭按钮样式 */
.close-btn {
    position: fixed;
    left: 20px;
    bottom: 40px;
    z-index: 100;
    width: 40px;
    height: 40px;
    padding: 0;
    border-radius: 50%;
    background: rgba(0, 0, 0, 0.6);
    color: #fff;
}

/* 缩放控制按钮样式 */
.zoom-controls {
    position: fixed;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 100;
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 12px;
    background: rgba(255, 255, 255, 0.95);
    padding: 12px 20px;
    border-radius: 25px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
    backdrop-filter: blur(8px);
    transition: all 0.3s ease;
    cursor: grab;
    user-select: none;
}

.zoom-controls:hover {
    background: rgba(255, 255, 255, 1);
    box-shadow: 0 6px 30px rgba(0, 0, 0, 0.2);
    transform: translateX(-50%) translateY(-2px);
}

.zoom-controls.dragging {
    cursor: grabbing;
    transform: translateX(-50%) scale(1.05);
    box-shadow: 0 8px 40px rgba(0, 0, 0, 0.25);
    background: rgba(255, 255, 255, 1);
    transition: none;
}

.zoom-btn {
    width: 40px;
    height: 40px;
    padding: 0;
    border-radius: 50%;
    background: #fff;
    border: 1px solid #e8e8e8;
    color: #333;
    transition: all 0.2s ease;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* .zoom-btn:hover {
    background: #4caf50;
    color: #fff;
    border-color: #4caf50;
    transform: scale(1.1);
    box-shadow: 0 4px 12px rgba(25, 137, 250, 0.3);
} */

.zoom-btn:active {
    transform: scale(0.95);
}

.zoom-level {
    font-size: 14px;
    font-weight: 600;
    color: #333;
    text-align: center;
    min-width: 50px;
    padding: 8px 12px;
    background: rgba(25, 137, 250, 0.1);
    border-radius: 20px;
    border: 1px solid rgba(25, 137, 250, 0.2);
}

/* 加载遮罩样式 */
.wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    background: rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(4px);
}

/* 加载内容样式 */
.loading-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
    color: #fff;
}

.progress-circle {
    width: 80px;
    height: 80px;
    background-color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.progress-percent {
    font-size: 18px;
    font-weight: bold;
    color: #4caf50;
}

.loading-text {
    max-width: 200px;
}

.loading-title {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 8px;
    color: #fff;
}

.loading-subtitle {
    font-size: 14px;
    color: rgba(255, 255, 255, 0.8);
    line-height: 1.4;
}

.page-jump {
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    cursor: pointer;
    min-width: 60px;
    height: 32px;
    background: rgba(0, 0, 0, 0.6);
    border-radius: 16px;
    padding: 0 12px;
}

.page-display {
    color: white;
    font-size: 14px;
    font-weight: 500;
    white-space: nowrap;
    user-select: none;
}

.page-input {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.9);
    border: 2px solid #4caf50;
    border-radius: 16px;
    text-align: center;
    font-size: 14px;
    font-weight: 500;
    color: #333;
    outline: none;
}

.page-input::-webkit-outer-spin-button,
.page-input::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

.page-input[type=number] {
    -moz-appearance: textfield;
}

.page-jump:hover {
    background: rgba(0, 0, 0, 0.8);
}

/* 错误状态样式 */
.error-container {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    background: #f8f9fa;
}

.error-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
    padding: 40px 20px;
    max-width: 300px;
}

.error-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin: 16px 0 8px 0;
}

.error-message {
    font-size: 14px;
    color: #666;
    line-height: 1.5;
    margin-bottom: 20px;
}

.retry-btn {
    min-width: 100px;
}
</style>