-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 に答える