Convert Figma logo to code with AI

gjTool logopdfh5

web/h5/移动端PDF预览插件,可手势缩放。支持npm install和script标签引入

1,071
247
1,071
86

Top Related Projects

52,603

PDF Reader in JavaScript

12,193

Client/server side PDF printing in pure JavaScript

10,554

A JavaScript PDF generation library for Node and the browser

30,767

Client-side JavaScript PDF generation for everyone.

Quick Overview

The pdfh5 project is a Python library that provides a simple and efficient way to extract text and images from PDF files and convert them into HTML5 format. It is designed to be a lightweight and easy-to-use tool for developers who need to work with PDF data in their applications.

Pros

  • Cross-platform compatibility: The library is written in Python, which makes it compatible with a wide range of operating systems, including Windows, macOS, and Linux.
  • Efficient PDF processing: The library uses a fast and reliable PDF parsing library, which allows it to process PDF files quickly and accurately.
  • Customizable output: The library allows users to customize the output HTML5 format, including the ability to specify the layout, styling, and metadata.
  • Easy integration: The library is easy to integrate into existing Python-based projects, with a simple and intuitive API.

Cons

  • Limited PDF feature support: The library may not support all the features and functionality of PDF files, such as complex layouts, annotations, or interactive elements.
  • Dependency on external libraries: The library relies on several external libraries, which may increase the complexity of the installation and setup process.
  • Potential performance issues: Depending on the size and complexity of the PDF files being processed, the library may experience performance issues, especially when processing large or complex documents.
  • Limited documentation: The project's documentation may be limited, which could make it more difficult for new users to get started with the library.

Code Examples

Here are a few examples of how to use the pdfh5 library:

from pdfh5 import PDF2HTML

# Convert a PDF file to HTML5
pdf = PDF2HTML('input.pdf')
html = pdf.convert()
with open('output.html', 'w') as f:
    f.write(html)

This code converts the input.pdf file to an HTML5 format and saves the result to the output.html file.

from pdfh5 import PDF2HTML

# Extract text from a PDF file
pdf = PDF2HTML('input.pdf')
text = pdf.get_text()
print(text)

This code extracts the text content from the input.pdf file and prints it to the console.

from pdfh5 import PDF2HTML

# Extract images from a PDF file
pdf = PDF2HTML('input.pdf')
images = pdf.get_images()
for i, image in enumerate(images):
    image.save(f'image_{i}.png')

This code extracts all the images from the input.pdf file and saves them as individual PNG files.

Getting Started

To get started with the pdfh5 library, follow these steps:

  1. Install the library using pip:
pip install pdfh5
  1. Import the PDF2HTML class from the pdfh5 module:
from pdfh5 import PDF2HTML
  1. Create a PDF2HTML object and use its methods to process a PDF file:
# Convert a PDF file to HTML5
pdf = PDF2HTML('input.pdf')
html = pdf.convert()
with open('output.html', 'w') as f:
    f.write(html)
  1. Customize the output by passing additional arguments to the convert() method:
# Customize the output HTML5
pdf = PDF2HTML('input.pdf')
html = pdf.convert(layout='grid', metadata={'title': 'My PDF Document'})
with open('output.html', 'w') as f:
    f.write(html)
  1. Explore the other methods provided by the PDF2HTML class, such as get_text() and get_images(), to extract specific content from the PDF file.

For more detailed information and advanced usage, please refer to the project's documentation.

Competitor Comparisons

52,603

PDF Reader in JavaScript

Pros of pdf.js

  • More comprehensive and feature-rich PDF rendering solution
  • Widely adopted and battle-tested in production environments
  • Extensive documentation and community support

Cons of pdf.js

  • Larger file size and potentially higher resource usage
  • Steeper learning curve for implementation and customization
  • May be overkill for simple PDF viewing needs

Code Comparison

pdf.js:

