lundi 23 mars 2020

Generate a Word Doc from a Python Script and return it with PHP

I have a PHP website with a feature where users can download a custom word doc. This word doc is made in a python script using Python-Docx.

I am struggling to find a way to hand off the word doc back to the PHP. This is the best I have come up with so far:

PHP:

$output = array();
exec("../../../venv/bin/python download.py ",$output);
$file_url = 'test.docx';

$today = date("Y-m-d-His");
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=custom-doc-".$today.".doc");
file_put_contents('test.docx', base64_decode($output[0]));

Python:

# source_doc is generated above
target_stream = BytesIO()
source_document.save(target_stream)
target_stream.seek(0)
print(target_stream.getvalue())

This returns a word doc with the byte code from python-docx. Word does not read it as a word document. I'd like to avoid using the file system. Has anyone done something similar? Or are there other approaches I should be looking into? Thanks

Aucun commentaire:

Enregistrer un commentaire