在VBA中从Base64字符串生成PDF [英] Generating PDF from Base64 string in VBA

查看:369
本文介绍了在VBA中从Base64字符串生成PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下JSON响应:

I have the following JSON response:

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

我正在尝试按照以下代码从Base64字符串中保存PDF文件:

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

这会导致PDF文件损坏/无效(PDF查看器无法识别).

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

推荐答案

适应于:这对我有用-将文件保存到与运行代码的工作簿相同的位置.

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

这篇关于在VBA中从Base64字符串生成PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