pdfjsLib.getDocument('path/to/document.pdf').promise.then(function(pdf) {
  pdf.getPage(1).then(function(page) {
    var scale = 1.5;
    var viewport = page.getViewport({ scale: scale });
    // Render page
  });
});

pdfh5:

new Pdfh5('#demo', {
  pdfurl: 'path/to/document.pdf',
  zoomEnable: true,
  scrollEnable: true
});

Summary

pdf.js offers a more robust and feature-complete solution for PDF rendering, with extensive community support and documentation. However, it may be more complex to implement and have a larger footprint. pdfh5 provides a simpler, more lightweight option for basic PDF viewing needs, but with fewer advanced features and less widespread adoption.

12,193

Client/server side PDF printing in pure JavaScript

Pros of pdfmake

  • Client-side PDF generation in pure JavaScript, allowing for dynamic PDF creation in browsers
  • Extensive documentation and examples, making it easier for developers to get started
  • Supports complex layouts, tables, and styling options for creating professional-looking documents

Cons of pdfmake

  • Larger file size compared to pdfh5, which may impact load times for web applications
  • Steeper learning curve due to its more comprehensive feature set
  • Limited support for existing PDF manipulation (primarily focused on PDF creation)

Code Comparison

pdfmake:

var docDefinition = {
  content: [
    'Hello world',
    { text: 'Styled text', style: 'header' },
    { table: { body: [['Column 1', 'Column 2'], ['Value 1', 'Value 2']] } }
  ]
};
pdfMake.createPdf(docDefinition).download();

pdfh5:

var pdfh5 = new Pdfh5('#demo', {
  pdfurl: './path/to/your.pdf'
});
pdfh5.renderPdf();

The code comparison shows that pdfmake is focused on creating PDFs from scratch using JavaScript objects, while pdfh5 is primarily used for rendering existing PDFs in the browser.

10,554

A JavaScript PDF generation library for Node and the browser

Pros of PDFKit

  • More comprehensive PDF creation capabilities, allowing for complex document generation
  • Better documentation and wider community support
  • Supports both server-side (Node.js) and client-side (browser) usage

Cons of PDFKit

  • Larger file size and potentially higher resource usage
  • Steeper learning curve for beginners due to more advanced features
  • Primarily focused on PDF creation rather than viewing

Code Comparison

PDFKit (PDF creation):

const PDFDocument = require('pdfkit');
const doc = new PDFDocument();
doc.pipe(fs.createWriteStream('output.pdf'));
doc.text('Hello, world!');
doc.end();

PDFH5 (PDF viewing):

var pdfh5 = new Pdfh5('#demo', {
  pdfurl: './test.pdf'
});
pdfh5.renderPdf(1);

Key Differences

  • PDFKit is primarily for creating PDFs, while PDFH5 focuses on viewing PDFs in browsers
  • PDFKit offers more control over PDF content and structure
  • PDFH5 provides a simpler API for displaying PDFs in web applications
  • PDFKit has broader platform support, including server-side usage
  • PDFH5 is more lightweight and easier to integrate for basic PDF viewing needs
30,767

Client-side JavaScript PDF generation for everyone.

Pros of jsPDF

  • More comprehensive PDF creation capabilities, including text, images, and vector graphics
  • Wider browser compatibility and no external dependencies
  • Larger community and more frequent updates

Cons of jsPDF

  • Steeper learning curve due to more complex API
  • Larger file size, which may impact page load times
  • Limited built-in support for viewing PDFs in the browser

Code Comparison

pdfh5:

var pdfh5 = new Pdfh5('#demo', {
  pdfurl: './path/to/pdf'
});

jsPDF:

var doc = new jsPDF();
doc.text('Hello world!', 10, 10);
doc.save('a4.pdf');

Summary

pdfh5 is primarily focused on PDF viewing within the browser, offering a simpler API for basic PDF display. jsPDF, on the other hand, provides a more powerful toolkit for creating PDFs from scratch, with extensive options for content manipulation. While pdfh5 excels in quick PDF viewing integration, jsPDF is better suited for applications requiring dynamic PDF generation and complex document creation.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

