前端实现预览PDF
下载包 npm install react-pdf
我使用的是react-pdf@5.7.2版本
以下例子使用的是react创建的项目
直接上代码=>cv可用,保证高效
1.新增依赖
yarn add react-pdf@5.7.2
npm install react-pdf@5.7.2
2.导出js
/*
1.进入该组件时,通过路由传递path进来,形如:
history.push({ pathname: '/pdfPreview', query: { path } })
2.进入该组件时,通过props传递path进来,形如:
{ filePath :{ path :''} }
*/
import React, { useState } from 'react';
import { Spin, Tooltip, Input } from 'antd';
import {
LeftOutlined,
RightOutlined,
PlusCircleOutlined,
MinusCircleOutlined,
FullscreenOutlined,
FullscreenExitOutlined,
} from '@ant-design/icons';
import styles from './index.less';
import { Document, Page, pdfjs } from 'react-pdf';
// pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
const pdfjsWorker = require('pdfjs-dist/build/pdf.worker.entry'); // 引用本地的
pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker;
const PreviewPDF = (props: any) => {
const { location, filePDF, filePath } = props; // 方法1: 作为组件传入的值, 取出path(pdf地址)
// const { path }: any = location.query; // 方法2: 作为路由跳转的传入的值, 取出path(pdf地址)
const path = filePath;
const [pageNumber, setPageNumber] = useState(1);
const [pageNumberInput, setPageNumberInput] = useState(1);
const [pageNumberFocus, setPageNumberFocus] = useState(false);
const [numPages, setNumPages] = useState(1);
const [pageWidth, setPageWidth] = useState(1200);
const [fullscreen, setFullscreen] = useState(false);
const onDocumentLoadSuccess = ({ numPages }: any) => {
setNumPages(numPages);
};
const lastPage = () => {
if (pageNumber == 1) return;
const page = pageNumber - 1;
setPageNumber(page);
setPageNumberInput(page);
};
const nextPage = () => {
if (pageNumber === numPages) return;
const page = pageNumber + 1;
setPageNumber(page);
setPageNumberInput(page);
};
const onPageNumberFocus = () => {
setPageNumberFocus(true);
};
const onPageNumberBlur = () => {
setPageNumberFocus(false);
setPageNumberInput(pageNumber);
};
const onPageNumberChange = (e: any) => {
let { value } = e.target;
value = value <= 0 ? 1 : value;
value = value >= numPages ? numPages : value;
setPageNumberInput(value);
};
const toPage = (e: any) => {
setPageNumber(Number(e.target.value));
};
const pageZoomOut = () => {
if (pageWidth <= 1200) return;
const width = pageWidth * 0.8;
setPageWidth(width);
};
const pageZoomIn = () => {
const width = pageWidth * 1.2;
setPageWidth(width);
};
const pageFullscreen = () => {
if (fullscreen) {
setFullscreen(false);
setPageWidth(1200);
} else {
setFullscreen(true);
setPageWidth(window.screen.width - 40);
}
};
return (
<div className={`${styles.view}`}>
<div className={styles.pageContainer}>
<Document
file={path}
onLoadSuccess={onDocumentLoadSuccess}
loading={<Spin size="large" />}
options={{
// cMapUrl: `https://cdn.jsdelivr.net/npm/pdfjs-dist@${pdfjs.version}/cmaps/`, // 解决打印不显示的问题,必要的
cMapUrl:'./cmaps/', // public路径 下载到本地
cMapPacked: true,
optimizedImages: true,
// disableWorker: true
}}
>
<Page pageNumber={pageNumber} width={pageWidth} loading={<Spin size="large" />} />
</Document>
</div>
<div className={styles.pageTool}>
<Tooltip title={pageNumber == 1 ? '已是第一页' : '上一页'}>
<LeftOutlined className={styles.outlined} onClick={lastPage} />
</Tooltip>
<Input
value={pageNumberFocus ? pageNumberInput : pageNumber}
onFocus={onPageNumberFocus}
onBlur={onPageNumberBlur}
onChange={onPageNumberChange}
onPressEnter={toPage}
type="number"
/>
/ {numPages}
<Tooltip title={pageNumber == numPages ? '已是最后一页' : '下一页'}>
<RightOutlined className={styles.outlined} onClick={nextPage} />
</Tooltip>
<Tooltip title="放大">
<PlusCircleOutlined className={styles.outlined} onClick={pageZoomIn} />
</Tooltip>
<Tooltip title="缩小">
<MinusCircleOutlined className={styles.outlined} onClick={pageZoomOut} />
</Tooltip>
<Tooltip title={fullscreen ? '恢复默认' : '适合窗口'}>
{fullscreen ? (
<FullscreenExitOutlined className={styles.outlined} onClick={pageFullscreen} />
) : (
<FullscreenOutlined className={styles.outlined} onClick={pageFullscreen} />
)}
</Tooltip>
</div>
</div>
);
};
export default PreviewPDF;
3.cv Css
.view {
display: flex;
justify-content: center;
height: 100%;
// height: 100vh;
padding: 20px 0;
// background: #444;
.pageContainer {
width: max-content;
max-width: 100%;
// overflow-y: scroll;
box-shadow: rgba(0, 0, 0, 0.2) 0px 2px 4px 0px;
}
.pageTool {
position: absolute;
bottom: 60px;
left: -20px;
padding: 8px 15px;
color: white;
background: rgb(66, 66, 66);
// background-color: #fff;
border-radius: 15px;
.outlined {
margin: 0 10px;
user-select: none;
}
input {
display: inline-block;
width: 50px;
height: 24px;
margin-right: 10px;
text-align: center;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
}
input[type='number'] {
-moz-appearance: textfield;
}
}
}
4.引用组件
import PreviewPDF from './PreviewPDF';
/**
*
* @param file 数据返回的值,就是预览的pdf的path值
* 此处写的一个方法调用,获取path值,进行操作
*/
const handlePreview = async(file: any) => {
await setFilePath(file.url);
setVisiblePDF(true); // 组件方式预览
// const prefix = `${window.location.protocol}//${window.location.host}`;
// window.open(`${prefix}/#/binjiang-publicpower/previewPDF?path=${file.url}`); // 路由的方式预览, 新窗口打开
};
<Modal width={1400} destroyOnClose footer={false} visible={visiblePDF} onCancel={() => setVisiblePDF(false)} title={''}>
<PreviewPDF filePath={filePath} />
</Modal>
其实可以后端返回的链接添加参数(因为有些后端返回的是下载的链接),用自带的浏览器打开
默认的响应头是attachment,这里要改成inline,变成下载的
<a href={`${file.fileUrl || fileUrl}?dispositionType=inline`} target="_target"></a>
前端实现预览PDF的更多相关文章
- pdfjs-dist 后端返回文件前端实现预览pdf
pdfjs-dist锁定版本号2.2.228,别的都不太好使,各种各样的报错 不锁定的时候升高版本出现pdf预览不了 引用的时候 import pdfjsLib from 'pdfjs-dist/bu ...
- 使用pdf.js实现前端页面预览pdf文档,解决了跨域请求
pdf.js主要包含两个库文件,一个pdf.js和一个pdf.worker.js,,一个负责API解析,一个负责核心解析 官网地址:http://mozilla.github.io/pdf.js/ 下 ...
- 前端实现在线预览pdf、word、xls、ppt等文件
最近在做一个公司的资源管理系统,一些知识小记一下. 1.前端实现pdf文件在线预览功能 方式一.pdf文件理论上可以在浏览器直接打开预览但是需要打开新页面.在仅仅是预览pdf文件且UI要求不高的情况下 ...
- layui.js---layer;;前端预览pdf
layui.js---layer;;前端预览pdf 1.必须引入layui.js 2.uul是pdf文件地址 3.触发function函数:小于号button onclick="pdfsee ...
- 前端实现在线预览pdf、docx、xls、ppt等文件
思路:前台将各种格式的附件上传到服务器----后台通过方法将这些格式的文件转化成图片,前台通过放映ppt的方式将其展示在页面上. 关键点:reveal.js 参考文章:https://www.awes ...
- 前端实现预览ppt,word,xls,pdf文件
1.前端实现pdf文件在线预览功能 ps:刚好工作上有这个需求,所以到处找了一下处理方案,大家有需要可以试一下这几种方案,找到合适自己的 方式一. pdf文件理论上可以在浏览器直接打开预览但是需要打开 ...
- 前端使用pdf.js预览pdf文件
现在的浏览器基本都支持直接把pdf文件拖到浏览器就可以打开了,不用安装额外的插件.但是不同的浏览器显示的页面不一样.如果我们想在网页上统一预览pdf怎样实现呢? Mozilla开源了一个插件pdf.j ...
- 前端使用pdf.js预览pdf文件,超级简单
现在的浏览器基本都支持直接把pdf文件拖到浏览器就可以打开了,不用安装额外的插件.但是不同的浏览器显示的页面不一样.如果我们想在网页上统一预览pdf怎样实现呢? Mozilla开源了一个插件pdf.j ...
- fis3+vue+pdf.js制作预览PDF文件或其他
人生第一篇博客,的确有点紧张,但有些许兴奋,因为这对于我来说应该是一个好的开始,以此励志在技术的道路上越走越远. 看过了多多少少的技术博客,给自己带来了很多技术上的收获,也因此在想什么时候自己也可以赠 ...
- JS展示预览PDF。
刚好遇到需求,需要在手机端--展示一个电子收据,电子收据返回是PDF格式的,所以需要在前端上面去做PDF预览. 在学习过程中,了解到一种很简单,不需要任何插件的方法做PDF预览,但是这方法有局限性. ...
随机推荐
- 从右边开始寻找整数的第k位
从右边开始寻找整数的第k位 Implement match_k, which takes in an integer k and returns a function that takes in a ...
- dotnet C# 根据椭圆长度和宽度和旋转角计算出椭圆中心点的方法
本文来告诉大家如何根据椭圆长度和宽度和旋转角计算出椭圆中心点的方法 方法很简单,请看代码 /// <summary> /// 辅助进行椭圆点计算的类 /// </summary> ...
- 【简说Python WEB】用户身份验证--Werkzeug
目录 [简说Python WEB]用户身份验证--Werkzeug Flask的security扩展 使用Werkzeug生成密码散列值 系统环境:Ubuntu 18.04.1 LTS Python使 ...
- docker-compose搭建的Mysql主从复制
设置前注意下面几点: 1)要保证同步服务期间之间的网络联通.即能相互ping通,能使用对方授权信息连接到对方数据库(防火墙开放3306端口). 2)关闭selinux. 3)同步前,双方数据库中需要同 ...
- U.2与M.2接口
U.2接口 U.2接口别称SFF-8639,是由固态硬盘形态工作组(SSD Factor Work Group)推出的接口规范.U.2接口不但能支持SATA-Express(一种PCI-E与SATA混 ...
- PCI-E与SATA SSD
为什么要采用PCI-E通道 目前在固态硬盘SSD中,有一部分采用了SATA3.0接口,而一些高端的固态硬盘则采用了PCI-E接口.那么为什么高端固态硬盘要采用PCI-E接口呢?为了弄清楚这个问题,先看 ...
- nim 4. 模块
看了一下nim的模块系统,真的非常简洁. 1) 一个nim文件就是一个模块 2) 通过import 引入模块,引入的时候不需要带扩展名, 比如有个模块 mod1.nim, 引入的时候: import ...
- 当字符遇上 scanf() 要当心
当字符遇上 scanf() 要当心 看一下程序 char ch1,ch2; printf("请输入ch1,ch2的值:"); scanf("%c %c",&am ...
- C 语言编程 — 指令行参数
目录 文章目录 目录 前文列表 命令行参数 前文列表 <程序编译流程与 GCC 编译器> <C 语言编程 - 基本语法> <C 语言编程 - 基本数据类型> < ...
- 带你阅读Naive Ui Admin后台管理源码,并手撸JS版本
Naive Ui Admin 是一个基于 Vue3.0.Vite. Naive UI.TypeScript 的中后台解决方案,它使用了最新的前端技术栈,并提炼了典型的业务模型,页面,包括二次封装组件. ...