gpt4 book ai didi

javascript - 如何实现 ctrl 单击行为以从 web 应用程序中嵌入的 pdf 复制文本?

转载 作者:行者123 更新时间:2023-11-28 19:45:21 26 4
gpt4 key购买 nike

我要求网络应用程序实现以下行为:

在浏览器中显示嵌入 PDF 对象的 Web 表单后,用户需要能够通过 ctrl + 鼠标单击 之后,所选文本将被复制到显示嵌入 PDF 对象的同一 Web 表单中的输入字段。

是否有 API(最好是开源的)可以实现此行为?我可以使用 JSP、JSF、PrimeFaces、Javascript 或 HTML5 等技术来满足此要求吗?我该如何做到这一点?

最佳答案

在示例中我将使用

  • PDF.js
  • JSF 2.2(什么版本并不重要,但最好是 2.x)
  • PrimeFaces(用于 inputField 或 textArea)* 可选

步骤:

  • 下载并集成 PDF.js
  • 按 CTRL 注册事件

下载并集成 PDF.js

Download PDF.js ,下载完成后解压,你会看到如下文件夹层次

.
├── LICENSE
├── build
│   ├── pdf.js
│   └── pdf.worker.js
└── web
├── cmaps/
├── compatibility.js
├── compressed.tracemonkey-pldi-09.pdf
├── debugger.js
├── images/
├── l10n.js
├── locale/
├── viewer.css
├── viewer.html
└── viewer.js

假设您的 JSF 项目在 webapp 中有一个 resources 文件夹,请将以下文件从 web 文件夹(从解压缩的文件)复制到 resources 其中它们看起来像这样:

webapp/resources 文件夹

├── css
│   └── viewer.css (web/viewer.css)
├── images
│   └── pdfjs
│   ├── ** All the images inside (web/images)
└── js
└── pdfjs
├── compatibility.js (web/compatibility.js)
├── l10n.js (web/l10n.js)
├── pdf.js (web/pdf.js)
├── pdf.worker.js (web/pdf.worker.js)
└── viewer.js (web/viewer.js)

编辑viewer.css以解析所有必需的图像,将每个url替换为

“#{resource['images/pdfjs/correspondingImageName']}”

这是一个完整的解决方案 viewer.css

使用viewer.html(来自zip的web/viewer.html)的内容创建xhtml文件,该文件代表查看器标记,这就是我将查看器与所有html一起使用的原因5 标记是能够选择文本的,而不是像 canvas only example

这是将 viewer.html 完整复制到 viewer.xhml 的示例

请注意,最后我按以下顺序包含了库:

<h:outputScript name="js/pdfjs/compatibility.js" target="head" /> 
<h:outputScript name="js/pdfjs/l10n.js" target="head" />
<h:outputScript name="js/pdfjs/pdf.js" target="head" />
<h:outputScript name="js/pdfjs/viewer.js" target="head" />

要运行 PDF.js,您需要指定两件事:pdf.worder.js 位置和 pdfURL(请参阅viewer.xhml)

 <script>
var DEFAULT_URL = "#{pdfURL}"; //pdf should be hosted on your domain name (ajaxly loaded)
PDFJS.workerSrc = "#{resource['js/pdfjs/pdf.worker.js']}";
</script>

按 CTRL 注册事件

定义一个inputTextinputTextArea

<p:inputTextarea id="inputTextArea" />

现在注册一个 keydown 事件或任何合适的事件,例如:

 $('.pdfZone').keydown(function(event) {
if (event.which == "17"){ // CTRL key
$('#inputTextArea').text(window.getSelection().toString())
}
});

.pdfZone 是 pdf viewerdiv 容器

您可以在 github 上找到完整的示例 [ 1 ] [2 ],以及在线 Demo .

注意:我没有使用 CTRL + 单击,因为在我的 Mac OSX 中会触发右键单击,无论如何您都可以更改事件处理。

建议使用 CTRL + 单击(但演示将仅使用 CTRL)

 $('.pdfZone').on('mouseup',function(e) {                       
if (e.ctrlKey) {
$('#inputTextArea').text(window.getSelection().toString());
}
});

关于javascript - 如何实现 ctrl 单击行为以从 web 应用程序中嵌入的 pdf 复制文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24369762/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com