🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

viquard-preview

Package Overview
Dependencies
Maintainers
1
Versions
4
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

viquard-preview

一个功能强大的文档预览组件库,支持PDF、Word、Excel、图片、代码、Markdown等多种格式

latest
npmnpm
Version
1.0.3
Version published
Weekly downloads
5
150%
Maintainers
1
Weekly downloads
 
Created
Source

viquard-preview - 文档预览组件库

一个功能强大的文档预览组件库,支持 PDF、Word、Excel、图片、代码、Markdown 等多种格式。基于 Viquard UI 和现代 Web 技术构建。

功能特性

  • 多格式支持:PDF、Word、Excel、图片、代码、Markdown 等
  • PDF 文件预览:支持 URL、Blob、文件上传
  • 页码跳转和导航:快速定位页面
  • 缩放控制:放大/缩小/适应宽度/适应页面
  • 缩略图侧边栏:快速预览和跳转
  • 多种预览模式:Modal、Drawer、Inline、Fullscreen
  • PDF 注释功能:支持多种注释工具和文本框批注
  • 只读模式:禁用编辑、下载、导出等功能
  • Markdown 转 PDF:纯前端实现,无需后端
  • Word 转 PDF:纯前端实现,无需后端
  • Excel 预览:支持分页、搜索和工作表切换
  • 代码高亮:支持多种编程语言
  • 响应式设计:支持 Light/Dark 主题
  • 插件化架构:可注册自定义查看器
  • TypeScript 支持:完整的类型定义

安装

作为 npm 包使用

npm install viquard-preview
# 或
yarn add viquard-preview
# 或
pnpm add viquard-preview

必需依赖

npm install react react-dom viquard-ui

可选依赖(按需安装)

根据你需要的功能,可以选择性安装以下依赖:

# PDF 预览功能
npm install pdfjs-dist

# Word 文档预览
npm install mammoth

# Excel 预览
npm install xlsx

# Markdown 预览(代码高亮、数学公式)
npm install react-markdown remark-gfm remark-math rehype-katex rehype-prism rehype-prism-plus rehype-raw prismjs katex

# 图片编辑功能
npm install react-easy-crop html2canvas

# PDF 导出功能
npm install jspdf pdf-lib

# 其他工具
npm install jszip d3-sankey mermaid

快速开始

import { FilePreview } from 'viquard-preview';
import 'viquard-preview/styles';
import 'viquard-ui/style.css';
import { useState } from 'react';

function App() {
  const [open, setOpen] = useState(false);

  return (
    <>
      <button onClick={() => setOpen(true)}>预览文档</button>
      <FilePreview
        open={open}
        onClose={() => setOpen(false)}
        file={{
          type: 'url',
          url: '/path/to/file.pdf',
          fileName: '文档.pdf',
        }}
        mode="modal"
      />
    </>
  );
}

API 文档

FilePreview 组件

Props

属性类型默认值说明
openboolean-必需。是否打开预览窗口
onClose() => void-必需。关闭预览窗口的回调函数
filePreviewFileSource-必需。文件源(URL、Blob、File 或 ID)
mode'modal' | 'drawer' | 'inline' | 'fullscreen''modal'预览模式
size'small' | 'medium' | 'large' | 'auto''large'尺寸预设(仅在 mode 为 modal/drawer 时生效)
customSizePreviewCustomSize-自定义尺寸(覆盖 size 预设)
enableAnnotationbooleanfalse启用 PDF 注释功能
readonlybooleanfalse只读模式,禁用编辑、下载、导出等功能
pdfOptionsPdfOptions-PDF 特定配置选项
toolbarExtraReactNode-自定义工具栏额外内容
onLoadStateChange(state: LoadState) => void-加载状态变化回调
onError(error: Error) => void-错误回调

预览模式 (mode)

  • modal - 模态框模式,居中显示,带遮罩层
  • drawer - 抽屉模式,从侧边滑出
  • inline - 内联模式,嵌入到页面中
  • fullscreen - 全屏模式,占据整个屏幕

尺寸预设 (size)

  • small - 小尺寸(约 400px)
  • medium - 中等尺寸(约 600px)
  • large - 大尺寸(约 800px)
  • auto - 自动尺寸,根据内容调整

自定义尺寸 (customSize)

customSize={{
  width: '90vw',      // 宽度(支持 px、%、vw 等单位)
  height: '90vh',     // 高度
  maxWidth: '1200px', // 最大宽度
  maxHeight: '800px', // 最大高度
}}

PDF 选项 (pdfOptions)