pdfh5.js

npm version npm downloads npm downloads MIT GitHub issues GitHub stars GitHub forks

有问题可以加Q群咨询,技术交流群,也可以探讨技术,另有开发技术讨论微信群可以问群主拉入微信群

pdfh5.js示例

更新信息

  • 2025.10.19 更新: v3.0.0大版本更新,支持官方pdf.js v5.4.296,移除svg渲染模式,恢复懒加载模式,新增分段加载模式,新增沙箱集成(防止JavaScript注入等),新增密码pdf文件预览,优化手势缩放(后续会继续优化,目前还是有问题)。

  • 根据需求选择加载模式:小文件直接全部加载,中等文件用懒加载,大文件用分段加载。如果同时配置多个模式,按优先级:分段加载 > 懒加载 > 传统加载。

pdfh5在线预览

https://pdfh5.gjtool.cn/pdfh5/password.pdf 密码 123456zxcv..

快速开始(有两种方式)

一、script标签引入方式

  • 1.创建div容器
<div id="demo"></div>
  • 2.引入pdfh5.js(插件会自动检测并加载PDF.js资源)
<script src="js/pdfh5.js"></script>
  • 3.实例化
var pdfh5 = new Pdfh5(document.querySelector("#demo"), {
    pdfurl: "./default.pdf"
});

二、npm安装方式(适应于vue), react使用方法类似vue(example/react-test是react使用示例)

  • 1.安装
npm install pdfh5
  • 2.静态资源引用

    将pdfh5文件夹下的cmaps、iccs、standard_fonts、wasm、js/pdf.worker.min.js都放置到public静态资源目录下

  • 3.使用

<script setup lang="ts">
import Pdfh5 from "pdfh5"
import { ref, onMounted, onUnmounted } from 'vue'

const container = ref<HTMLElement>()
let pdfViewer: any = null

onMounted(async () => {
  try {
    
    console.log('Pdfh5构造函数:', Pdfh5);

    // 创建PDF查看器
    pdfViewer = new Pdfh5(container.value!, {
      pdfurl: "/git.pdf",
      textLayer: true,
      workerSrc:"./pdf.worker.min.js",
      cMapUrl: './cmaps/',
      standardFontDataUrl: './standard_fonts/',
      iccUrl: './iccs/',
      wasmUrl: './wasm/'
    });
    console.log('PDF查看器创建成功:', pdfViewer);

  } catch (error) {
    console.error('PDF初始化失败:', error);
  }
})

onUnmounted(() => {
  if (pdfViewer && typeof pdfViewer.destroy === 'function') {
    pdfViewer.destroy()
  }
})
</script>

<template>
  <div class="pdf-container" ref="container"></div>
</template>

<style scoped>
.pdf-container {
  width: 100%;
  height: 100vh;
}
</style>

API接口方法

实例化

  • pdfh5实例化的时候传两个参数,selector选择器,options配置项参数,会返回一个pdfh5实例对象,可以用来操作pdf,监听相关事件
var pdfh5 = new Pdfh5(selector, options);
参数名称类型取值是否必须作用
selectorHTMLElement-√pdfh5的容器,html DOM元素对象
optionsObject-×pdfh5的配置项参数

options配置项参数列表

  • 示例: 配置项参数 pdfurl
var pdfh5 = new Pdfh5(document.querySelector("#demo"), {
	pdfurl: "./default.pdf"
});

基础配置

参数名称类型取值默认值作用
pdfurlStringPDF文件地址-pdf地址
dataArray(arraybuffer)PDF文件流数据-pdf文件流 ,与pdfurl二选一(二进制PDF数据。使用类型化数组(Uint8Array)可以提高内存使用率。如果PDF数据是BASE64编码的,请先使用atob()将其转换为二进制字符串。)
passwordStringPDF密码nullPDF密码(如果有密码保护)
gotoNumber页码数字0加载pdf跳转到第几页(0表示不跳转)

