-2

我正在尝试使用我的 Delphi 代码中的命令行实用程序(它适用于 dos 命令行的测试)将 PDF 转储为文本。

这是我的代码

if fileexists(ExtractFilePath(Application.ExeName) + 'pdftotext.exe') then
begin
  ShellExecute(H,'open', 'pdftotext.exe', PWideChar(fFileName), nil, SW_SHOWNORMAL);
  if fileExists(changeFileExt(fFileName, '.txt')) then
    Lines.LoadFromFile(changeFileExt(fFileName, '.txt'))
  else
    ShowMessage('File Not found');
end;

在代码中放置断点并单步执行时,它会到达

if fileExists(changeFileExt(fFileName, '.txt')) then  

行但返回 false,因此调用了 Shellexecute 但没有转储任何文件

我做错了什么?

4

2 回答 2

7

ShellExecute不等待被调用的程序完成运行。您可能过早地检查文件。该文件还没有被创建。

运行程序并等待它终止,然后再检查输出文件。ShellExecute没有返回足够的信息让你这样做,所以你应该尝试CreateProcess。有几个例子可以说明如何做到这一点。试试这个:

如何等待命令行程序完成?

于 2011-01-08T04:59:27.733 回答
1

事实证明,将填充路径添加到可执行文件使其工作得很好

uses
  Forms, ShellAPI, SysConst, SysUtils;

procedure Pdf2Text(const fFileName: string; const Lines: TStrings);
var
  H: HWND;
  PdfToTextPathName: string;
  ReturnValue: Integer;
  TxtFileName: string;
begin
  H := 0;
  PdfToTextPathName := ExtractFilePath(Application.ExeName) + 'pdftotext.exe'; // full path
  if FileExists(PdfToTextPathName) then
  begin
    ReturnValue := ShellExecute(0,'open', PWideChar(PdfToTextPathName), PWideChar(fFileName), nil, SW_SHOWNORMAL);
    if ReturnValue <= 32 then
      RaiseLastOsError();
    // note: the code below this line will crash when pdftotext.exe does not finish soon enough; you should actually wait for pdftotext.exe completion
    TxtFileName := ChangeFileExt(fFileName, '.txt');
    if FileExists(TxtFileName) then
      Lines.LoadFromFile(TxtFileName)
    else
      raise EFileNotFoundException.CreateRes(@SFileNotFound);
  end;
end;

编辑:一些代码清理有助于尽早发现错误,尤其是在测试概念证明时。

于 2011-01-10T15:33:58.923 回答