【epubjs】高亮、下划线、保存用户划线等功能实现&记录

前言

需要使用epubjs渲染epub文件,并且实现用户能在文本上划线、保存,并在下一次打开后渲染所划的线的功能。

前文:【vue2】纯前端实现本地的pdf/word/epub文件预览(包括pdf选中文字,epub高亮等)
在上一篇文章的基础上又扩展了一些功能。主要还是基于epubjs官方文档进行二次开发的。

正文

画下划线

如果已知某段文字的cfi,可以通过下面的方法画下划线

 // 在渲染器准备完成后执行
     this.rendition.on("rendered", async () => {
    
    
// 获取之前保存的选中内容的CFI范围
     const cfi = "epubcfi(/6/14[x_preface3.xhtml]!/4/6,/1:0,/1:47)"; // 假设这是之前保存的CFI范围
    this.rendition.annotations.underline(cfi, {
    
    }, () => {
    
    }, "", {
    
    
    "background-color": "rgba(255, 255, 0, 0.5)",
          });
        });

不过这个画的下划线是方框的样式。所以后面没有用这种方式

自定义样式的下划线

如果有多个位置需要渲染下划线,可以使用循环遍历。

       this.rendition.on("rendered", async () => {
    
    
          const cfiList = this.uniqueEntryPositions; //位置数组
          cfiList.forEach((cfi) => {
    
    
            const marker = document.createElement("span");
            marker.style.textDecoration = "underline"; // 设置下划线
            marker.style.textDecorationStyle = "dashed"; // 设置下划线样式
            marker.style.textDecorationColor = "#ffa500"; // 设置下划线颜色
            marker.style.lineHeight = "1.5"; // 设置行高为1.5倍
            marker.classList.add("my-marker");

            const range = this.rendition.getRange(cfi.entry_position); //这是cfi位置
            if (range) {
    
    
              range.surroundContents(marker);
            }
          });
        });

补充:自带的高亮效果一般,所以没有使用。应该是把underline改成Highlight就可以了。但是使用annotations的话,如何自定义样式我没有找到方法(或者忘了…)

保存用户下划线

(简单版)其实就是监听选中的时候,获取到的cfiRange 就是上面要使用的位置。调用后端接口把这个位置信息和文档的信息存入就可以了。

this.rendition.on("selected", (cfiRange, contents) => {
    
    } 

但是因为文档已渲染好的,所以无法及时把用户下划线实时渲染到页面上(或者有方法只是我不知道T T)

猜你喜欢

转载自blog.csdn.net/sinat_41838682/article/details/131866913
今日推荐