使用pdf.js渲染pdf时如何重设单词的样式? [英] How can I restyle a word when rendering a pdf with pdf.js?
问题描述
当我用pdf.js运行pdf时,我希望能够重新设置某些单词的样式(例如,突出显示)吗?
When I runder a pdf with pdf.js I would like to be able to restyle some words (e.g. highlight) is this possible?
推荐答案
是的,在使用PDF.js时可以突出显示单词
Yes, it is possible to highlight words while working with PDF.js
页面包含
- 画布(用于呈现的内容)
- HTMLDivElement(用于未渲染的文本内容)
您可以使用后一种来选择文本元素.
you can use the latter one to select text elements.
可以访问您的选择API 浏览器,您可以通过document.getSelection()
进行选择.
Having access to the Selection API on your browser, you can get the selection via document.getSelection()
.
以下代码演示了如果所选文本没有(内部)跨越多个HTMLElement时如何做到这一点:
The following code demonstrates how to do that if the selected text does not (internally) span across multiple HTMLElements:
var s = document.getSelection();
var oldstr = s.anchorNode.textContent;
var textBeforeSelection = oldstr.substr(0, s.anchorOffset);
var textInsideSelection = oldstr.substr(s.anchorOffset, s.focusOffset - s.anchorOffset);
var textAfterSelection = oldstr.substr(s.focusOffset, oldstr.length - s.focusOffset);
foo.anchorNode.parentElement.innerHTML
= textBeforeSelection
+ "<span class='highlight'>"
+ textInsideSelection
+ "</span>"
+ textAfterSelection;
对于跨越多个(内部)HTMLElement的选择,您可能可以通过依次调用nextSibling
直到到达s.focusNode
来遍历从s.anchorNode
开始的DOM.
For a selection that spans multiple (internal) HTMLElements you might be able to traverse the DOM starting at s.anchorNode
by successively calling nextSibling
until you reach at s.focusNode
.
我说可能,因为元素在文档中的放置顺序可以与视图中的顺序不同.
I say might, because elements can be positioned in the document in a different order than the one they have on the view.
假设s.anchorNode
不是s.focusNode
,
-
s.anchorNode
将从0突出显示为s.anchorOffset
从 -
s.focusNode
和 - 它们之间的所有节点都可以完全突出显示
s.focusOffset
到节点末尾的s.anchorNode
would be highlighted from 0 tos.anchorOffset
s.focusNode
froms.focusOffset
until the end of the node and- all nodes between them could be highlighted entirely
这对文本节点有效(或至少对可能有效)-通过用突出显示范围包围每个非文本节点,可以将该思想扩展到非文本节点.
This works (or at least might work) for text nodes - the idea could be extended to non-text nodes by surrounding each non-text node with the highlighting span.
这篇关于使用pdf.js渲染pdf时如何重设单词的样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!