Открытие нескольких файлов PDF через Excel VBA и сохранение в виде текстовых файлов - PullRequest
0 голосов
/ 27 июня 2019

Я пытаюсь открыть несколько файлов PDF в папке и сохранить их как файлы .txt.

Я пробовал подходы в следующей теме

VBA конвертирование нескольких PDF-файлов в папке в текстовый файл

Как предлагается в ответе на вышеЯ попробовал следующий код, который не удался с ошибкой «Определяемый пользователем тип не определен»та же ошибка повторяется.

Я также попробовал метод Follow Hyperlink, чтобы открыть PDF-документы, предложенные в одной из тем на этом форуме, но этот метод, похоже, не работает, если вы хотите закрыть файл после манипулирования файлом.(Я не знаю, как закрыть файл)

Я добавил следующие библиотеки

enter image description here

Когда я пытался добавить) Библиотека типов PDFPrevHndlr 1.0 и б) Библиотека типов PDFShellServer 1.0 (я не знаю, нужен ли какой-либо из них) Я получил ошибку «Ошибка при загрузке DLL»

Нужно ли что-нибудь добавить?У меня установлен Adobe Acrobat Reader DC

enter image description here

У меня нет хорошего понимания работы с библиотеками, dLL и т. Д. Может кто-нибудь помочь, пожалуйста?Заранее большое спасибо.

Ответы [ 2 ]

0 голосов
/ 04 июля 2019

Вам необходимо установить Adobe Acrobat Professional!Попробуйте этот код.

Option Explicit
Option Private Module

Sub SavePDFAsOtherFormat(PDFPath As String, FileExtension As String)

    'Saves a PDF file as another format using Adobe Professional.

    'By Christos Samaras
    'https://myengineeringworld.net/////

    'In order to use the macro you must enable the Acrobat library from VBA editor:
    'Go to Tools -> References -> Adobe Acrobat xx.0 Type Library, where xx depends
    'on your Acrobat Professional version (i.e. 9.0 or 10.0) you have installed to your PC.

    'Alternatively you can find it Tools -> References -> Browse and check for the path
    'C:Program FilesAdobeAcrobat xx.0Acrobatacrobat.tlb
    'where xx is your Acrobat version (i.e. 9.0 or 10.0 etc.).

    Dim objAcroApp      As Acrobat.AcroApp
    Dim objAcroAVDoc    As Acrobat.AcroAVDoc
    Dim objAcroPDDoc    As Acrobat.AcroPDDoc
    Dim objJSO          As Object
    Dim boResult        As Boolean
    Dim ExportFormat    As String
    Dim NewFilePath     As String

    'Check if the file exists.
    If Dir(PDFPath) = "" Then
        MsgBox "Cannot find the PDF file!" & vbCrLf & "Check the PDF path and retry.", _
                vbCritical, "File Path Error"
        Exit Sub
    End If

    'Check if the input file is a PDF file.
    If LCase(Right(PDFPath, 3)) <> "pdf" Then
        MsgBox "The input file is not a PDF file!", vbCritical, "File Type Error"
        Exit Sub
    End If

    'Initialize Acrobat by creating App object.
    Set objAcroApp = CreateObject("AcroExch.App")

    'Set AVDoc object.
    Set objAcroAVDoc = CreateObject("AcroExch.AVDoc")

    'Open the PDF file.
    boResult = objAcroAVDoc.Open(PDFPath, "")

    'Set the PDDoc object.
    Set objAcroPDDoc = objAcroAVDoc.GetPDDoc

    'Set the JS Object - Java Script Object.
    Set objJSO = objAcroPDDoc.GetJSObject

    'Check the type of conversion.
    Select Case LCase(FileExtension)
        Case "eps": ExportFormat = "com.adobe.acrobat.eps"
        Case "html", "htm": ExportFormat = "com.adobe.acrobat.html"
        Case "jpeg", "jpg", "jpe": ExportFormat = "com.adobe.acrobat.jpeg"
        Case "jpf", "jpx", "jp2", "j2k", "j2c", "jpc": ExportFormat = "com.adobe.acrobat.jp2k"
        Case "docx": ExportFormat = "com.adobe.acrobat.docx"
        Case "doc": ExportFormat = "com.adobe.acrobat.doc"
        Case "png": ExportFormat = "com.adobe.acrobat.png"
        Case "ps": ExportFormat = "com.adobe.acrobat.ps"
        Case "rft": ExportFormat = "com.adobe.acrobat.rft"
        Case "xlsx": ExportFormat = "com.adobe.acrobat.xlsx"
        Case "xls": ExportFormat = "com.adobe.acrobat.spreadsheet"
        Case "txt": ExportFormat = "com.adobe.acrobat.accesstext"
        Case "tiff", "tif": ExportFormat = "com.adobe.acrobat.tiff"
        Case "xml": ExportFormat = "com.adobe.acrobat.xml-1-00"
        Case Else: ExportFormat = "Wrong Input"
    End Select

    'Check if the format is correct and there are no errors.
    If ExportFormat <> "Wrong Input" And Err.Number = 0 Then

        'Format is correct and no errors.

        'Set the path of the new file. Note that Adobe instead of xls uses xml files.
        'That's why here the xls extension changes to xml.
        If LCase(FileExtension) <> "xls" Then
            NewFilePath = WorksheetFunction.Substitute(PDFPath, ".pdf", "." & LCase(FileExtension))
        Else
            NewFilePath = WorksheetFunction.Substitute(PDFPath, ".pdf", ".xml")
        End If

        'Save PDF file to the new format.
        boResult = objJSO.SaveAs(NewFilePath, ExportFormat)

        'Close the PDF file without saving the changes.
        boResult = objAcroAVDoc.Close(True)

        'Close the Acrobat application.
        boResult = objAcroApp.Exit

        'Inform the user that conversion was successfully.
        MsgBox "The PDf file:" & vbNewLine & PDFPath & vbNewLine & vbNewLine & _
        "Was saved as: " & vbNewLine & NewFilePath, vbInformation, "Conversion finished successfully"

    Else

        'Something went wrong, so close the PDF file and the application.

        'Close the PDF file without saving the changes.
        boResult = objAcroAVDoc.Close(True)

        'Close the Acrobat application.
        boResult = objAcroApp.Exit

        'Inform the user that something went wrong.
        MsgBox "Something went wrong!" & vbNewLine & "The conversion of the following PDF file FAILED:" & _
        vbNewLine & PDFPath, vbInformation, "Conversion failed"

    End If

    'Release the objects.
    Set objAcroPDDoc = Nothing
    Set objAcroAVDoc = Nothing
    Set objAcroApp = Nothing

