Skip to content
Hosmel Quintana

Converting Documents

Convert local files, uploads, and bytes to Markdown or to anydoc's document model.

Anydoc converts a document from one of four sources: a local file, an upload, bytes, or a file on a storage disk. Pick the source, name its format if needed, then call .markdown() for Markdown or .document() for anydoc's document model.

Local files

anydoc.file(path) converts a file on the local disk. It takes a &str, String, &Path, or PathBuf. A relative path resolves against the application's base path, as it does for laravel::http::File, and an absolute path is used as it is:

rust
use std::path::PathBuf;

use laravel::prelude::*;
use laravel_anydoc::Anydoc;

pub async fn convert(anydoc: Inject<Anydoc>, path: PathBuf) -> laravel::Result<(String, String)> {
    let report = anydoc.file("storage/app/report.docx").markdown().await?;
    let other = anydoc.file(path).markdown().await?;

    Ok((report, other))
}

Conversion runs on Laravel's blocking thread pool, so it does not block the async runtime. It uses the application's context, so call it while the application handles a request, runs a command, or processes a job.

Uploaded files

anydoc.file(&upload) also takes a laravel::http::UploadedFile, which the package reads with UploadedFile::bytes():

rust
use laravel::http::UploadedFile;
use laravel::prelude::*;
use laravel_anydoc::Anydoc;

#[laravel::input]
#[validate(anyone)]
pub struct ImportRequest {
    #[validate(required)]
    document: UploadedFile,
}

pub async fn import(anydoc: Inject<Anydoc>, Valid(form): Valid<ImportRequest>) -> laravel::Result<String> {
    anydoc.file(&form.document).markdown().await
}

The route's LimitUploads middleware limits the size of uploads, 16 MiB by default. ANYDOC_MAX_FILE_SIZE adds the package's own limit; see Size limit.

Bytes

anydoc.bytes(bytes) converts a document you already hold in memory. It takes anything that converts into a Vec<u8>:

rust
use laravel::prelude::*;
use laravel_anydoc::Anydoc;

pub async fn convert(anydoc: Inject<Anydoc>, bytes: Vec<u8>) -> laravel::Result<String> {
    anydoc.bytes(bytes).markdown().await
}

Bytes have no extension, so the format is detected from the content alone. Name it with .format() when the content carries no signature, such as CSV; see Formats.