渲染配置

参数名称类型取值默认值作用
scaleNumber渲染比例1pdf渲染的比例
textLayerBooleantrue、falsefalse是否开启textLayer,可以复制文本
enableHWABooleantrue、falsetrue是否启用硬件加速,对图片渲染很重要
cMapUrlString字体映射文件路径智能检测解析pdf时,特殊情况下显示完整字体的cmaps文件夹路径
standardFontDataUrlString标准字体路径智能检测标准字体文件路径
iccUrlString颜色配置文件路径智能检测颜色管理配置文件路径
wasmUrlStringWebAssembly文件路径智能检测高性能PDF渲染的WebAssembly文件路径
workerSrcStringPDF.js Worker路径智能检测PDF.js Worker文件路径

交互配置

参数名称类型取值默认值作用
scrollEnableBooleantrue、falsetrue是否允许pdf滚动
zoomEnableBooleantrue、falsetrue是否允许pdf手势缩放
resizeBooleantrue、falsetrue是否允许窗口大小变化时重新渲染

懒加载配置

参数名称类型取值默认值作用
lazyLoadBooleantrue、falsefalse启用懒加载模式,只渲染可见页面

分段加载配置

参数名称类型取值默认值作用
progressiveLoadingBooleantrue、falsefalse启用分段加载模式,PDF.js官方流式加载+智能内存管理
chunkSizeNumber数字,单位字节65536分块大小,默认64KB
maxMemoryPagesNumber数字5最大内存页面数,超过会自动清理远距离页面
maxImageSizeNumber数字,单位字节8388608最大图片大小,8388608,兼容iOS Safari
canvasMaxAreaInBytesNumber数字,单位字节8388608最大canvas面积,iOS Safari浏览器canvas限制约为16777216

UI组件配置

参数名称类型取值默认值作用
loadingBarBooleantrue、falsetrue是否显示加载进度条
pageNumBooleantrue、falsetrue是否显示左上角页码
backTopBooleantrue、falsetrue是否显示右下角回到顶部按钮

其他配置

参数名称类型取值默认值作用
gotoNumber页码数字0加载pdf跳转到第几页
enableHWABooleantrue、falsetrue是否启用硬件加速,对图片渲染很重要

手势缩放配置

参数名称类型取值默认值作用
tapZoomFactorNumber数字2双击缩放倍数
zoomOutFactorNumber数字1.2缩放回弹因子
animationDurationNumber数字,单位毫秒300缩放动画持续时间
maxZoomNumber数字4最大缩放倍数
minZoomNumber数字0.5最小缩放倍数
dampingFactorNumber数字0.85阻尼因子

注释编辑器配置

参数名称类型取值默认值作用
annotationEditorModeString"NONE"、"FREETEXT"、"HIGHLIGHT"、"INK"、"STAMP"、"SIGNATURE""NONE"注释编辑器模式
editorParamsObject编辑器参数对象{}注释编辑器参数配置

沙箱安全配置

参数名称类型取值默认值作用
sandboxEnabledBooleantrue、falsetrue是否启用沙箱模式,防止JavaScript注入和XSS攻击

沙箱配置选项(sandboxOptions)

参数名称类型取值默认值作用
allowScriptsBooleantrue、falsefalse是否允许JavaScript执行
allowFormsBooleantrue、falsetrue是否允许表单交互
allowPopupsBooleantrue、falsefalse是否允许弹窗
allowSameOriginBooleantrue、falsetrue是否允许同源访问
sandboxStringHTML sandbox属性值"allow-same-origin allow-scripts"HTML sandbox属性,控制沙箱行为
referrerPolicyStringreferrer策略值"strict-origin-when-cross-origin"引用策略,控制referrer信息

沙箱配置示例

