0

I have a JSON response that looks like:

{u'AllowExistingAttachmentToBeOverwritten': False,
 u'Name': u'Go-Daddy.pdf', 
 u'AttachmentData': u'JVBERi0xLjQKJdPr6eEKMSAwIG9iago8PC9DcmVhdG9yIChNb3ppbGxhLzUuMCBcKFdpbmR...
u'ItemIdAttachedTo': 91198711,
u'Description': u''}

How do I convert it to a PDF file?

I tried:

with open(fileName, 'wb') as f:
    f.write(result['AttachmentData']) 
    f.close()

also tried:

with open(fileName, 'wb') as f:
    f.write(result['AttachmentData'].encode()) 
    f.close()

but in both cases the file were created but Adobe could not open the file.

Exprator
  • 26,992
  • 6
  • 47
  • 59
Eran S
  • 63
  • 7
  • Possible duplicate of https://stackoverflow.com/questions/2252726/how-to-create-pdf-files-in-python – Nurjan Jun 14 '17 at 08:07
  • Have you checked pyfpdf? https://www.blog.pythonlibrary.org/2012/07/10/an-intro-to-pyfpdf-a-simple-python-pdf-generation-library/ – Glrs Jun 14 '17 at 08:10

2 Answers2

1

To fully answer your question as soon as you receive data from json file is encoded in BASE64 UTF8 in most cases.To be able to get content of it or save it to the disk it should be BASE64DECODED.

To Replicate your situation following website was used (te get BASE64ENCODED PDF) : http://jsfiddle.net/eliseosoto/JHQnk/

As per suggestion of @eran-s where pdf_base64 is pdf received from json response.

import base64
pdf_base64 = 'JVBERi0xLj...' 
with open('test.pdf', 'wb') as f:
    f.write(base64.b64decode(pdf_base64))
    f.close()

This solution was tested and works like charm.

Please refer to link below for some more information. Embedding a File Attachment in JSON Object

Zebromalz
  • 31
  • 3
  • @eran-s : I think you may need to call `decode` function instead of `encode` as per `Zebromatz`. try changing the line to `f.write( base64.b64decode(result['AttachmentData']) )` – Hara Jun 14 '17 at 08:30
0

Just adding to the @Zebromatz. You just try to decode the file data to base64. Also validate while sending in json whether you are encoding with base64. Your possible code would be as follows.

import base64

# bla bla bla
# bla bla bla

with open(fileName, 'wb') as f:
    f.write( base64.b64decode(result['AttachmentData']) )
    f.close()

See if this would works.

Hara
  • 1,467
  • 4
  • 18
  • 35