pdfOptions={{
  defaultScale: 1.5,    // 默认缩放比例
  minScale: 0.5,         // 最小缩放比例
  maxScale: 3.0,         // 最大缩放比例
  showThumbnails: true,  // 是否显示缩略图侧边栏
}}

文件源类型 (PreviewFileSource)

支持四种文件源类型:

1. URL 文件

{
  type: 'url',
  url: 'https://example.com/file.pdf',
  fileName: 'file.pdf',        // 可选
  mimeType: 'application/pdf', // 可选
}

2. Blob 文件

{
  type: 'blob',
  blob: pdfBlob,
  fileName: 'document.pdf',   // 可选
  mimeType: 'application/pdf', // 可选
}

3. File 对象

{
  type: 'file',
  file: fileInput.files[0],
}

4. ID 解析器(自定义加载逻辑)

{
  type: 'id',
  id: 'file-123',
  resolver: async (id: string) => {
    const response = await fetch(`/api/files/${id}`);
    const blob = await response.blob();
    return {
      type: 'blob',
      blob,
      fileName: 'file.pdf',
    };
  },
}

PDF 注释功能

enableAnnotation={true} 时,PDF 查看器支持以下注释功能:

注释工具类型

  • select - 选择工具,用于选择和编辑已有注释
  • rect - 矩形工具
  • circle - 圆形工具
  • ellipse - 椭圆工具
  • line - 直线工具
  • arrow - 箭头工具(支持多种箭头样式)
  • highlight - 高亮工具
  • pen - 画笔工具(支持压力感应和可变宽度)
  • comment - 批注工具(支持文字选中和批注)

注释属性

每个注释包含以下属性:

interface Annotation {
  id: string;                    // 唯一标识符
  page: number;                  // 页码(从 1 开始)
  type: AnnotationType;          // 注释类型
  rect: { x, y, width, height }; // 归一化坐标矩形(0-1)
  path?: string;                 // SVG 路径(画笔工具)
  points?: Array<{x, y}>;        // 点序列(直线、箭头)
  content?: string;              // 注释内容
  selectedText?: string;          // 选中的文字(批注)
  color?: string;                // 颜色
  borderWidth?: number;          // 边框宽度
  borderColor?: string;          // 边框颜色
  showBorder?: boolean;          // 是否显示边框
  filled?: boolean;              // 是否填充
  fillColor?: string;            // 填充颜色
  borderRadius?: number;          // 圆角半径(矩形)
  lineWidth?: number;            // 线条宽度(直线、箭头)
  arrowStyle?: string;           // 箭头样式(箭头工具)
  penStyle?: string;             // 画笔样式(画笔工具)
  createdAt?: string;           // 创建时间
}

注释操作

  • 创建:选择注释工具,在 PDF 上绘制
  • 编辑:使用选择工具点击注释,可拖拽调整位置和大小
  • 删除:选择注释后按 Delete 键或右键菜单删除
  • 样式调整:右键菜单可修改颜色、边框、填充等属性
  • 批注:使用批注工具选中文字,添加批注内容

文本框批注功能

PDF 查看器还支持文本框批注:

  • 文本输入:在 PDF 上添加文本框
  • 样式设置:字体、大小、颜色、背景色、边框
  • LaTeX 支持:支持数学公式输入
  • 富文本:支持粗体、斜体等格式

只读模式

readonly={true} 时,预览器将进入只读模式,禁用所有编辑和导出功能:

  • 禁用 PDF 注释功能(即使 enableAnnotation={true} 也会被禁用)
  • 禁用文本框批注功能
  • 隐藏下载按钮
  • 隐藏导出按钮(导出图片、导出带注释的PDF)
  • 隐藏重命名按钮
  • 禁用注释工具栏和文本框工具栏

只读模式下,用户可以:

  • 查看文档
  • 翻页
  • 缩放
  • 搜索
  • 查看缩略图

但无法:

  • 添加或编辑注释
  • 下载文件
  • 导出文件
  • 重命名文件

工具栏功能

预览器工具栏提供以下功能:

  • 页码导航:上一页/下一页,页码跳转
  • 缩放控制:放大、缩小、适应宽度、适应页面
  • 旋转:顺时针旋转 90 度
  • 下载:下载当前文件(只读模式下禁用)
  • 全屏:进入/退出全屏模式
  • 搜索:PDF 文本搜索(仅 PDF)
  • 缩略图:显示/隐藏缩略图侧边栏(仅 PDF)
  • 大纲:显示文档大纲(PDF、Word、Markdown)

查看器注册系统

你可以注册自定义查看器来支持新的文件格式:

import { viewerRegistry } from 'viquard-preview';
import { MyCustomViewer } from './MyCustomViewer';