End Sub

Для получения более подробной информации см. Ссылку ниже.

https://myengineeringworld.net/2013/03/vba-macro-to-convert-pdf-files-into.html

Или, если у вас не установлен Acrobat, попробуйтеРешение ниже, и, конечно, измените код в соответствии с вашими потребностями.

Sub ChangeDocsToTxtOrRTFOrHTML()
    'with export to PDF in Word 2007
    Dim fs As Object
    Dim oFolder As Object
    Dim tFolder As Object
    Dim oFile As Object
    Dim strDocName As String
    Dim intPos As Integer
    Dim locFolder As String
    Dim fileType As String
    On Error Resume Next

    locFolder = InputBox("Enter the folder path to DOCs", "File Conversion", "C:\Users\your_path_here\")
    Select Case Application.Version
        Case Is < 12
            Do
                fileType = UCase(InputBox("Change DOC to TXT, RTF, HTML", "File Conversion", "TXT"))
            Loop Until (fileType = "TXT" Or fileType = "RTF" Or fileType = "HTML")
        Case Is >= 12
            Do
                fileType = UCase(InputBox("Change DOC to TXT, RTF, HTML or PDF(2007+ only)", "File Conversion", "TXT"))
            Loop Until (fileType = "TXT" Or fileType = "RTF" Or fileType = "HTML" Or fileType = "PDF")
    End Select

    Application.ScreenUpdating = False
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set oFolder = fs.GetFolder(locFolder)
    Set tFolder = fs.CreateFolder(locFolder & "Converted")
    Set tFolder = fs.GetFolder(locFolder & "Converted")

    For Each oFile In oFolder.Files
        Dim d As Document
        Set d = Application.Documents.Open(oFile.Path)
        strDocName = ActiveDocument.Name
        intPos = InStrRev(strDocName, ".")
        strDocName = Left(strDocName, intPos - 1)
        ChangeFileOpenDirectory tFolder
        Select Case fileType
            Case Is = "TXT"
                strDocName = strDocName & ".txt"
                ActiveDocument.SaveAs FileName:=strDocName, FileFormat:=wdFormatText
        Case Is = "RTF"
                strDocName = strDocName & ".rtf"
                ActiveDocument.SaveAs FileName:=strDocName, FileFormat:=wdFormatRTF
        Case Is = "HTML"
                strDocName = strDocName & ".html"
                ActiveDocument.SaveAs FileName:=strDocName, FileFormat:=wdFormatFilteredHTML
        Case Is = "PDF"
                strDocName = strDocName & ".pdf"
                ActiveDocument.ExportAsFixedFormat OutputFileName:=strDocName, ExportFormat:=wdExportFormatPDF
        End Select
        d.Close
        ChangeFileOpenDirectory oFolder
    Next oFile
    Application.ScreenUpdating = True

End Sub
0 голосов
/ 27 июня 2019

Xpdf предоставляет некоторые инструменты командной строки, одним из которых является pdftotext.exe, который экспортирует текст из pdf в файл.

Private Sub PdfToText(ByVal PdfPath As String, ByVal TextPath As String)
Const PathToPdfToText As String = "" '"path\to\exe" 'add path to exe if not in windows path
With CreateObject("wscript.shell")
    .Run Chr(34) & PathToPdfToText & "pdftotext.exe" & Chr(34) & " " & Chr(34) & PdfPath & Chr(34) & " " & Chr(34) & TextPath & Chr(34), 1, 1
End With
End Sub

используйте как

PdfToText "path\to\pdfdoc.pdf", "path\to\textfile.txt"

Отсутствует совет по старому элементу управления для чтения (может быть, кому-то полезен). Метод SaveAs

Получить элемент управления Adobe Reader AciveX в Office x86

На расширенном PowerShell выполните:

& "$env:SystemRoot\SysWOW64\regsvr32"  "C:\Program Files (x86)\Common Files\Adobe\Acrobat\ActiveX\AcroPDFImpl.dll"

для регистрации элемента управления.

После регистрации у вас есть элемент управления ActiveX «Adobe PDF Reader Imp», который можно использовать на x86.Кредиты для этого идут на Нуба .

Но я не уверен, если Reader предоставляет сохранить текст.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...