var pdfh5 = new Pdfh5(document.querySelector("#demo"), {
    pdfurl: "./document.pdf",
    sandboxEnabled: true,
    sandboxOptions: {
        allowScripts: false,        // 禁止JavaScript执行
        allowForms: true,           // 允许表单交互
        allowPopups: false,         // 禁止弹窗
        allowSameOrigin: true,       // 允许同源访问
        sandbox: "allow-same-origin allow-scripts",
        referrerPolicy: "strict-origin-when-cross-origin"
    }
});

资源路径配置说明

var pdfh5 = new Pdfh5(document.querySelector("#demo"), {
    pdfurl: "./document.pdf",
    workerSrc: "./pdf.worker.min.js",
    cMapUrl: "../cmaps/",
    standardFontDataUrl: "../standard_fonts/",
    iccUrl: "../iccs/",
    wasmUrl: "../wasm/"
});

资源文件说明

插件需要以下PDF.js资源文件:

  • cmaps/ - 字体映射文件(用于正确显示中文字体)
  • standard_fonts/ - 标准字体文件(用于PDF标准字体渲染)
  • iccs/ - 颜色配置文件(用于颜色管理和色彩空间转换)
  • wasm/ - WebAssembly文件(用于高性能PDF渲染和图像解码)
  • pdf.worker.min.js - PDF.js Worker文件(用于后台PDF处理)

pdf请求示例

1、文件地址

new Pdfh5(document.querySelector("#demo"), {
	pdfurl: "git.pdf"
});

2、pdf文件流或者arraybuffer已经得到,如何渲染

 new Pdfh5(document.querySelector("#demo"), {
 	data: blob,  //blob arraybuffer
 });

methods 方法列表

基础控制方法

方法名传参传参取值作用
showFunction带一个回调函数pdfh5显示
hideFunction带一个回调函数pdfh5隐藏
destroyFunction带一个回调函数pdfh5销毁

交互控制方法

方法名传参传参取值作用
setScrollEnabledBooleantrue、false启用/禁用PDF滚动
setZoomEnabledBooleantrue、false启用/禁用PDF手势缩放
isScrollEnabled-无参数获取滚动状态
isZoomEnabled-无参数获取缩放状态
setProgressiveLoadingBoolean, ObjectBoolean:是否启用, Object:配置选项{chunkSize, maxMemoryPages}设置分段加载配置
getProgressiveLoadingStatus-无参数获取分段加载状态
getMemoryUsage-无参数获取内存使用情况

页面导航方法

方法名传参传参取值作用
goToPageNumberNumber:要跳转的pdf页数pdf跳转到第几页(pdf加载完成后使用)
nextPage-无参数跳转到下一页
prevPage-无参数跳转到上一页
scrollToTop-无参数滚动到顶部

缩放控制方法

方法名传参传参取值作用
zoomIn-无参数放大PDF
zoomOut-无参数缩小PDF
setScaleNumberNumber:缩放比例设置缩放比例
setZoomEnabledBooleantrue、false启用/禁用缩放手势
isZoomEnabledBoolean无参数获取缩放状态
setZoomConstraintsObject{minScale, maxScale, step}设置缩放约束
getZoomConstraints-无参数获取缩放约束
isZooming-无参数检查是否正在缩放

搜索功能方法

方法名传参传参取值作用
searchTextStringString:搜索关键词搜索文本
findNext-无参数查找下一个匹配项
findPrevious-无参数查找上一个匹配项
clearSearch-无参数清除搜索高亮

下载和打印方法

方法名传参传参取值作用
downloadPDFStringString:下载文件名,默认"document.pdf"下载PDF
printPDF-无参数打印PDF(渲染所有页面到打印容器)

分段加载方法

方法名传参传参取值作用
setProgressiveLoadingBoolean, ObjectBoolean:是否启用, Object:配置选项{chunkSize, maxMemoryPages}设置分段加载配置
getProgressiveLoadingStatus-无参数获取分段加载状态
getMemoryUsage-无参数获取内存使用情况

