### Run the example app with flutter run Source: https://github.com/ajmalbuv/typst_flutter/blob/main/example/README.md From the project root, execute `flutter run` to launch the example app. The native build systems automatically fetch prebuilt Typst binaries in the background. ```bash flutter run ``` -------------------------------- ### Local setup and build commands for typst_flutter Source: https://github.com/ajmalbuv/typst_flutter/blob/main/GEMINI.md Commands to clone the repository, install dependencies, build the Rust native library, copy it to the expected location for Linux, and run the example app. The first `cargo build --release` can take 5–15 minutes due to Typst's large dependency tree. ```bash git clone https://github.com/ajmalbuv/typst_flutter cd typst_flutter # Install Dart/Flutter deps flutter pub get # Build the native library (first time is slow — Typst has a large dep tree) cd rust cargo build --release cd .. # Copy the built library to the right place (Linux example) cp rust/target/release/libtypst_flutter.so linux/libs/ # Run the example app cd example flutter pub get flutter run -d linux # or macos, android, etc. ``` -------------------------------- ### CMake: Auto-run setup if DLL missing Source: https://github.com/ajmalbuv/typst_flutter/blob/main/windows/CMakeLists.txt If the pre-built DLL is not found, runs `dart run typst_flutter:setup` from the consumer app root. On failure, emits a warning with instructions to run manually. ```cmake if(NOT EXISTS "${_prebuilt_dll}") message(STATUS "typst_flutter: prebuilt binary missing — running setup...") # Consumer app root = one level above the app's windows/ folder (CMAKE_SOURCE_DIR) set(_app_root "${CMAKE_SOURCE_DIR}/..") execute_process( COMMAND cmd /c dart run typst_flutter:setup WORKING_DIRECTORY "${_app_root}" RESULT_VARIABLE _setup_result OUTPUT_VARIABLE _setup_out ERROR_VARIABLE _setup_err ) if(NOT _setup_result EQUAL 0) message(WARNING "typst_flutter: auto-download failed (exit ${_setup_result}).\n" " stdout: ${_setup_out}\n" " stderr: ${_setup_err}\n" " Run manually: dart run typst_flutter:setup" ) endif() endif() ``` -------------------------------- ### Run setup script after adding package Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/src/content/docs/guides/getting-started.md Run these commands from your app root after adding the package. The setup script downloads prebuilt native Typst libraries (~15MB) from GitHub Releases and caches them in your pub cache. This is required once per version upgrade; no Rust toolchain is needed. ```bash flutter pub get dart run typst_flutter:setup ``` -------------------------------- ### CMake: Fail if DLL still missing Source: https://github.com/ajmalbuv/typst_flutter/blob/main/windows/CMakeLists.txt Raises a fatal error if the pre-built DLL is still not found after the setup attempt, including the expected path and manual setup command. ```cmake if(NOT EXISTS "${_prebuilt_dll}") message(FATAL_ERROR "typst_flutter: typst_flutter.dll not found at:\n" " ${_prebuilt_dll}\n\n" "Run once from your app root:\n" " dart run typst_flutter:setup\n" ) endif() ``` -------------------------------- ### Manually run setup script when auto-download fails Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/src/content/docs/guides/getting-started.md Run this command manually from your app root if the build-time auto-download fails (e.g., no internet or permission issues). Then rebuild your app. ```bash dart run typst_flutter:setup ``` -------------------------------- ### Create and push a git tag Source: https://github.com/ajmalbuv/typst_flutter/blob/main/RELEASE_PROCESS.md After bumping the version, create and push a git tag following the pattern v*.*.*. The example uses version 3.0.0. ```bash # Example for version 3.0.0 git tag v3.0.0 git push origin v3.0.0 ``` -------------------------------- ### Compile and export a PDF with TypstCompiler Source: https://github.com/ajmalbuv/typst_flutter/blob/main/README.md Initialize the Typst engine with TypstCompiler.create(), compile a document with inputs, query headings, export to PDF, and dispose the document handle. The example shows passing variables via inputs and using sys.inputs.at with a default. ```dart import 'package:typst_flutter/typst_flutter.dart'; final compiler = await TypstCompiler.create(); // Compile to an opaque document handle final doc = await compiler.compile( source: r''' #set page(width: 148mm, height: 210mm, margin: 1cm) = Hello Typst! This is rendered *natively* in Flutter. #sys.inputs.at("theme", default: "light") ''', inputs: {'theme': 'dark'}, // Safely pass variables to Typst ); // Query metadata/structure from the compiled document final headingJson = await compiler.query(document: doc, selector: ''); // Export to PDF bytes final pdfBytes = await doc.exportPdf(); print('Generated a ${doc.pageCount}-page PDF (${pdfBytes.length} bytes).'); // You can now save pdfBytes to disk or share it! // Don't forget to dispose the document handle doc.dispose(); ``` -------------------------------- ### Project-level CMake configuration for typst_flutter example Source: https://github.com/ajmalbuv/typst_flutter/blob/main/example/linux/CMakeLists.txt Sets up the CMake project for the Linux runner, defining the binary name, application ID, and build type defaults. It also configures cross-compilation sysroot and standard compile settings for targets. ```cmake # Project-level configuration. cmake_minimum_required(VERSION 3.13) project(runner LANGUAGES CXX) # The name of the executable created for the application. Change this to change # the on-disk name of your application. set(BINARY_NAME "typst_flutter_example") # The unique GTK application identifier for this application. See: # https://wiki.gnome.org/HowDoI/ChooseApplicationID set(APPLICATION_ID "com.ajmalbuv.typst_flutter") # Explicitly opt in to modern CMake behaviors to avoid warnings with recent # versions of CMake. cmake_policy(SET CMP0063 NEW) # Load bundled libraries from the lib/ directory relative to the binary. set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") # Root filesystem for cross-building. if(FLUTTER_TARGET_PLATFORM_SYSROOT) set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) endif() # Define build configuration options. if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Flutter build mode" FORCE) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Profile" "Release") endif() # Compilation settings that should be applied to most targets. # # Be cautious about adding new options here, as plugins use this function by # default. In most cases, you should add new options to specific targets instead # of modifying this function. function(APPLY_STANDARD_SETTINGS TARGET) target_compile_features(${TARGET} PUBLIC cxx_std_14) target_compile_options(${TARGET} PRIVATE -Wall -Werror) target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") endfunction() # Flutter library and tool build rules. set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") add_subdirectory(${FLUTTER_MANAGED_DIR}) # System-level dependencies. find_package(PkgConfig REQUIRED) pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) # Application build; see runner/CMakeLists.txt. add_subdirectory("runner") # Run the Flutter tool portions of the build. This must not be removed. add_dependencies(${BINARY_NAME} flutter_assemble) # Only the install-generated bundle's copy of the executable will launch # correctly, since the resources must in the right relative locations. To avoid # people trying to run the unbundled copy, put it in a subdirectory instead of # the default top-level location. set_target_properties(${BINARY_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" ) # Generated plugin build rules, which manage building the plugins and adding # them to the application. include(flutter/generated_plugins.cmake) # === Installation === # By default, "installing" just makes a relocatable bundle in the build # directory. set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() # Start with a clean build bundle directory every time. install(CODE " file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") " COMPONENT Runtime) set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) install(FILES "${bundled_library}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endforeach(bundled_library) # Copy the native assets provided by the build.dart from all packages. set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) # Fully re-copy the assets directory on each build to avoid having stale files # from a previous install. set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) # Install the AOT library on non-Debug builds only. if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### Migration from 1.x to 2.0 API Source: https://github.com/ajmalbuv/typst_flutter/blob/main/CHANGELOG.md Migration guide showing the old 1.x API calls (compile, renderPage, compileSvg, compileDocument, renderCachedPageAsSvg) and the new 2.0 equivalents using compile() returning TypstDocument, then exportPdf(), renderRaster(), renderSvg(), and dispose(). ```dart // ── Before (1.x) ────────────────────────────────────────── // PDF final doc = await compiler.compile(source: markup); final pdf = doc.pdf; // Uint8List directly // Raster final result = await compiler.renderPage(source: markup); final image = await result.toImage(); // SVG final doc = await compiler.compileSvg(source: markup); final svgs = doc.svgs; // Multi-page (implicit state — race condition prone) final count = await compiler.compileDocument(source: markup); final svg = await compiler.renderCachedPageAsSvg(pageIndex: 0); // ── After (2.0) ─────────────────────────────────────────── // PDF final doc = await compiler.compile(source: markup); final pdf = await doc.exportPdf(); // Raster final doc = await compiler.compile(source: markup); final result = await doc.renderRaster(pageIndex: 0); final image = await result.toImage(); // SVG final doc = await compiler.compile(source: markup); final svg = await doc.renderSvg(0); // Multi-page (safe — each doc is independent) final doc = await compiler.compile(source: markup); for (var i = 0; i < doc.pageCount; i++) { final svg = await doc.renderSvg(i); } // Don't forget to dispose when done! doc.dispose(); ``` -------------------------------- ### Generate PDF with TypstCompiler Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/src/content/docs/guides/getting-started.md Initializes the Typst compiler, compiles Typst source code, exports PDF bytes, and disposes the document. The source uses raw string syntax (r'''...''') to avoid escaping. The example prints the page count and byte length. Remember to dispose the document when done. ```dart import 'package:typst_flutter/typst_flutter.dart'; // 1. Initialize the compiler (loads the native binaries) final compiler = await TypstCompiler.create(); // 2. Compile your source code to an opaque handle final doc = await compiler.compile( source: r''' #set page(width: 148mm, height: 210mm, margin: 1cm) = Hello Typst! This is rendered *natively* in Flutter. ''', ); // 3. Export to PDF bytes final pdfBytes = await doc.exportPdf(); print('Generated a ${doc.pageCount}-page PDF (${pdfBytes.length} bytes).'); // Don't forget to dispose the document when you're done! doc.dispose(); ``` -------------------------------- ### Render a live preview with TypstDocumentViewer Source: https://github.com/ajmalbuv/typst_flutter/blob/main/README.md Use TypstDocumentViewer to automatically compile and render a document with a scrollable, zoomable UI. The example sets renderMode to TypstRenderMode.svg for crisp vector text. ```dart import 'package:flutter/material.dart'; import 'package:typst_flutter/typst_flutter.dart'; class MyEditor extends StatelessWidget { @override Widget build(BuildContext context) { return TypstDocumentViewer( source: r''' = Multi-page Viewer This document spans multiple pages. #pagebreak() And scrolling is instantly fast because the document handle is immutable! ''', renderMode: TypstRenderMode.svg, // Use SVG for crisp vector text ); } } ``` -------------------------------- ### CMakeLists.txt: Flutter Windows build configuration Source: https://github.com/ajmalbuv/typst_flutter/blob/main/example/windows/flutter/CMakeLists.txt Defines the Flutter library interface, C++ wrapper libraries (flutter_wrapper_plugin and flutter_wrapper_app), and a custom command that runs the Flutter tool backend (tool_backend.bat) to generate required artifacts. It sets fallback target platform to 'windows-x64' if not defined and publishes key paths (FLUTTER_LIBRARY, FLUTTER_ICU_DATA_FILE, PROJECT_BUILD_DIR, AOT_LIBRARY) to the parent scope for the install step. ```cmake # This file controls Flutter-level build steps. It should not be edited. cmake_minimum_required(VERSION 3.14) set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") # Configuration provided via flutter tool. include(${EPHEMERAL_DIR}/generated_config.cmake) # TODO: Move the rest of this into files in ephemeral. See # https://github.com/flutter/flutter/issues/57146. set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") # Set fallback configurations for older versions of the flutter tool. if (NOT DEFINED FLUTTER_TARGET_PLATFORM) set(FLUTTER_TARGET_PLATFORM "windows-x64") endif() # === Flutter Library === set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") # Published to parent scope for install step. set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) list(APPEND FLUTTER_LIBRARY_HEADERS "flutter_export.h" "flutter_windows.h" "flutter_messenger.h" "flutter_plugin_registrar.h" "flutter_texture_registrar.h" ) list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") add_library(flutter INTERFACE) target_include_directories(flutter INTERFACE "${EPHEMERAL_DIR}" ) target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") add_dependencies(flutter flutter_assemble) # === Wrapper === list(APPEND CPP_WRAPPER_SOURCES_CORE "core_implementations.cc" "standard_codec.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") list(APPEND CPP_WRAPPER_SOURCES_PLUGIN "plugin_registrar.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") list(APPEND CPP_WRAPPER_SOURCES_APP "flutter_engine.cc" "flutter_view_controller.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") # Wrapper sources needed for a plugin. add_library(flutter_wrapper_plugin STATIC ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ) apply_standard_settings(flutter_wrapper_plugin) set_target_properties(flutter_wrapper_plugin PROPERTIES POSITION_INDEPENDENT_CODE ON) set_target_properties(flutter_wrapper_plugin PROPERTIES CXX_VISIBILITY_PRESET hidden) target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) target_include_directories(flutter_wrapper_plugin PUBLIC "${WRAPPER_ROOT}/include" ) add_dependencies(flutter_wrapper_plugin flutter_assemble) # Wrapper sources needed for the runner. add_library(flutter_wrapper_app STATIC ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_APP} ) apply_standard_settings(flutter_wrapper_app) target_link_libraries(flutter_wrapper_app PUBLIC flutter) target_include_directories(flutter_wrapper_app PUBLIC "${WRAPPER_ROOT}/include" ) add_dependencies(flutter_wrapper_app flutter_assemble) # === Flutter tool backend === # _phony_ is a non-existent file to force this command to run every time, # since currently there's no way to get a full input/output list from the # flutter tool. set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) add_custom_command( OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ${CPP_WRAPPER_SOURCES_APP} ${PHONY_OUTPUT} COMMAND ${CMAKE_COMMAND} -E env ${FLUTTER_TOOL_ENVIRONMENT} "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" ${FLUTTER_TARGET_PLATFORM} $ VERBATIM ) add_custom_target(flutter_assemble DEPENDS "${FLUTTER_LIBRARY}" ${FLUTTER_LIBRARY_HEADERS} ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ${CPP_WRAPPER_SOURCES_APP} ) ``` -------------------------------- ### TypstDiagnostic.hints Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/src/content/docs/reference/api.md Gets additional hints to help fix the error. ```APIDOC ## List get hints ### Description Gets additional hints to help fix the error. ### Method hints (getter) ### Parameters None ### Returns - **List** - A list of hints. ``` -------------------------------- ### CMake: Bundle DLL with Flutter Source: https://github.com/ajmalbuv/typst_flutter/blob/main/windows/CMakeLists.txt Exposes the pre-built DLL path to Flutter so it gets bundled into the Windows application. ```cmake set(typst_flutter_bundled_libraries "${_prebuilt_dll}" PARENT_SCOPE ) ``` -------------------------------- ### Update version in pubspec.yaml Source: https://github.com/ajmalbuv/typst_flutter/blob/main/RELEASE_PROCESS.md Before tagging, update the version number in pubspec.yaml to the new version. The example shows version 3.0.0. ```yaml # pubspec.yaml version: 3.0.0 # <-- Update this ``` -------------------------------- ### Display Typst document with TypstDocumentViewer Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/src/content/docs/guides/getting-started.md Use the TypstDocumentViewer widget to display Typst documents in your UI. It automatically manages the compilation lifecycle. The example uses SVG rendering mode for crisp vector output. ```dart import 'package:flutter/material.dart'; import 'package:typst_flutter/typst_flutter.dart'; class TypstPreview extends StatelessWidget { @override Widget build(BuildContext context) { return TypstDocumentViewer( source: r''' = Multi-page Viewer This document spans multiple pages. #pagebreak() And scrolling is instantly fast because the document handle is immutable! ''', renderMode: TypstRenderMode.svg, // Use SVG for crisp vector rendering ); } } ``` -------------------------------- ### TypstDocument.pageInfo Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/src/content/docs/reference/api.md Gets the dimensions of a specific page in points. ```APIDOC ## Future pageInfo(int pageIndex) ### Description Gets the dimensions of a specific page in points (pt). ### Method pageInfo ### Parameters #### Required Parameters - **pageIndex** (int) - Required - The index of the page. ### Returns - **Future** - A future that resolves to the page dimensions. ``` -------------------------------- ### TypstDiagnostic.message Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/src/content/docs/reference/api.md Gets the human-readable error description. ```APIDOC ## String get message ### Description Gets the human-readable error description. ### Method message (getter) ### Parameters None ### Returns - **String** - The error message. ``` -------------------------------- ### TypstDocument.pageCount Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/src/content/docs/reference/api.md Gets the total number of pages in the compiled document. ```APIDOC ## int get pageCount ### Description Gets the total number of pages in the compiled document. ### Method pageCount (getter) ### Parameters None ### Returns - **int** - The total number of pages. ``` -------------------------------- ### TypstDiagnostic.severity Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/src/content/docs/reference/api.md Gets the severity of the diagnostic. ```APIDOC ## String get severity ### Description Gets the severity (e.g. error, warning). ### Method severity (getter) ### Parameters None ### Returns - **String** - The severity level. ``` -------------------------------- ### Create a new Starlight project with Bun Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/README.md Use this command to scaffold a new Starlight project using the official template. Run it in your terminal to create a new project directory. ```bash bun create astro@latest -- --template starlight ``` -------------------------------- ### TypstCompiler.create Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/src/content/docs/reference/api.md Initializes the Typst compiler and loads native libraries into memory. ```APIDOC ## Future create({FontSource? fonts}) ### Description Initializes the compiler and loads the native libraries into memory. Optionally accepts a FontSource to load custom fonts. ### Method create ### Parameters #### Optional Parameters - **fonts** (FontSource?) - Optional - A FontSource to load custom fonts. ### Returns - **Future** - A future that resolves to the initialized TypstCompiler instance. ``` -------------------------------- ### Starlight project structure Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/README.md Shows the default folder and file layout of a Starlight project. Use this as a reference for where to place content, assets, and configuration files. ```text . ├── public/ ├── src/ │ ├── assets/ │ ├── content/ │ │ └── docs/ │ └── content.config.ts ├── astro.config.mjs ├── package.json └── tsconfig.json ``` -------------------------------- ### FontSource.none / FileSource.none Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/src/content/docs/reference/api.md Creates a FontSource or FileSource with no additional assets. ```APIDOC ## FontSource.none() / FileSource.none() ### Description Creates a FontSource or FileSource with no additional assets. ### Method none ### Parameters None ### Returns - **FontSource** or **FileSource** - An empty source. ``` -------------------------------- ### Configure Flutter Linux runner executable with CMake Source: https://github.com/ajmalbuv/typst_flutter/blob/main/example/linux/runner/CMakeLists.txt Defines the runner executable for a Flutter Linux application. Sets the minimum CMake version, declares the project, and creates the executable from main.cc, my_application.cc, and the generated plugin registrant. Applies standard build settings, adds the application ID as a preprocessor definition, links against flutter and GTK, and includes the source directory. The binary name must be changed in the top-level CMakeLists.txt, not here, or `flutter run` will break. ```cmake cmake_minimum_required(VERSION 3.13) project(runner LANGUAGES CXX) # Define the application target. To change its name, change BINARY_NAME in the # top-level CMakeLists.txt, not the value here, or `flutter run` will no longer # work. # # Any new source files that you add to the application should be added here. add_executable(${BINARY_NAME} "main.cc" "my_application.cc" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" ) # Apply the standard set of build settings. This can be removed for applications # that need different build settings. apply_standard_settings(${BINARY_NAME}) # Add preprocessor definitions for the application ID. add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") # Add dependency libraries. Add any application-specific dependencies here. target_link_libraries(${BINARY_NAME} PRIVATE flutter) target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") ``` -------------------------------- ### CMake: Define pre-built DLL path Source: https://github.com/ajmalbuv/typst_flutter/blob/main/windows/CMakeLists.txt Sets the path to the pre-built typst_flutter.dll relative to the plugin's windows directory. ```cmake set(_prebuilt_dll "${CMAKE_CURRENT_SOURCE_DIR}/../.typst_flutter_prebuilt/windows/typst_flutter.dll" ) ``` -------------------------------- ### Run integration test with flutter test Source: https://github.com/ajmalbuv/typst_flutter/blob/main/README.md Run the integration test for the package. Because the package relies on native Rust libraries via FFI, unit tests must be run as integration tests against a host platform. ```bash flutter test integration_test/simple_test.dart ``` -------------------------------- ### TypstCompilerProvider usage Source: https://github.com/ajmalbuv/typst_flutter/blob/main/GEMINI.md Shows how to wrap your app with TypstCompilerProvider to share a single background compiler globally; any TypstView or TypstDocumentViewer inside will automatically reuse it. ```dart // Wrap your app/page to share a single background compiler globally TypstCompilerProvider( compiler: mySharedCompiler, child: MyApp(), ) // Any TypstView or TypstDocumentViewer deep inside will automatically reuse it! ``` -------------------------------- ### Rust Cargo.toml key dependencies Source: https://github.com/ajmalbuv/typst_flutter/blob/main/GEMINI.md Key dependencies for the Rust crate, including the Typst compiler, PDF/render/SVG exporters, the Flutter Rust Bridge, and HTTP/archive utilities for package resolution. ```toml typst = "0.15.0" # core compiler typst-pdf = "0.15.0" # PDF export typst-render = "0.15.0" # raster image render (RGBA pixels) typst-svg = "0.15.0" # SVG export flutter_rust_bridge = "2" # Dart ↔ Rust bridge time = "0.3" # date/time for typst::World::today() ureq = "3" # HTTP client for package resolution (rustls TLS backend) flate2 = "1" # gzip decompression for package archives tar = "0.4" # tar archive unpacking ``` -------------------------------- ### Share a compiler with TypstCompilerProvider Source: https://github.com/ajmalbuv/typst_flutter/blob/main/README.md Wrap your app with TypstCompilerProvider to share a single compiler instance across TypstView and TypstDocumentViewer widgets, avoiding spawning a new Rust thread per widget. Initialize the compiler once and pass it to the provider. ```dart // 1. Initialize once final compiler = await TypstCompiler.create(); // 2. Wrap your app TypstCompilerProvider( compiler: compiler, child: Scaffold( body: ListView( children: [ // 3. These render instantly using the shared engine! TypstView.source(source: '$ x^2 + y^2 = r^2 $'), TypstView.source(source: '$ e^(i pi) + 1 = 0 $'), ], ) ) ) ``` -------------------------------- ### CMake: Set minimum version and project Source: https://github.com/ajmalbuv/typst_flutter/blob/main/windows/CMakeLists.txt Specifies the minimum CMake version (3.14) and declares the project with CXX language. ```cmake cmake_minimum_required(VERSION 3.14) project(typst_flutter LANGUAGES CXX) ``` -------------------------------- ### TypstDocumentViewer (self-managed) Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/src/content/docs/reference/api.md A high-level widget for displaying scrollable Typst documents with self-managed compilation. ```APIDOC ## TypstDocumentViewer({required String source, TypstRenderMode renderMode}) ### Description A high-level widget for displaying scrollable Typst documents. Self-manages compilation from source. ### Method TypstDocumentViewer (constructor) ### Parameters #### Required Parameters - **source** (String) - Required - The Typst source code. #### Optional Parameters - **renderMode** (TypstRenderMode) - Optional - The render mode (svg or raster). Defaults to svg. ### Returns - **TypstDocumentViewer** - The widget instance. ``` -------------------------------- ### TypstView widget usage Source: https://github.com/ajmalbuv/typst_flutter/blob/main/GEMINI.md Shows the two ways to use the TypstView widget: from a pre-compiled document (recommended) or via TypstView.source for self-managed compilation. Both accept pageIndex and renderMode (svg or raster). ```dart // Option 1: From a pre-compiled document (recommended) TypstView( document: myTypstDoc, pageIndex: 0, renderMode: TypstRenderMode.svg, // or .raster ) // Option 2: Self-managed compilation (convenience) TypstView.source( source: r'= Hello, Typst!', fonts: FontSource.assets(['assets/NotoSans.ttf']), pageIndex: 0, renderMode: TypstRenderMode.svg, ) ``` -------------------------------- ### CMakeLists.txt: Flutter Linux Build Configuration Source: https://github.com/ajmalbuv/typst_flutter/blob/main/example/linux/flutter/CMakeLists.txt This CMake file controls Flutter-level build steps for Linux. It sets up system dependencies (GTK, GLIB, GIO), defines the Flutter library and headers, and adds a custom command to run the Flutter tool backend. It should not be edited. ```cmake # This file controls Flutter-level build steps. It should not be edited. cmake_minimum_required(VERSION 3.10) set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") # Configuration provided via flutter tool. include(${EPHEMERAL_DIR}/generated_config.cmake) # TODO: Move the rest of this into files in ephemeral. See # https://github.com/flutter/flutter/issues/57146. # Serves the same purpose as list(TRANSFORM ... PREPEND ...), # which isn't available in 3.10. function(list_prepend LIST_NAME PREFIX) set(NEW_LIST "") foreach(element ${${LIST_NAME}}) list(APPEND NEW_LIST "${PREFIX}${element}") endforeach(element) set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) endfunction() # === Flutter Library === # System-level dependencies. find_package(PkgConfig REQUIRED) pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") # Published to parent scope for install step. set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) list(APPEND FLUTTER_LIBRARY_HEADERS "fl_basic_message_channel.h" "fl_binary_codec.h" "fl_binary_messenger.h" "fl_dart_project.h" "fl_engine.h" "fl_json_message_codec.h" "fl_json_method_codec.h" "fl_message_codec.h" "fl_method_call.h" "fl_method_channel.h" "fl_method_codec.h" "fl_method_response.h" "fl_plugin_registrar.h" "fl_plugin_registry.h" "fl_standard_message_codec.h" "fl_standard_method_codec.h" "fl_string_codec.h" "fl_value.h" "fl_view.h" "flutter_linux.h" ) list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") add_library(flutter INTERFACE) target_include_directories(flutter INTERFACE "${EPHEMERAL_DIR}" ) target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") target_link_libraries(flutter INTERFACE PkgConfig::GTK PkgConfig::GLIB PkgConfig::GIO ) add_dependencies(flutter flutter_assemble) # === Flutter tool backend === # _phony_ is a non-existent file to force this command to run every time, # since currently there's no way to get a full input/output list from the # flutter tool. add_custom_command( OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} ${CMAKE_CURRENT_BINARY_DIR}/_phony_ COMMAND ${CMAKE_COMMAND} -E env ${FLUTTER_TOOL_ENVIRONMENT} "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} VERBATIM ) add_custom_target(flutter_assemble DEPENDS "${FLUTTER_LIBRARY}" ${FLUTTER_LIBRARY_HEADERS} ) ``` -------------------------------- ### FontSource.bytes / FileSource.bytes Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/src/content/docs/reference/api.md Loads files from raw memory buffers. ```APIDOC ## FontSource.bytes(...) / FileSource.bytes(...) ### Description Loads files from raw memory buffers. ### Method bytes ### Parameters #### Required Parameters - **...** (varies) - Required - The raw byte data. ### Returns - **FontSource** or **FileSource** - A source that loads from raw memory buffers. ``` -------------------------------- ### FRB-bridged TypstEngine and CompiledDocument API Source: https://github.com/ajmalbuv/typst_flutter/blob/main/GEMINI.md FRB-bridged API for the TypstEngine and CompiledDocument types. TypstEngine is opaque and stateful, holding a SimpleWorld; CompiledDocument is opaque and immutable. The compile method accepts markup, virtual files, optional system time, inputs, and a package flag, returning a CompiledDocument or TypstCompileError. ```rust // ── TypstEngine (opaque, stateful) ────────────────────────── #[frb(opaque)] pub struct TypstEngine { world: SimpleWorld } impl TypstEngine { #[frb(sync)] pub fn new() -> Self; // bundled fonts loaded pub fn add_fonts(&mut self, font_data: Vec>); pub fn compile( &mut self, markup: String, files: Vec, sys_time: Option, inputs: Option>, allow_packages: bool, ) -> Result; } // ── CompiledDocument (opaque, immutable) ──────────────────── #[frb(opaque)] pub struct CompiledDocument { inner: PagedDocument } impl CompiledDocument { pub fn page_count(&self) -> usize; pub fn page_info(&self, index: usize) -> Result; pub fn render_page(&self, index: usize, pixel_per_pt: f32) -> Result; pub fn export_pdf(&self) -> Result, String>; pub fn export_svg(&self, index: usize) -> Result; } ``` -------------------------------- ### Add typst_flutter package with flutter pub add Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/src/content/docs/guides/getting-started.md Run this command in your Flutter project root to add the typst_flutter dependency to pubspec.yaml. ```bash flutter pub add typst_flutter ``` -------------------------------- ### TypstCompiler API Source: https://github.com/ajmalbuv/typst_flutter/blob/main/GEMINI.md Shows the public API of the TypstCompiler class: create() loads the native library and resolves fonts, addFonts() adds more fonts, compile() turns source into a TypstDocument, query() uses a Typst selector, dispose() releases native resources, and compilerVersion returns the embedded Typst version. ```dart // Create a compiler instance (loads native library, resolves fonts) static Future create({FontSource? fonts}) // Add more fonts after creation Future addFonts(FontSource fonts) // Compile source → opaque TypstDocument handle Future compile({ required String source, FileSource? files, DateTime? date, Map? inputs, bool allowPackages = true, }) // Query document structure/metadata using a Typst selector Future query({ required TypstDocument document, required String selector, }) // Release native resources void dispose() // Version of embedded Typst compiler Future get compilerVersion ``` -------------------------------- ### TypstDocumentViewer.document Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/src/content/docs/reference/api.md A high-level widget for displaying scrollable Typst documents from a pre-compiled document. ```APIDOC ## TypstDocumentViewer.document({required TypstDocument document, TypstRenderMode renderMode}) ### Description A high-level widget for displaying scrollable Typst documents from a pre-compiled document. ### Method TypstDocumentViewer.document (constructor) ### Parameters #### Required Parameters - **document** (TypstDocument) - Required - The pre-compiled Typst document. #### Optional Parameters - **renderMode** (TypstRenderMode) - Optional - The render mode (svg or raster). Defaults to raster. ### Returns - **TypstDocumentViewer** - The widget instance. ``` -------------------------------- ### Add typst_flutter dependency to pubspec.yaml Source: https://github.com/ajmalbuv/typst_flutter/blob/main/README.md Add the typst_flutter package to your pubspec.yaml to use the library. ```yaml dependencies: typst_flutter: ^3.0.0 ``` -------------------------------- ### TypstView Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/src/content/docs/reference/api.md A widget that renders exactly one page of a Typst document. ```APIDOC ## TypstView({required TypstDocument document, required int pageIndex, TypstRenderMode renderMode}) ### Description A widget that renders exactly one page of a Typst document. Useful for custom paging logic. ### Method TypstView (constructor) ### Parameters #### Required Parameters - **document** (TypstDocument) - Required - The Typst document. - **pageIndex** (int) - Required - The index of the page to render. #### Optional Parameters - **renderMode** (TypstRenderMode) - Optional - The render mode (svg or raster). Defaults to svg. ### Returns - **TypstView** - The widget instance. ``` -------------------------------- ### TypstCompiler.compile Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/src/content/docs/reference/api.md Compiles Typst source code into a TypstDocument handle. ```APIDOC ## Future compile({required String source, FileSource? files, DateTime? date}) ### Description Compiles the Typst source into an opaque TypstDocument handle. The compiled document lives in Rust memory, ensuring fast metadata access and eliminating race conditions. ### Method compile ### Parameters #### Required Parameters - **source** (String) - Required - The Typst source code to compile. #### Optional Parameters - **files** (FileSource?) - Optional - A FileSource for additional files. - **date** (DateTime?) - Optional - The date to use for compilation. ### Returns - **Future** - A future that resolves to the compiled TypstDocument. ``` -------------------------------- ### TypstCompiler.addFonts Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/src/content/docs/reference/api.md Adds additional fonts to an already initialized compiler. ```APIDOC ## Future addFonts(FontSource fonts) ### Description Adds additional fonts to an already initialized compiler. ### Method addFonts ### Parameters #### Required Parameters - **fonts** (FontSource) - Required - The FontSource containing the fonts to add. ### Returns - **Future** - A future that completes when the fonts have been added. ``` -------------------------------- ### Configure Flutter Windows runner CMakeLists.txt Source: https://github.com/ajmalbuv/typst_flutter/blob/main/example/windows/runner/CMakeLists.txt CMake configuration for the Windows runner of a Flutter application. Defines the executable target with required source files, applies standard build settings, sets version preprocessor definitions, disables NOMINMAX, links Flutter libraries and dwmapi.lib, and adds the flutter_assemble dependency. ```cmake cmake_minimum_required(VERSION 3.14) project(runner LANGUAGES CXX) # Define the application target. To change its name, change BINARY_NAME in the # top-level CMakeLists.txt, not the value here, or `flutter run` will no longer # work. # # Any new source files that you add to the application should be added here. add_executable(${BINARY_NAME} WIN32 "flutter_window.cpp" "main.cpp" "utils.cpp" "win32_window.cpp" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" "Runner.rc" "runner.exe.manifest" ) # Apply the standard set of build settings. This can be removed for applications # that need different build settings. apply_standard_settings(${BINARY_NAME}) # Add preprocessor definitions for the build version. target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") # Disable Windows macros that collide with C++ standard library functions. target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") # Add dependency libraries and include directories. Add any application-specific # dependencies here. target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") # Run the Flutter tool portions of the build. This must not be removed. add_dependencies(${BINARY_NAME} flutter_assemble) ``` -------------------------------- ### TypstRenderResult.bytes Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/src/content/docs/reference/api.md Raw RGBA pixel data. ```APIDOC ## Uint8List bytes ### Description Raw RGBA pixel data. ### Method bytes (property) ### Parameters None ### Returns - **Uint8List** - The raw RGBA pixel data. ``` -------------------------------- ### TypstView usage Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/src/content/docs/reference/api.md Renders a single page of a Typst document using the TypstView widget. Requires a pre-compiled document, a page index, and a render mode. ```dart TypstView( document: myTypstDoc, pageIndex: 0, renderMode: TypstRenderMode.svg, ) ``` -------------------------------- ### FontSource.assets / FileSource.assets Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/src/content/docs/reference/api.md Loads files directly from Flutter assets. ```APIDOC ## FontSource.assets(...) / FileSource.assets(...) ### Description Loads files directly from Flutter assets. ### Method assets ### Parameters #### Required Parameters - **...** (varies) - Required - The asset paths or identifiers. ### Returns - **FontSource** or **FileSource** - A source that loads from Flutter assets. ``` -------------------------------- ### Bridge architecture: Dart to Rust via FRB Source: https://github.com/ajmalbuv/typst_flutter/blob/main/GEMINI.md Architecture diagram showing the Dart-to-Rust bridge via flutter_rust_bridge (FRB). It traces the compile call from TypstCompiler.compile() through TypstEngine::compile() to typst::compile(), and lists the lazy document operations (exportPdf, renderSvg, renderRaster, pageInfo, dispose) that act on the opaque CompiledDocument handle. ```text Flutter app (Dart) │ │ compiler.dart │ TypstCompiler.compile(source) │ │ │ └── TypstEngine.compile() ← FRB managed Isolate │ │ │ ══════════════════ │ FRB Generated Bridge │ ══════════════════ │ │ │ rust/src/api/typst.rs │ TypstEngine::compile(markup, files, sys_time) │ │ │ ├── configures SimpleWorld (implements typst::World) │ ├── calls typst::compile(&world) │ └── returns CompiledDocument { inner: PagedDocument } │ │ document.dart │ TypstDocument (wraps CompiledDocument) │ │ │ ├── .exportPdf() → CompiledDocument.export_pdf() → typst_pdf::pdf() │ ├── .renderSvg(i) → CompiledDocument.export_svg(i) → typst_svg::svg() │ ├── .renderRaster(i) → CompiledDocument.render_page(i) → typst_render::render() │ ├── .pageInfo(i) → page dimensions in points │ └── .dispose() → drops the Rust PagedDocument ``` -------------------------------- ### TypstDocument.dispose Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/src/content/docs/reference/api.md Eagerly releases native memory held by the Rust PagedDocument. ```APIDOC ## void dispose() ### Description Eagerly releases the native memory held by the Rust PagedDocument. ### Method dispose ### Parameters None ### Returns - **void** - No return value. ``` -------------------------------- ### TypstDocument.renderRaster Source: https://github.com/ajmalbuv/typst_flutter/blob/main/docs/src/content/docs/reference/api.md Renders a specific page to raw RGBA pixels. ```APIDOC ## Future renderRaster({required int pageIndex, double pixelsPerPt = 2.0}) ### Description Renders a specific page to raw RGBA pixels. ### Method renderRaster ### Parameters #### Required Parameters - **pageIndex** (int) - Required - The index of the page to render. #### Optional Parameters - **pixelsPerPt** (double) - Optional - The resolution in pixels per point. Defaults to 2.0. ### Returns - **Future** - A future that resolves to the render result containing raw RGBA pixel data. ```