This demo shows how to use pypandoc (a Python wrapper around Pandoc) to convert text between markup formats. The program provides a small web UI, but the focus here is on how pypandoc.convert_text(...) is used.
https://pandoc-converter-example.wasmer.app/
All logic lives in one file. Here are the relevant code sections related to pypandoc:
A list of markup formats is declared. These are passed directly to pypandoc:
SUPPORTED_FORMATS = [
("markdown", "Markdown"),
("rst", "reStructuredText"),
("html", "HTML"),
("latex", "LaTeX"),
("mediawiki", "MediaWiki"),
("docbook", "DocBook"),
("org", "Org Mode"),
]The actual conversion happens in the POST request handler. The work is run in a background thread to avoid blocking the server:
converted = await asyncio.to_thread(
pypandoc.convert_text,
text,
to=target_format,
format=source_format,
)Key details:
formatspecifies the source format.tospecifies the target format.- The return value is the converted text, ready to display or save.
If Pandoc raises an error, it is caught and safely escaped for display:
except (RuntimeError, OSError) as exc:
escaped_error = html.escape(str(exc))
return ERROR_TEMPLATE.replace("{escaped_error}", escaped_error)This ensures that unsupported conversions or missing executables don’t crash the app.
- Create a
requirements.txt:
fastapi
uvicorn
pypandoc
- Install dependencies:
pip install -r requirements.txt- Run the server:
uvicorn app:app --host 0.0.0.0 --port 8000- Convert via API (example without UI):
curl -X POST http://localhost:8000/api/hx/convert \
-F 'source_format=markdown' \
-F 'target_format=rst' \
-F 'text=# Hello **world**'The response will contain the converted text wrapped in HTML.
API endpoints:
- GET
/api/pandoc-convert?from=markdown&to=html&text=...returns converted content as plain text. - POST
/api/pandoc-convert?from=markdown&to=htmlwith form fieldtextreturns converted content as plain text.
On failure, endpoints return JSON { "error": "<msg>" } with status 400.
- Include
app.pyandrequirements.txt. - Deploy to Wasmer Edge and point the web process to run Uvicorn (e.g.,
uvicorn app:app --host 0.0.0.0 --port $PORT). - Open
https://<your-subdomain>.wasmer.app/and try converting text between formats.
⚡ With this setup, the key takeaway is how to call pypandoc.convert_text with format and to arguments to transform text between markup languages.
Would you like me to also add a minimal example without FastAPI (just showing pypandoc.convert_text in a script) so the README highlights the conversion part even more directly?