VBA 将 PDF 从 URL 保存到本地文件夹

问题描述 投票:0回答:2

我正在尝试循环浏览多个 url 将 pdf 下载到本地文件夹。

网址示例为 https://find-energy-certificate.service.gov.uk/energy-certificate/8309-9619-9729-7796-8423?print=true

这是我到目前为止写的vb。

Dim sveloc As String
Dim svenme As String
Dim url    As String

sveloc = Application.ActiveWorkbook.Path & "\Saved EPCs"

i = 7
Do Until sh01.Cells(i, 27) = "" 'all cells in the list are populated with no gaps

    url = sh01.Cells(i, 27)
    svenme = sh01.Cells(i, 2)
    sveloc = sveloc & "\" & svenme & ".pdf"

        ThisWorkbook.FollowHyperlink (url)
        'code to open and save the pdf goes here

    i = i + 1

Loop

感谢任何帮助,因为我真的很难过这个问题。 短暂性脑缺血发作。

vba pdf url download
2个回答
2
投票

受到 KJ 答案的启发,没有错误检查等。只是想说明如何使用 shell 来自动化整个过程。

sveloc = Application.ActiveWorkbook.Path & "\Saved EPCs"

edgePath = Environ$("PROGRAMFILES(X86)") & "\Microsoft\Edge\Application\msedge.exe"

With CreateObject("WScript.Shell")
    i = 7
    Do Until Len(sh01.Cells(i, 27)) = 0 'all cells in the list are populated with no gaps
        On Error Resume Next
        .Run """" & edgePath & """ --profile-directory=Default --headless -print-to-pdf=""" & sveloc & "\" & sh01.Cells(i, 2) & ".pdf" & """ """ & sh01.Cells(i, 27) & """", 1, True
        On Error GoTo 0
        i = i + 1
    Loop
End With

1
投票

不需要 VBA,但您可以使用它来更改变量,因此使用 Windows 中的示例,我们可以通过 Edge 运行 在 html 运行时构建 pdf:-

"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" --profile-directory=Default --headless -print-to-pdf=C:\Users\WDAGUtilityAccount\Desktop\8309-9619-9729-7796-8423.pdf "https://find-energy-certificate.service.gov.uk/energy-certificate/8309-9619-9729-7796-8423?print=true"
就像魔术一样,文件不到一秒就出现在我的桌面上

没有在线pdf,它是由浏览器构建的。所以使用浏览器是必不可少的。您可以使用一个额外的开关删除打印页眉/页脚,但无法更改方向,在英国设备中它将是 A4 纵向。

--no-pdf-header-footer

 将当前代码视为较新的代码。

如果您只想要较小的未标记文件,另一个开关可能很有价值


-disable-pdf-tagging


如果您尝试在没有浏览器打印的情况下下载,您将只获得网页打印所需的原始 HTML,因此如上所述调用浏览器远程打印,将生成所需的“专为网络设计”图形副本。

curl -o test.htm https://find-energy-certificate.service.gov.uk/energy-certificate/8309-9619-9729-7796-8423?print=true


在评论中提出了如何适应这种方法以更改浏览器并保持调用简单的问题,因此我建议使用 cmd 或 bat 文件来使该部分更容易。因此,从 vba 调用类似的东西

Batchfile 8309-9619-9729-7796-8423


@echo off set "browser=C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" set "filedir=C:\Users\WDAGUtilityAccount\Desktop" set "urlpath=https://find-energy-certificate.service.gov.uk/energy-certificate" "%browser%" --profile-directory=Default --headless --print-to-pdf="%filedir%\%~1.pdf" -print-to-pdf-no-header "%urlpath%/%~1?print=true"
但是,请注意调用 pdf 生成速度太快,在调用之间添加一个小等待,即使在多线程 CPU 上同时写入 PDF 也常常会因图形资源冲突而导致灾难。

© www.soinside.com 2019 - 2024. All rights reserved.