在不使用 SendKeys 的情况下使用 VBA 在记事本中保存 PDF 中的文本文件

Saving a text file from a PDF in Notepad using VBA without SendKeys

所以,我想做的是获取一个 pdf 文件,用 Internet Explorer 打开它,从中复制文本,将该文本粘贴到记事本中的文本文件中,然后使用与创建它的pdf。到目前为止,我已经完成了所有这些工作,但在我拥有所需数据后保存文本文件除外。我发现自己现在卡住了,任何想法都会有所帮助。

这是我目前的代码:

Set b2 = ThisWorkbook

Set ie = CreateObject("InternetExplorer.Application")
strPath = "C:\Users3281\Desktop\test 134.pdf"

ie.Visible = True
ie.navigate (strPath)

Do While ie.Busy And ie.ReadyState <> 4
        DoEvents
    Loop


Application.Wait Now + TimeSerial(0, 0, 2)
    AppActivate strPath
    SendKeys "^(a)", True
    Application.Wait Now + TimeSerial(0, 0, 1)

    Do
        On Error Resume Next
        SendKeys "^(c)", True
    Loop While Err.Number <> 0
np = Shell("Notepad.exe", vbNormalFocus)


AppActivate np
SendKeys "^(v)", True
'tried the SendKeys method of saving my text file here, not to much avail
SendKeys "^(s)", True

'this bit here finds the file name of strPath
a = InStrRev(strPath, "\")
b = InStrRev(strPath, ".")
c = Mid(strPath, a + 1, b - a - 1)

'haven't got anything after this point but a few failed attempts

(对于代码混乱我深表歉意,在我有一些可以工作的东西之前我不会专注于结构)

我会这样做:

Dim NP as object

set NP = CreateObject("Notepad.Application")

'copy the text from the .PDF as you do now

NP.paste
NP.SaveAs Filename:=<your file name>

注意:这是完全未经测试的,但应该作为一个框架。我没有查看记事本对象模型来确认我的方法名称是否正确。

所以,最终对我有用的代码如下:

Dim b2 As Workbook
Dim ie As Object
Dim np As Object

Sub test4()
Set b2 = ThisWorkbook

Set ie = CreateObject("InternetExplorer.Application")
strPath = "C:\Users3281\Desktop\test 134.pdf"

ie.Visible = False
ie.navigate (strPath)

Do While ie.Busy And ie.ReadyState <> 4
    DoEvents
Loop

Application.Wait Now + TimeSerial(0, 0, 2)
AppActivate strPath
SendKeys "^(a)", True
Application.Wait Now + TimeSerial(0, 0, 1)

Do
    On Error Resume Next
    SendKeys "^(c)", True
Loop While Err.Number <> 0

ie.Quit

Set np = CreateObject("Word.Application")
AppActivate np
np.documents.Add
np.Visible = False
np.Selection.pasteandformat wdpastedefault

b = InStrRev(strPath, ".")
filenm = Mid(strPath, 1, b - 1)

np.activedocument.SaveAs2 Filename:=filenm, FileFormat:=2
np.activedocument.Close
np.Quit

np = Nothing
ie = Nothing
SendKeys "{NUMLock}", True

End Sub

我发现使用 Word 比使用记事本创建文本文档更成功。此代码将获取 pdf,在 IE 中打开它,select 所有文本,复制到剪贴板,然后将其粘贴到 word 文档,然后将其作为文本文件保存在与原始 pdf 相同的文件夹中。