注释编辑器方法

方法名传参传参取值作用
setAnnotationEditorModeStringString:编辑器模式("NONE"、"FREETEXT"、"HIGHLIGHT"、"INK"、"STAMP"、"SIGNATURE")设置注释编辑器模式
getAnnotationEditorMode-无参数获取当前注释编辑器模式
addAnnotationObjectObject:注释数据对象添加注释
removeAnnotationStringString:注释ID删除注释
updateAnnotationString, ObjectString:注释ID, Object:更新数据更新注释
getAnnotations-无参数获取所有注释
clearAnnotations-无参数清除所有注释

分段加载需要的服务端配置说明

1. Nginx配置(推荐)

分段加载需要服务端支持HTTP范围请求(Range Requests),Nginx默认支持静态文件的范围请求,但需要正确配置:

# 基础配置 - 支持PDF文件的范围请求
location ~* \.(pdf)$ {
    # 启用范围请求支持
    add_header Accept-Ranges bytes;
    
    # 设置正确的MIME类型
    add_header Content-Type application/pdf;
    
    # 缓存控制(可选)
    expires 1h;
    add_header Cache-Control "public, immutable";
    
    # CORS支持(如果需要跨域)
    add_header Access-Control-Allow-Origin "*";
    add_header Access-Control-Allow-Methods "GET, HEAD, OPTIONS";
    add_header Access-Control-Allow-Headers "Range, Content-Range";
    
    # 处理OPTIONS请求
    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;
    }
}

2. 反向代理配置

如果使用Nginx作为反向代理,需要额外配置:

location /api/pdf/ {
    proxy_pass http://backend_server;
    
    # 禁用缓冲,支持流式传输
    proxy_buffering off;
    proxy_request_buffering off;
    
    # 设置超时时间
    proxy_read_timeout 300s;
    proxy_connect_timeout 60s;
    
    # 使用HTTP/1.1
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    
    # 传递原始请求头
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    
    # 支持范围请求
    proxy_set_header Range $http_range;
    proxy_set_header If-Range $http_if_range;
}

3. Apache配置

如果使用Apache服务器:

# 启用mod_rewrite和mod_headers
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule headers_module modules/mod_headers.so

# 配置PDF文件处理
<LocationMatch "\.pdf$">
    # 启用范围请求
    Header set Accept-Ranges bytes
    
    # 设置MIME类型
    Header set Content-Type "application/pdf"
    
    # CORS支持
    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Methods "GET, HEAD, OPTIONS"
    Header set Access-Control-Allow-Headers "Range, Content-Range"
    
    # 缓存控制
    Header set Cache-Control "public, max-age=3600"
</LocationMatch>

4. Node.js Express配置

如果使用Node.js作为后端:

const express = require('express');
const app = express();

// 支持范围请求的中间件
app.use('/pdf', (req, res, next) => {
    // 设置CORS头
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Range, Content-Range');
    
    // 处理OPTIONS请求
    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');
        }
    }
}));

5. PHP配置

如果使用PHP作为后端:

<?php
// 设置CORS头
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, HEAD, OPTIONS');
header('Access-Control-Allow-Headers: Range, Content-Range');

// 处理OPTIONS请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

// 支持范围请求的PDF文件服务
$file = $_GET['file'];
$filePath = 'pdf-files/' . $file;

