
Security News
GitHub Actions Checkout Now Blocks Risky pull_request_target Checkouts
GitHub Actions checkout now blocks risky pull_request_target checkouts by default to help prevent pwn request supply chain attacks.
viquard-preview
Advanced tools
一个功能强大的文档预览组件库,支持 PDF、Word、Excel、图片、代码、Markdown 等多种格式。基于 Viquard UI 和现代 Web 技术构建。
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"
/>
</>
);
}
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
open | boolean | - | 必需。是否打开预览窗口 |
onClose | () => void | - | 必需。关闭预览窗口的回调函数 |
file | PreviewFileSource | - | 必需。文件源(URL、Blob、File 或 ID) |
mode | 'modal' | 'drawer' | 'inline' | 'fullscreen' | 'modal' | 预览模式 |
size | 'small' | 'medium' | 'large' | 'auto' | 'large' | 尺寸预设(仅在 mode 为 modal/drawer 时生效) |
customSize | PreviewCustomSize | - | 自定义尺寸(覆盖 size 预设) |
enableAnnotation | boolean | false | 启用 PDF 注释功能 |
readonly | boolean | false | 只读模式,禁用编辑、下载、导出等功能 |
pdfOptions | PdfOptions | - | PDF 特定配置选项 |
toolbarExtra | ReactNode | - | 自定义工具栏额外内容 |
onLoadStateChange | (state: LoadState) => void | - | 加载状态变化回调 |
onError | (error: Error) => void | - | 错误回调 |
modal - 模态框模式,居中显示,带遮罩层drawer - 抽屉模式,从侧边滑出inline - 内联模式,嵌入到页面中fullscreen - 全屏模式,占据整个屏幕small - 小尺寸(约 400px)medium - 中等尺寸(约 600px)large - 大尺寸(约 800px)auto - 自动尺寸,根据内容调整customSize={{
width: '90vw', // 宽度(支持 px、%、vw 等单位)
height: '90vh', // 高度
maxWidth: '1200px', // 最大宽度
maxHeight: '800px', // 最大高度
}}
pdfOptions={{
defaultScale: 1.5, // 默认缩放比例
minScale: 0.5, // 最小缩放比例
maxScale: 3.0, // 最大缩放比例
showThumbnails: true, // 是否显示缩略图侧边栏
}}
支持四种文件源类型:
{
type: 'url',
url: 'https://example.com/file.pdf',
fileName: 'file.pdf', // 可选
mimeType: 'application/pdf', // 可选
}
{
type: 'blob',
blob: pdfBlob,
fileName: 'document.pdf', // 可选
mimeType: 'application/pdf', // 可选
}
{
type: 'file',
file: fileInput.files[0],
}
{
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',
};
},
}
当 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 查看器还支持文本框批注:
当 readonly={true} 时,预览器将进入只读模式,禁用所有编辑和导出功能:
enableAnnotation={true} 也会被禁用)只读模式下,用户可以:
但无法:
预览器工具栏提供以下功能:
你可以注册自定义查看器来支持新的文件格式:
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
);
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();
管理预览器状态(页码、缩放等):
import { usePreviewState } from 'viquard-preview';
const { state, setPage, setScale, setRotation } = usePreviewState(defaultScale);
文件上传 Hook:
import { useFileUpload } from 'viquard-preview';
const { files, handleFileSelect, clearFiles } = useFileUpload({
accept: '.pdf,.doc,.docx',
multiple: false,
});
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';
文件选择触发组件:
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' }}
/>
<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);
}}
/>
所有类型定义都已导出,支持完整的 TypeScript 类型提示:
import type {
FilePreviewProps,
PreviewFileSource,
PreviewWindowMode,
PreviewSizePreset,
PreviewCustomSize,
LoadState,
ViewerType,
PdfOptions,
Annotation,
AnnotationType,
} from 'viquard-preview';
FAQs
一个功能强大的文档预览组件库,支持PDF、Word、Excel、图片、代码、Markdown等多种格式
The npm package viquard-preview receives a total of 5 weekly downloads. As such, viquard-preview popularity was classified as not popular.
We found that viquard-preview demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

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.

Security News
GitHub Actions checkout now blocks risky pull_request_target checkouts by default to help prevent pwn request supply chain attacks.

Product
Socket now supports Custom Roles and Repository Access Permissions so organizations can control who can access specific repositories and actions.

Product
Socket MCP now lets AI assistants review org alerts, investigate threats using the Socket threat feed, and inspect package files in addition to dependency scoring.