我学习用delphi准备一个字典程序。到目前为止,我已经解决了关于 Word 文档的问题,但我遇到了一些关于 PDF 文档的问题。我使用 Delphi 7 导入并安装了 AcroPdf 组件,我想从 Delphi 中的 ACROPDF 组件查看的 pdf 文档中获取用户通过 dblclicking 选择的单词(或文本)。如果我能得到它,我会直接将它发送到字典数据库。如果你帮助我,我会很高兴。谢谢... Remzi MAKAK
1 回答
下面显示了一种从在 Adobe Acrobat Professional(v.8,英文版)中打开的 Pdf 文档中获取所选文本的方法。
更新此答案的原始版本忽略了检查调用的布尔结果MenuItemExecute
并为其指定了错误的参数。这两点都在此答案的更新版本中得到修复。事实证明,调用失败的原因是,在尝试将选择的文本复制到剪贴板之前,MenuItemExecute
必须先调用Acrobat 文档。BringToFront
创建一个新的 Delphi VCL 项目。
在 D7 的 IDE 中
Projects | Import Type Library
,在Import Type Library
弹出窗口中向下滚动,直到在文件列表中看到“Acrobat (Version 1.0)”,在Class names
框中看到“TAcroApp, TAcroAVDoc...”。需要导入。点击Create unit
按钮/在项目的主表单文件中
一种。确保它使用步骤 2 中的 Acrobat_Tlb.Pas 单元。您可能需要将保存 Acrobat_Tlb.Pas 的路径添加到项目的 SearchPath 中。
湾。在表单上放置一个 TButton,将其命名为
btnGetSel
。在表单上放置一个 TEdit 并为其命名edSelection
编辑主表单单元的源代码,如下所示。
设置调试器断点不要在过程中设置断点,Acrobat.MenuItemExecute('File->Copy');
GetSelection
因为这可能会破坏对其中的调用BringToFront
。关闭任何正在运行的 Adobe Acrobat 实例。在任务管理器中检查它没有运行的隐藏实例。执行这些步骤的原因是要确保当您运行应用程序时,它会与它启动的 Acrobat 实例“对话”,而不是另一个。
编译并运行您的应用程序。打开应用程序和Acrobat 后,切换到 Acrobat,选择一些文本,切换回您的应用程序并单击
btnGetSel
按钮。
代码:
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;