Dan
Dan

Reputation: 147

Generating PDF from Base64 string in VBA

I have the following JSON response:

{
  "status": "Success",
  "label": "pdf_base64_string",
  "order": "ABC123456"
}

I'm trying to save a PDF file from the Base64 string per the following code:

FileData = Base64DecodeString(pdf_base64_string)
fileNum = FreeFile
FilePath = "C:\label.pdf"
Open FilePath For Binary Access Write As #fileNum
     Put #fileNum, 1, FileData
Close #fileNum

This results in a broken/invalid PDF file (not recognized by the PDF viewer).

Upvotes: 1

Views: 10107

Answers (2)

EKNATH KULKARNI
EKNATH KULKARNI

Reputation: 404

Points need to take care of for pdf to base64

  1. If you are converting the pdf to base64/blob for rest API then do not use string variables because the size of a string variable is 32200 only.
  2. If you are using pdf for rest API then you need to read the pdf in binary-only [ do not read it by text]
  3. In VBA JSON file is sent through the text-only so try to use the streams instead of the JSON file.

I am sharing the code which does the binary conversion of base64 of the pdf file.

 Function EncodeFileBase64(FileName As String) As String


fileNum = FreeFile
Open FileName For Binary As fileNum
ReDim arrData(LOF(fileNum) - 1)
Get fileNum, , arrData
Close fileNum

Set objXML = New MSXML2.DOMDocument
Set objNode = objXML.createElement("b64")

objNode.DataType = "bin.base64"
objNode.nodeTypedValue = arrData
EncodeFileBase64 = objNode.text

EncodeFileBase64 = Replace(objNode.text, vbLf, "")

 
Set objNode = Nothing
Set objXML = Nothing

End Function

Upvotes: 0

Tim Williams
Tim Williams

Reputation: 166316

Adapted from: Inserting an Image into a sheet using Base64 in VBA?

This works for me - saves the file to the same location as the workbook running the code.

Sub TestDecodeToFile()

    Dim strTempPath As String
    Dim b64test As String

    'little face logo
    b64test = "R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48" & _
    "CXF8m2iQ3YmmKqVlRtW4MLwWACH+H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw=="

    strTempPath = ThisWorkbook.Path & "\temp.png" 'use workbook path as temp path

    'save byte array to temp file
    Open strTempPath For Binary As #1
       Put #1, 1, DecodeBase64(b64test)
    Close #1

End Sub

Private Function DecodeBase64(ByVal strData As String) As Byte()

    Dim objXML As Object 'MSXML2.DOMDocument
    Dim objNode As Object 'MSXML2.IXMLDOMElement

    'get dom document
    Set objXML = CreateObject("MSXML2.DOMDocument")

    'create node with type of base 64 and decode
    Set objNode = objXML.createElement("b64")
    objNode.DataType = "bin.base64"
    objNode.Text = strData
    DecodeBase64 = objNode.nodeTypedValue

    'clean up
    Set objNode = Nothing
    Set objXML = Nothing

End Function

Upvotes: 3

Related Questions