// 注册自定义查看器
viewerRegistry.register(
  {
    id: 'my-custom-viewer',
    name: '自定义查看器',
    supportedMimeTypes: ['application/custom'],
    supportedExtensions: ['custom'],
    priority: 10, // 优先级,数字越大优先级越高
    features: ['pagination', 'zoom'],
  },
  MyCustomViewer
);

ViewerRegistry API

import { viewerRegistry } from 'viquard-preview';

// 注册查看器
viewerRegistry.register(metadata, component);

// 注销查看器
viewerRegistry.unregister(viewerId);

// 根据 MIME 类型或文件名获取查看器
const viewer = viewerRegistry.getViewer(mimeType, fileName);

// 根据 ID 获取查看器
const viewer = viewerRegistry.getViewerById(viewerId);

// 检查是否支持某文件类型
const supported = viewerRegistry.isSupported(mimeType, fileName);

// 获取所有已注册的查看器
const allViewers = viewerRegistry.getAllViewers();

Hooks

usePreviewState

管理预览器状态(页码、缩放等):

import { usePreviewState } from 'viquard-preview';

const { state, setPage, setScale, setRotation } = usePreviewState(defaultScale);

useFileUpload

文件上传 Hook:

import { useFileUpload } from 'viquard-preview';

const { files, handleFileSelect, clearFiles } = useFileUpload({
  accept: '.pdf,.doc,.docx',
  multiple: false,
});

usePdfDocument

PDF 文档加载 Hook(仅 PDF):

import { usePdfDocument } from 'viquard-preview';

const { document, loading, error } = usePdfDocument(source);

工具函数

import {
  normalizeFileSource,    // 归一化文件源
  downloadFile,           // 下载文件
  createBlobUrl,          // 创建 Blob URL
  revokeBlobUrl,          // 撤销 Blob URL
  mimeToViewerType,       // MIME 类型转查看器类型
  extToMimeType,          // 扩展名转 MIME 类型
  getFileInfo,            // 获取文件信息
  getFileExtension,       // 获取文件扩展名
} from 'viquard-preview';

FilePreviewTrigger 组件

文件选择触发组件:

import { FilePreviewTrigger } from 'viquard-preview';

<FilePreviewTrigger
  onFileSelect={(file) => {
    setFileSource({ type: 'file', file });
    setOpen(true);
  }}
  accept=".pdf,.doc,.docx"
  multiple={false}
>
  <button>选择文件</button>
</FilePreviewTrigger>

使用示例

基础预览

<FilePreview
  open={open}
  onClose={() => setOpen(false)}
  file={{ type: 'url', url: '/file.pdf', fileName: 'file.pdf' }}
/>

自定义尺寸和模式

<FilePreview
  open={open}
  onClose={() => setOpen(false)}
  file={fileSource}
  mode="drawer"
  customSize={{ width: '90vw', height: '90vh' }}
/>

启用 PDF 注释

<FilePreview
  open={open}
  onClose={() => setOpen(false)}
  file={pdfFile}
  enableAnnotation={true}
  pdfOptions={{ defaultScale: 1.5 }}
/>

只读模式

<FilePreview
  open={open}
  onClose={() => setOpen(false)}
  file={pdfFile}
  readonly={true}
/>

自定义工具栏

<FilePreview
  open={open}
  onClose={() => setOpen(false)}
  file={fileSource}
  toolbarExtra={
    <button onClick={handleCustomAction}>自定义操作</button>
  }
/>

监听加载状态

<FilePreview
  open={open}
  onClose={() => setOpen(false)}
  file={fileSource}
  onLoadStateChange={(state) => {
    if (state === 'loading') {
      console.log('正在加载...');
    } else if (state === 'success') {
      console.log('加载成功');
    }
  }}
  onError={(error) => {
    console.error('加载失败:', error);
  }}
/>

技术栈

  • React 18+ - UI 框架
  • TypeScript - 类型安全
  • Vite - 构建工具
  • Viquard UI - UI 组件库
  • pdf.js - PDF 渲染
  • mammoth - Word 文档解析
  • xlsx - Excel 文件处理
  • react-markdown - Markdown 渲染
  • mermaid - 图表渲染
  • katex - 数学公式渲染

类型定义

所有类型定义都已导出,支持完整的 TypeScript 类型提示:

import type {
  FilePreviewProps,
  PreviewFileSource,
  PreviewWindowMode,
  PreviewSizePreset,
  PreviewCustomSize,
  LoadState,
  ViewerType,
  PdfOptions,
  Annotation,
  AnnotationType,
} from 'viquard-preview';

Keywords

preview

FAQs

Package last updated on 20 Nov 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts