浏览代码

Merge pull request #1402 from zauberzeug/generate_pdf

Add example which generates a pdf
Falko Schindler 1 年之前
父节点
当前提交
d65b1c5821
共有 4 个文件被更改,包括 55 次插入0 次删除
  1. 1 0
      examples/generate_pdf/.gitignore
  2. 51 0
      examples/generate_pdf/main.py
  3. 2 0
      examples/generate_pdf/requirements.txt
  4. 1 0
      main.py

+ 1 - 0
examples/generate_pdf/.gitignore

@@ -0,0 +1 @@
+*.pdf

+ 51 - 0
examples/generate_pdf/main.py

@@ -0,0 +1,51 @@
+#!/usr/bin/env python3
+from io import BytesIO
+from pathlib import Path
+
+import cairo
+
+from nicegui import ui
+
+PDF_PATH = Path('output.pdf')
+
+
+def generate_svg() -> str:
+    output = BytesIO()
+    surface = cairo.SVGSurface(output, 300, 200)
+    draw(surface)
+    surface.finish()
+    return output.getvalue().decode('utf-8')
+
+
+def generate_pdf() -> bytes:
+    output = BytesIO()
+    surface = cairo.PDFSurface(output, 300, 200)
+    draw(surface)
+    surface.finish()
+    return output.getvalue()
+
+
+def draw(surface: cairo.SVGSurface) -> None:
+    context = cairo.Context(surface)
+    context.select_font_face('Arial', cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
+    context.set_font_size(20)
+    context.move_to(10, 40)
+    context.show_text(name.value)
+    context.move_to(10, 80)
+    context.show_text(email.value)
+
+
+def update() -> None:
+    preview.content = generate_svg()
+    PDF_PATH.write_bytes(generate_pdf())
+
+
+with ui.row():
+    with ui.column():
+        name = ui.input('Name', placeholder='Enter your name', on_change=update)
+        email = ui.input('E-Mail', placeholder='Enter your E-Mail address', on_change=update)
+    preview = ui.html().classes('border-2 border-gray-500')
+    update()
+    ui.button('Download PDF', on_click=lambda: ui.download(PDF_PATH)).bind_visibility_from(name, 'value')
+
+ui.run()

+ 2 - 0
examples/generate_pdf/requirements.txt

@@ -0,0 +1,2 @@
+nicegui
+pycairo

+ 1 - 0
main.py

@@ -342,6 +342,7 @@ async def index_page(client: Client) -> None:
                          'Demonstrate using the official '
                          '[zauberzeug/nicegui](https://hub.docker.com/r/zauberzeug/nicegui) docker image')
             example_link('Download Text as File', 'providing in-memory data like strings as file download')
+            example_link('Generate PDF', 'create SVG preview and PDF download from input form elements')
 
     with ui.row().classes('dark-box min-h-screen mt-16'):
         link_target('why')