如何在Javascript中以pdf格式获取选定的文本? [英] How can I get selected text in pdf in Javascript?

查看:99
本文介绍了如何在Javascript中以pdf格式获取选定的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写Chrome扩展程序来处理pdf文件,因此我想在pdf中获取选定的文本.我该怎么办.

I'm writing a Chrome Extention to manipulate pdf file so I want to get selected text in the pdf. How can I do that.

类似的东西:

推荐答案

您可以使用内部页面上下文中进行:

You can use the internal undocumented commands of the built-in PDF viewer.
To access it your content script should do it in page context:

function getPdfSelectedText() {
  return new Promise(resolve => {
    window.addEventListener('message', function onMessage(e) {
      if (e.origin === 'chrome-extension://mhjfbmdgcfjbbpaeojofohoefgiehjai' &&
          e.data && e.data.type === 'getSelectedTextReply') {
        window.removeEventListener('message', onMessage);
        resolve(e.data.selectedText);
      }
    });
    const script = document.createElement('script');
    document.documentElement.appendChild(script).text =
      "document.querySelector('embed').postMessage({type: 'getSelectedText'}, '*')";
    script.remove();
  });
}

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg === 'getPdfSelection') {
    getPdfSelectedText().then(sendResponse);
    return true;
  }
});

这篇关于如何在Javascript中以pdf格式获取选定的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