分享

在VBA中从Base64字符串生成PDF

 F2967527 2021-01-20

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 = FreeFileFilePath = 'C:\label.pdf'Open FilePath For Binary Access Write As #fileNum     Put #fileNum, 1, FileDataClose #fileNum

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

解决方案

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 #1End SubPrivate 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 = NothingEnd Function

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约