if (file_exists($filePath)) {
    $fileSize = filesize($filePath);
    $range = $_SERVER['HTTP_RANGE'] ?? '';
    
    if ($range) {
        // 处理范围请求
        $ranges = explode('=', $range);
        $offset = explode('-', $ranges[1]);
        $start = intval($offset[0]);
        $end = isset($offset[1]) ? intval($offset[1]) : $fileSize - 1;
        
        header('HTTP/1.1 206 Partial Content');
        header('Content-Range: bytes ' . $start . '-' . $end . '/' . $fileSize);
        header('Content-Length: ' . ($end - $start + 1));
        header('Content-Type: application/pdf');
        header('Accept-Ranges: bytes');
        
        $fp = fopen($filePath, 'rb');
        fseek($fp, $start);
        echo fread($fp, $end - $start + 1);
        fclose($fp);
    } else {
        // 完整文件请求
        header('Content-Type: application/pdf');
        header('Content-Length: ' . $fileSize);
        header('Accept-Ranges: bytes');
        readfile($filePath);
    }
}
?>

6. 配置验证

验证服务端是否正确支持范围请求:

# 测试范围请求
curl -H "Range: bytes=0-1023" -I http://your-server.com/path/to/file.pdf

# 应该返回:
# HTTP/1.1 206 Partial Content
# Accept-Ranges: bytes
# Content-Range: bytes 0-1023/1048576
# Content-Length: 1024

事件监听方法

方法名传参传参取值作用
on(String, Function)String:监听的事件名,Function:监听的事件回调监听事件
offStringString:要移除的事件名移除事件监听
trigger(String, Object)String:事件名,Object:事件数据触发事件

状态获取方法

方法名传参传参取值作用
getStatus-无参数获取当前状态信息

on方法监听所有事件-事件名列表

  • 示例: 监听pdf准备开始渲染,此时可以拿到pdf总页数
pdfh5.on("ready", function () {
	console.log("总页数:" + this.totalNum)
})

生命周期事件

事件名回调参数作用
initFunction监听pdfh5开始初始化
readyFunction监听pdf准备开始渲染,此时可以拿到pdf总页数
errorFunction(msg,time)监听加载失败,msg信息,time耗时
successFunction(msg,time)监听pdf渲染成功,msg信息,time耗时
completeFunction(status, msg, time)监听pdf加载完成事件,加载失败、渲染成功都会触发。status有两种状态success和error
renderFunction(currentNum, pageTime, totalTime, currentPageDom)监听pdf渲染过程,currentNum当前页码,pageTime单页耗时,totalTime总耗时,currentPageDom当前页面DOM

交互事件

事件名回调参数作用
zoomFunction(scale)监听pdf缩放,scale缩放比例
zoomStartFunction(data)监听缩放开始,data包含scale和startTime
zoomEndFunction(data)监听缩放结束,data包含scale、startScale、scaleChange、duration等
pageLoadedFunction(data)监听页面加载完成(分段加载),data包含pageNum和memoryUsage
pageCleanedFunction(data)监听页面清理完成(分段加载),data包含pageNum
scrollFunction(data)监听pdf滚动,data包含scrollTop滚动条高度和currentNum当前页码
backTopFunction监听回到顶部按钮的点击事件回调

控制事件

事件名回调参数作用
zoomEnabledFunction(flag)监听缩放启用状态变化,flag:true,false
scrollEnabledFunction(flag)监听滚动启用状态变化,flag:true,false
showFunction监听pdfh5显示
hideFunction监听pdfh5隐藏
destroyFunction监听pdfh5销毁

注释编辑器事件

事件名回调参数作用
annotationAddedFunction(data)监听注释添加,data包含注释信息
annotationRemovedFunction(data)监听注释删除,data包含注释信息
annotationUpdatedFunction(data)监听注释更新,data包含注释信息
annotationModeChangedFunction(mode)监听注释模式变化,mode为新的模式
annotationSelectedFunction(data)监听注释选择,data包含选中的注释信息

事件监听示例

// 监听PDF加载完成事件
pdfh5.on("complete", function (status, msg, time) {
    console.log("状态:" + status + ",总耗时:" + time + "毫秒,总页数:" + this.totalNum, msg);
});

// 监听滚动事件
pdfh5.on("scroll", function (data) {
    console.log("scrollTop:" + data.scrollTop, "currentNum:" + data.currentNum);
});

