当前位置:网站首页>Wechat applet realizes PDF preview function - pdf.js (including source code analysis)
Wechat applet realizes PDF preview function - pdf.js (including source code analysis)
2022-07-22 15:43:00 【Amnesia patients_】
List of articles
Preface
I met a need some time ago , About pdf Preview of the file , Customer requirements are as follows :
- It can only be previewed in wechat applet , Can't call up local browser preview ;
- Users need to be forced to read 10s Only after reading , Then proceed to the next step ;
- Users cannot Download Preview pdf file ;
For some reason ( Ten thousand words are omitted here ), This project has H5 End and native wechat applet end , And they have the same business logic , Therefore, the best way is to design a set of schemes to apply to both ends , I made some attempts in the early stage , You can see This article , Finally decided to use pdf.js To meet business requirements .
One 、pdf.js What is it? ?
PDF.js from Mozilla Provide support . The goal is to create a common 、 be based on Web Standard platform , For parsing and rendering PDF.
Two 、 Use steps
1. Download library files
Go to pdf.js Of Official website Download library files , We can download any version , The latter applies to older browsers , The latter I downloaded here .
When the download is complete , Because of the limitation of wechat applet packaging , I put the library file on Tencent cloud server , If you want to test, you can contact me to provide test resources .
H5 It can be put locally , Directory as follows :
2. Usage mode
adopt web Under the table of contents viewer.html viewer + pdf File path preview pdf file
yourPath/web/viewer.html?file=pdfPath
Wechat applet —— Use web-view label
Code example :
//.wxml
<web-view src="{
{pdfView+pdfUrl}}" ></web-view>
//.js
data: {
// viewer.html Path to viewer
pdfView:"yourPath/web/viewer.html?file=",
// To preview pdf Path to file
pdfUrl:"http://play.li-stack.top:88/pdf/sjisr-3-2-36-42.pdf"
},
Running effect :
H5 End —— Use iframe label ( Use vue frame )
Code example :
<template>
<div>
<iframe :src="src" style="width: 100%;height: 100vh" ></iframe>
</div>
</template>
<script>
export default {
name: "myTestTwo",
data(){
return {
url:'http://play.li-stack.top:88/pdf/sjisr-3-2-36-42.pdf',
src:''
}
},
mounted() {
this.getUrl();
},
methods :{
getUrl:function () {
this.src = '/pdfplugin/web/viewer.html?file=' + this.url
}
}
}
</script>
<style scoped>
</style>
Running effect :
matters needing attention :
- web-view By default, the label is spread all over the screen , Will overwrite other components ;
- H5 Project use pdf.js Pay attention to cross domain issues ;
3. Change the source code
How to hide the top toolbar
In business requirements , Users cannot download pdf , The way I deal with it here is Hide the top toolbar
processing method :
- stay web Under folder viewer.html file , Found
<div class="toolbar">
- Change it to
<div class="toolbar" style="display:none">
So you can hide .
How to force users to read for a certain time
When users are forced to read , It must be pdf The file is loaded first , Just start the countdown .
processing method :
- stay viewer.js Find load function ( Direct search
load: function load(pdfDocument
location )) , Part of the code is as follows
load: function load(pdfDocument) {
var _this11 = this;
this.pdfDocument = pdfDocument;
pdfDocument.getDownloadInfo().then(function (_ref4) {
var length = _ref4.length;
_this11._contentLength = length;
_this11.downloadComplete = true;
_this11.loadingBar.hide();
firstPagePromise.then(function () {
_this11.eventBus.dispatch("documentloaded", {
source: _this11
});
});
});
// Add the following code
let mytime = 10
let timeout = setInterval(()=>{
console.log(" count down :",mytime)
if(mytime == 0){
clearTimeout(timeout)
}else{
--mytime
}
},1000)
……
}
- When pdf Running effect after loading successfully , You can achieve the page rendering effect by yourself
How to get pdf Total number of pages
Also in the above load Function , When pdf After loading ,pdfDocument Property contains the current pdf The total number of pages
processing method : It can be done by pdfDocument.numPages obtain
How to get pdf The current number of pages
If you can get the current number of pages , Also get the total number of pages , This can achieve the reading progress , Of course, there are many details about the reading progress , For example, the user quickly slides down , This is definitely not really reading , I won't subdivide here , Now let's get the current number of pages
processing method :
- It can be obtained in local storage , Key name :pdfjs.history;
- Find the function
function webViewerPageChanging(_ref15)
, Every time you swipe the screen , You will get the current number of pages after each page , The code is as follows :
function webViewerPageChanging(_ref15) {
var pageNumber = _ref15.pageNumber,
pageLabel = _ref15.pageLabel;
// Print it out here
console.log(pageNumber)
PDFViewerApplication.toolbar.setPageNumber(pageNumber, pageLabel);
PDFViewerApplication.secondaryToolbar.setPageNumber(pageNumber);
if (PDFViewerApplication.pdfSidebar.isThumbnailViewVisible) {
PDFViewerApplication.pdfThumbnailViewer.scrollThumbnailIntoView(pageNumber);
}
}
Send the total number of pages and the current number of pages to the applet
Sometimes you need H5 Communicate with applet , You can refer to This article
summary
This article is mainly aimed at wechat applet web-view label , stay H5 Use in ifream There will be a simpler way to get the number of pages ,
For example, you can try :
var iFrame = document.getElementById('iframe_id');
if( iFrame.contentDocument){
let currentPageNum = iFrame.contentDocument.getElementById('pageNumber').value;
}
// perhaps
document.querySelector('iframe id').contentWindow.PDFViewerApplication.page;
// perhaps
window.PDFViewerApplication.pdfViewer.currentPageNumber
Welcome to communicate actively ……
边栏推荐
- Succès de la construction du cluster expérimental tdengine
- [06] instruction jump: it turns out that if... Else is goto
- 旋转矩阵_百度百科
- Redis高可用原理 主从哨兵集群
- C语言输出所有水仙花数
- img.shape[-2:]/len(img.shape[-2:]):GeneralizedRCNN:original_image_sizes中的 torch._assert
- Summary of URL rules for real-time streaming of Hikvision, Dahua and yushila
- Tdengine learning notes
- 10个自动化测试框架,测试工程师用起来
- 优炫数据库上可以搭建Oracle RAC吗?
猜你喜欢
The difference between IO and NiO
mysql安装失败,不知道什么原因
ROS2自学笔记:TF坐标管理
“码”上赢门票——TDengine开发者大会购票福利第二弹
AutoLabel(自动标签)
ADB 命令结合 monkey 的简单使用,超详细
Basic concept of Nacos and single machine startup
temporal database
Reasons for driving voltage deviation caused by high voltage differential probe
Deep learning 8 deep model optimization and regularization
随机推荐
Cloud native
GeneralizedRCNN:features = OrderedDict([(“0“, features)])
[fiddlertx plug-in] use Fiddler to capture Tencent classroom video download
Play with canoe, a complete collection of blog directories
玩转CANoe,博客目录大全
GeneralizedRCNN:features = OrderedDict([(“0“, features)])
img.shape[-2:]/len(img.shape[-2:]):GeneralizedRCNN:original_image_sizes中的 torch._assert
Tensorboard安装与使用
Nifi 1.16.3 updates and bugs used in production.
Machine learning notes - overview of machine learning system design process
指数滑动平均法_百度百科
Reasons for driving voltage deviation caused by high voltage differential probe
PLT draw and save the results
信息系统项目管理师必背核心考点(四十八)合同类型的选择
优炫数据库上可以搭建Oracle RAC吗?
Barcode (bar code)
Joint search set framework
Tdengine experimental cluster establishment success
Ubuntu common operation and maintenance commands
2022.7.21 special matrix compression