Spaces:
Paused
Paused
Update main.py
Browse files
main.py
CHANGED
|
@@ -109,4 +109,49 @@ async def convert_to_pdf(request: HTMLRequest):
|
|
| 109 |
pdf = pdfkit.from_string(request.html_content, False, options=options)
|
| 110 |
return Response(content=pdf, media_type="application/pdf")
|
| 111 |
except Exception as e:
|
| 112 |
-
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
pdf = pdfkit.from_string(request.html_content, False, options=options)
|
| 110 |
return Response(content=pdf, media_type="application/pdf")
|
| 111 |
except Exception as e:
|
| 112 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
from html4docx import HtmlToDocx
|
| 116 |
+
import io
|
| 117 |
+
import tempfile
|
| 118 |
+
import os
|
| 119 |
+
|
| 120 |
+
class HTMLInput(BaseModel):
|
| 121 |
+
html: str
|
| 122 |
+
|
| 123 |
+
@app.post("/convert")
|
| 124 |
+
async def convert_html_to_docx(input_data: HTMLInput):
|
| 125 |
+
temp_file = None
|
| 126 |
+
try:
|
| 127 |
+
# Create a new HtmlToDocx parser
|
| 128 |
+
parser = HtmlToDocx()
|
| 129 |
+
|
| 130 |
+
# Parse the HTML string to DOCX
|
| 131 |
+
docx = parser.parse_html_string(input_data.html)
|
| 132 |
+
|
| 133 |
+
# Create a temporary file
|
| 134 |
+
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.docx')
|
| 135 |
+
temp_filename = temp_file.name
|
| 136 |
+
|
| 137 |
+
# Save the DOCX to the temporary file
|
| 138 |
+
docx.save(temp_filename)
|
| 139 |
+
|
| 140 |
+
# Open the file and read its contents
|
| 141 |
+
with open(temp_filename, 'rb') as file:
|
| 142 |
+
file_contents = file.read()
|
| 143 |
+
|
| 144 |
+
# Return the DOCX file as a response
|
| 145 |
+
return fastapi.responses.Response(
|
| 146 |
+
content=file_contents,
|
| 147 |
+
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
| 148 |
+
headers={"Content-Disposition": "attachment; filename=converted.docx"}
|
| 149 |
+
)
|
| 150 |
+
except Exception as e:
|
| 151 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 152 |
+
finally:
|
| 153 |
+
# Clean up: close and remove the temporary file
|
| 154 |
+
if temp_file:
|
| 155 |
+
temp_file.close()
|
| 156 |
+
os.unlink(temp_file.name)
|
| 157 |
+
|