// 监听注释编辑器事件
pdfh5.on("annotationAdded", function (data) {
    console.log("注释已添加:", data);
});

pdfh5.on("annotationModeChanged", function (mode) {
    console.log("注释模式已切换为:", mode);
});

完整使用示例

基础使用

var pdfh5 = new Pdfh5(document.querySelector("#demo"), {
    pdfurl: "./document.pdf",
    scale: 1.5,
    textLayer: true,
    zoomEnable: true,
    scrollEnable: true
});

高级配置示例

var pdfh5 = new Pdfh5(document.querySelector("#demo"), {
    // 基础配置
    pdfurl: "./large-document.pdf",
    password: "123456", // 如果有密码保护
    
    // 渲染配置
    scale: 1.0,
    textLayer: true,
    enableHWA: true,
    
    // 交互配置
    zoomEnable: true,
    scrollEnable: true,
    backTop: true,
    pageNum: true,
    loadingBar: true,
    
    // 手势缩放配置
    tapZoomFactor: 2,
    maxZoom: 4,
    minZoom: 0.5,
    
    // 分段加载配置(大文件推荐)
    progressiveLoading: true,
    chunkSize: 65536,
    maxMemoryPages: 5,
    
    // 注释编辑器配置
    annotationEditorMode: "FREETEXT",
    editorParams: {
        freeTextColor: "#000000",
        freeTextSize: 12,
        inkColor: "#000000",
        inkThickness: 1
    },
    
    // 沙箱安全配置
    sandboxEnabled: true,
    sandboxOptions: {
        allowScripts: false,
        allowForms: true,
        allowPopups: false,
        allowSameOrigin: true
    },
    
    // 资源路径配置
    workerSrc: "./pdf.worker.min.js",
    cMapUrl: "../cmaps/",
    standardFontDataUrl: "../standard_fonts/",
    iccUrl: "../iccs/",
    wasmUrl: "../wasm/"
});

// 事件监听
pdfh5.on("ready", function() {
    console.log("PDF加载完成,总页数:", this.totalNum);
});

pdfh5.on("annotationAdded", function(data) {
    console.log("新注释已添加:", data);
});

// 方法调用
pdfh5.setAnnotationEditorMode("HIGHLIGHT");
pdfh5.setProgressiveLoading(true, {chunkSize: 32768});

打赏榜单

  • JayLin ï¿¥6.66
  • 靓仔城 ï¿¥6.67
  • 南蓝 ï¿¥8.80
  • 我是太阳 ï¿¥29.99
  • *小波 ï¿¥1.00
  • *鑫 Â¥9.99
  • *手 Â¥9.99
  • *勇 ï¿¥19.99
  • *爷 Â¥5.00
  • *超 Â¥20.00
  • 3*Y Â¥5.00
  • *阳 Â¥5.00
  • **雄 Â¥5.00
  • A*r Â¥1.23
  • *客 Â¥5.00
  • *运 Â¥66.66
  • *è¾° Â¥30.00
  • *黎 Â¥6.66+Â¥5.00
  • **福 Â¥6.66
  • *🏀 Â¥6.66+Â¥1.00
  • *阳 Â¥10.00
  • 自闭中 Â¥16.66+Â¥16.00
  • *焕 Â¥6.66
  • *人 Â¥5.00
  • *。 Â¥5.20
  • 半*) Â¥5.00
  • *1 Â¥15.00
  • *蕾 Â¥16.66+Â¥8.80
  • *军 Â¥10.00
  • **强 Â¥58.88
  • E*y Â¥6.60
  • J*u Â¥13.00
  • A*a Â¥50.00
  • *东 Â¥8.80
  • j*y Â¥9.99
  • *宇 Â¥6.66
  • *涛 ï¿¥1.00
  • *. ï¿¥10.00
  • *☺ ï¿¥6.66
  • *霸 ï¿¥6.66
  • a*r ï¿¥20.00
  • 木槿(**耀) ï¿¥50.00