Delphi提取PDF文本实例
针对当前PDF解析工具稀缺且易出错的现状,本文提出一种利用Delphi语言封装ApachePDFBox开源库的解决方案,通过命令行调用其ExtractText功能,有效实现PDF文档的文本提取。该方法需要Java运行环境以及pdfbox-app-2.0.6.jar包支持,运行稳定可靠,并且能够正确处理中文内容,具有实用性。
市面上能生成 PDF 的控件不少,但真正好用的解析工具可不多。之前试过 pdf Toolkit,结果第一个稍微复杂点的 PDF 就报错,汉字还乱码——可能是版本或用法不对,但折腾下去实在不划算。

于是想起以前用 Ja va 时调过 Apache 的 pdfBox 库,效果很不错。索性下载一份,用 Delphi 来封装调用,把 PDF 文本解析出来。
环境要求:Ja va 运行环境
pdfBox 应用包:pdfbox-app-2.0.6.jar
思路很简单:通过命令行调用 pdfBox 的提取功能,再在 Delphi 里捕获结果。
首先,封装一个执行 DOS 命令的函数:
procedure CheckResult(b: Boolean); begin if not b then raise Exception.Create(SysErrorMessage(GetLastError)); end; function RunDOS(const CommandLine: string): string; var HRead, HWrite: THandle; StartInfo: TStartupInfo; ProceInfo: TProcessInformation; b: Boolean; sa: TSecurityAttributes; inS: THandleStream; sRet: TStrings; begin Result := ''; FillChar(sa, sizeof(sa), 0); //设置允许继承,否则在NT和2000下无法取得输出结果 sa.nLength := sizeof(sa); sa.bInheritHandle := True; sa.lpSecurityDescriptor := nil; b := CreatePipe(HRead, HWrite, @sa, 0); CheckResult(b); FillChar(StartInfo, SizeOf(StartInfo), 0); StartInfo.cb := SizeOf(StartInfo); StartInfo.wShowWindow := SW_HIDE; //使用指定的句柄作为标准输入输出的文件句柄,使用指定的显示方式 StartInfo.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW; StartInfo.hStdError := HWrite; StartInfo.hStdInput := GetStdHandle(STD_INPUT_HANDLE); //HRead; StartInfo.hStdOutput := HWrite; b := CreateProcess(nil, //lpApplicationName: PChar PChar(CommandLine), //lpCommandLine: PChar nil, //lpProcessAttributes: PSecurityAttributes nil, //lpThreadAttributes: PSecurityAttributes True, //bInheritHandles: BOOL CREATE_NEW_CONSOLE, nil, nil, StartInfo, ProceInfo); CheckResult(b); WaitForSingleObject(ProceInfo.hProcess, INFINITE); inS := THandleStream.Create(HRead); if inS.Size > 0 then begin sRet := TStringList.Create; sRet.LoadFromStream(inS); Result := sRet.Text; sRet.Free; end; inS.Free; CloseHandle(HRead); CloseHandle(HWrite); end;
然后,封装一个专门解析 PDF 文本的函数,把命令拼好,调用上面那个函数:
function TfrmPDFTool.GetPDFText(sFile: string): string; var cmd:string; pdfFilePath,pdfFileName,txtFileName:String; begin //ja va -jar pdfbox-app-2.0.6.jar ExtractText -encoding utf-8 e:\temp\test.pdf e:\temp\testiii.txt pdfFilePath:=ExtractFilePath(sFile); pdfFileName:=ExtractFileName(sFile); txtFileName:=FAppPath+'Temp'+pdfFileName+'.txt'; cmd:='ja va -jar '+FAppPath+'PDFBoxpdfbox-app-2.0.6.jar ExtractText ' +' -encoding utf-8 '+sFile +' '+txtFileName; AddLog(cmd); Result:=RunDOS(cmd); AddLog(Result); memTxtFile.Lines.LoadFromFile(txtFileName,TUTF8Encoding.Create); FPDFText:=memTxtFile.Text; AddLog(FPDFText); end;
OK,大功告成!
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















