I'm trying to save a URL as PDF with VBA. I'm able to get a file to download/be created, but when opening I get an error:
Acrobat could not open 'file.pdf' because it is either not a supported file type or because the file has been damaged...
I've tried a few different ways to download the file, but I suspect the reason is because my URL is not one like http://www.url.com/file.pdf
, but instead it's like http://www.url.com/filegenerated/I
where the page itself is a PDF, that I can look at and download. Unfortunately it's an internal URL, so I can't post a link to it, but here's an example of what I mean:
Any ideas on what I could do instead? Manually I just have to either Download the PDF (when hovering mouse over it, the scroll buttons and download button show, like in the above screen shot), or Right Click and Save As, and it will save as a PDF.
Here are two macros I've tried so far:
Function SaveWebFile(ByVal vWebfile As String, ByVal vLocalFile As String) As Boolean
Dim oXMLHTTP As Object, i As Long, vFF As Long, oResp() As Byte
Set oXMLHTTP = CreateObject("msxml2.xmlhttp")
oXMLHTTP.Open "GET", vWebfile, False 'Open socket to get the website
oXMLHTTP.Send 'send request
'Wait for request to finish
Do While oXMLHTTP.readyState <> 4
DoEvents
Loop
'Returns the results as a byte array
oResp = oXMLHTTP.ResponseBody
'Create a local file and save result to it
vFF = FreeFile
If Dir(vLocalFile) <> "" Then Kill vLocalFile
Open vLocalFile For Binary As #vFF
Put #vFF, , oResp
Close #vFF
Set oXMLHTTP = Nothing
End Function
and
Private Sub DownloadFile(myURL As String, destFolder As String)
Dim WinHttpReq As Object, oStream As Object
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False
WinHttpReq.Send
myURL = WinHttpReq.ResponseBody
If WinHttpReq.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WinHttpReq.ResponseBody
oStream.SaveToFile destFolder & "file.pdf", 2 ' 1 = no overwrite, 2 = overwrite
oStream.Close
End If
End Sub
And I've also tried Chip Pearson's example to no avail.
A 9kb file is created, but it won't open, per the error above. I don't think it's the file, because when I do save the PDF, it's about 50kb, not 9kb, so I'm thinking the file created is a "placeholder" PDF?