pdfh5

repository·master·Indexed 22 days ago

https://github.com/gjtool/pdfh5

A JS plugin for PDF preview and gesture zooming on mobile web/H5. It supports lazy and segmented loading modes for efficient file handling and is compatible with Vue and React. Key features include hardware acceleration, text layer support, annotation editor modes, sandbox security, and comprehensive control methods for page navigation and zoom management.

Tokens
13.2K
Snippets
35
Records
64
Agent score
78%

What's inside pdfh5

  1. Enable Lazy Loading and Progressive Loading

    master

    For large PDF files, use these modes to optimize memory and performance:

    Lazy Loading

    Set lazyLoad: true to only render pages that are currently visible in the viewport.

    Progressive Loading

    Enables streaming loading via PDF.js with intelligent memory management. Use these keys to tune performance:

    • progressiveLoading (Boolean): Enable mode (default: false).
    • chunkSize (Number): Chunk size in bytes (default: 65536).
    • maxMemoryPages (Number): Maximum pages kept in memory before auto-cleaning distant pages (default: 5).
    • maxImageSize (Number): Max image size in bytes (default: 8388608).
    • canvasMaxAreaInBytes (Number): Max canvas area in bytes (default: 8388608).
  2. How loading modes work in pdfh5

    master

    pdfh5 supports different loading strategies based on file size to optimize performance:

    • Small files: Loaded entirely at once.
    • Medium files: Uses Lazy Loading (懒加载).
    • Large files: Uses Segmented Loading (分段加载).

    Priority Logic: If multiple modes are configured, the library follows this priority order: Segmented Loading > Lazy Loading > Traditional Loading.

  3. Quickstart: Use pdfh5 with a script tag

    master

    For simple HTML projects, you can include pdfh5.js via a <script> tag. The plugin will automatically attempt to detect and load the necessary PDF.js resources.

    1. Create a container div.
    2. Include the script.
    3. Instantiate Pdfh5 with the container and the pdfurl option.
    <!-- 1. Create container -->
    <div id="demo"></div>
    
    <!-- 2. Include plugin -->
    <script src="js/pdfh5.js"></script>
    
    <!-- 3. Instantiate -->
    <script>
    var pdfh5 = new Pdfh5(document.querySelector("#demo"), {
        pdfurl: "./default.pdf"
    });
    </script>
  4. Configure server for progressive loading (Range Requests)

    master

    Progressive loading (segment loading) requires the server to support HTTP Range Requests. If your server does not support Range headers, progressive loading will not work.

    location ~* \.(pdf)$ {
        add_header Accept-Ranges bytes;
        add_header Content-Type application/pdf;
        expires 1h;
        add_header Cache-Control "public, immutable";
        add_header Access-Control-Allow-Origin "*";
        add_header Access-Control-Allow-Methods "GET, HEAD, OPTIONS";
        add_header Access-Control-Allow-Headers "Range, Content-Range";
        
        if ($request_method = 'OPTIONS') {
            add_header Access-Control-Allow-Origin "*";
            add_header Access-Control-Allow-Methods "GET, HEAD, OPTIONS";
            add_header Access-Control-Allow-Headers "Range, Content-Range";
            add_header Access-Control-Max-Age 86400;
            return 204;
        }
    }

    Node.js Express Configuration

    const express = require('express');
    const app = express();
    
    app.use('/pdf', (req, res, next) => {
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');
        res.header('Access-Control-Allow-Headers', 'Range, Content-Range');
        if (req.method === 'OPTIONS') {
            res.status(204).end();
            return;
        }
        next();
    });
    
    app.use('/pdf', express.static('pdf-files', {
        setHeaders: (res, path) => {
            if (path.endsWith('.pdf')) {
                res.setHeader('Content-Type', 'application/pdf');
                res.setHeader('Accept-Ranges', 'bytes');
            }
        }
    }));

    Verify Range Request Support

    You can verify if your server is correctly configured using curl:

    curl -H "Range: bytes=0-1023" -I http://your-server.com/path/to/file.pdf

    Expected Response Headers:

    • HTTP/1.1 206 Partial Content
    • Accept-Ranges: bytes
    • Content-Range: bytes 0-1023/1048576
    • Content-Length: 1024
  5. Enable Volar Take Over Mode for better TypeScript performance

    master

    If the standalone TypeScript plugin is slow, you can enable Volar's Take Over Mode. This makes the TypeScript language service aware of .vue types more efficiently by letting Volar handle both TS and Vue files.

    Follow these steps in VS Code:

    1. Disable the built-in TypeScript Extension:
      • Open the Command Palette (Ctrl+Shift+P or Cmd+Shift+P).
      • Run Extensions: Show Built-in Extensions.
      • Find TypeScript and JavaScript Language Features.
      • Right-click it and select Disable (Workspace).
    2. Reload the window:
      • Open the Command Palette.
      • Run Developer: Reload Window.
  6. Manage the react-test project with Yarn scripts

    master

    The react-test package is a React application bootstrapped with Create React App. You can manage the development lifecycle using the following Yarn commands in the project directory:

    # Run the app in development mode at http://localhost:3000
    yarn start
    
    # Launch the test runner in interactive watch mode
    yarn test
    
    # Build the app for production in the `build` folder
    yarn build
    
    # Remove the single build dependency and copy all configuration files (webpack, Babel, etc.) into your project
    # WARNING: This is a one-way operation and you cannot undo it.
    yarn eject
  7. Install pdfh5 via npm

    master

    To use pdfh5 in modern JavaScript environments like Vue or React, install it via npm.

    Important: Static Assets Setup After installing, you must manually copy the following directories/files from the pdfh5 package folder to your project's public static assets directory to ensure the PDF engine functions correctly:

    • cmaps
    • iccs
    • standard_fonts
    • wasm
    • js/pdf.worker.min.js
    npm install pdfh5
  8. Configure IDE for Vue 3 + TypeScript + Vite development

    master

    To ensure optimal development experience with Vue 3, TypeScript, and Vite, use VS Code with the following extensions:

    1. Volar: The essential Vue language feature extension.
    2. TypeScript Vue Plugin (Volar): To provide type information for .vue imports in TypeScript.

    Note: If you are using Volar, you should disable the Vetur extension to avoid conflicts.

  9. Initialize pdfh5 with basic and advanced configurations

    master

    To use pdfh5, instantiate the Pdfh5 class by passing a DOM element and an options object.

    Basic usage requires pdfurl.

    Advanced usage allows for fine-grained control over rendering (HWA, text layers), interaction (zoom, scroll, back-to-top), progressive loading (for large files), annotation editor settings, and sandbox security.

    // Basic usage
    var pdfh5 = new Pdfh5(document.querySelector("#demo"), {
        pdfurl: "./document.pdf",
        scale: 1.5,
        textLayer: true,
        zoomEnable: true,
        scrollEnable: true
    });
    
    // Advanced configuration
    var pdfh5 = new Pdfh5(document.querySelector("#demo"), {
        // Basic
        pdfurl: "./large-document.pdf",
        password: "123456",
        
        // Rendering
        scale: 1.0,
        textLayer: true,
        enableHWA: true,
        
        // Interaction
        zoomEnable: true,
        scrollEnable: true,
        backTop: true,
        pageNum: true,
        loadingBar: true,
        
        // Gesture Zoom
        tapZoomFactor: 2,
        maxZoom: 4,
        minZoom: 0.5,
        
        // Progressive Loading (Recommended for large files)
        progressiveLoading: true,
        chunkSize: 65536,
        maxMemoryPages: 5,
        
        // Annotation Editor
        annotationEditorMode: "FREETEXT",
        editorParams: {
            freeTextColor: "#000000",
            freeTextSize: 12,
            inkColor: "#000000",
            inkThickness: 1
        },
        
        // Sandbox Security
        sandboxEnabled: true,
        sandboxOptions: {
            allowScripts: false,
            allowForms: true,
            allowPopups: false,
            allowSameOrigin: true
        },
        
        // Resource Paths
        workerSrc: "./pdf.worker.min.js",
        cMapUrl: "../cmaps/",
        standardFontDataUrl: "../standard_fonts/",
        iccUrl: "../iccs/",
        wasmUrl: "../wasm/"
    });