如何使用Delphi 7直接从acropdf组件中获取所选文本到编辑

时间:2016-04-26 15:07:55

标签: delphi pdf axacropdf

我正在学习用delphi编写字典程序。到目前为止,我已经解决了有关Word文档的问题,但是我对PDF文档有一些问题。 我使用Delphi 7导入并安装了AcroPdf组件,我希望得到用户通过用户在pdf文档中选择的单词(或文本),该文档由Delphi中的ACROPDF组件查看。如果我能得到它,我会直接将字典数据库发送给它。 如果你帮助我,我会很高兴。谢谢... Remzi MAKAK

1 个答案:

答案 0 :(得分:1)

以下显示了从Pdf文档中获取所选文本的一种方法 在Adobe Acrobat Professional中打开(v.8,英文版)。

更新此答案的原始版本忽略了检查调用MenuItemExecute 的布尔结果,为其指定了错误的参数。这两点都在此答案的更新版本中得到修复。事实证明,调用MenuItemExecute失败的原因是,在尝试将所选文本复制到剪贴板之前,必须先调用Acrobat文档上的BringToFront

  1. 创建一个新的Delphi VCL项目。

  2. 在D7的IDE中转到Projects | Import Type Library,然后在Import Type Library弹出窗口中向下滚动,直到看到类似" Acrobat(版本1.0)的内容文件列表,和 " TAcroApp,TAcroAVDoc ......"在Class names框中。这是您需要导入的那个。点击Create unit按钮/

  3. 在项目的主表单文件

    一个。确保它使用步骤2中的Acrobat_Tlb.Pas单元。您可能需要将路径添加到将Acrobat_Tlb.Pas保存到项目的SearchPath的任何位置。

    湾在表单上删除TButton,将其命名为btnGetSel。在表单上删除一个TEdit并将其命名为edSelection

  4. 编辑主表单单元的源代码,如下所示。

  5. Acrobat.MenuItemExecute('File->Copy'); 上设置调试器断点GetSelection过程中设置断点,因为这可能会打败请致电BringToFront

  6. 关闭所有正在运行的Adobe Acrobat实例。在任务管理器中检查它没有运行的隐藏实例。这些步骤的原因是为了确保在您运行应用程序时,它会"会谈"到它启动的Acrobat实例,而不是另一个。

  7. 编译并运行您的应用。应用 Acrobat打开后,切换到Acrobat,选择一些文字,切换回您的应用并点击btnGetSel按钮。

  8. 代码:

      uses ... Acrobat_Tlb, ClipBrd;
    
      TDefaultForm = class(TForm)
      [...]
      private
        FFileName: String;
        procedure GetSelection;
      public
        Acrobat : CAcroApp;
        PDDoc : CAcroPDDoc;
        AVDoc : CAcroAVDoc;
      end;
    
    [...]
    
    procedure TDefaultForm.FormCreate(Sender: TObject);
    begin
      //  Adjust the following path to suit your system.  My application is
      //  in a folder on drive D:
      FFileName := ExtractfilePath(Application.ExeName) + 'Printed.Pdf';
      Acrobat := CoAcroApp.Create;
      Acrobat.Show;
      AVDoc := CoAcroAVDoc.Create;
      AVDoc.Open(FileName, FileName); // := Acrobat.GetAVDoc(0) as CAcroAVDoc; //
    
      PDDoc := AVDoc.GetPDDoc as CAcroPDDoc;
    end;
    
    procedure TDefaultForm.btnGetSelClick(Sender: TObject);
    begin
      GetSelection;
    end;
    
    procedure TDefaultForm.GetSelection;
    begin
      // call this once some text is selected in Acrobat
      edSelection.Text := '';
    
      if AVDoc.BringToFront then  //  NB:  This call to BringToFront is essential for the call to MenuItemExecute('Copy') to succeed 
        Caption := 'BringToFront ok'
      else
        Caption := 'BringToFront failed';
      if Acrobat.MenuItemExecute('Copy') then
        Caption := 'Copy ok'
      else
        Caption := 'BringToFront failed';
    
      Sleep(100);  // Normally I would avoid ever calling Sleep in a Delphi     
      //  App's main thread.  In this case, it is to allow Acrobat time to transfer the selected
      //  text to the clipboard before we attempt to read it.
    
      try
        edSelection.Text := Clipboard.AsText;
      except
      end;
    
    end;