Skip to content

Commit

Permalink
feat(pkg::compiler): export to pdf
Browse files Browse the repository at this point in the history
  • Loading branch information
Myriad-Dreamin committed Sep 27, 2023
1 parent a30cad9 commit 70415af
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 35 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions packages/compiler/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ typst-ts-compiler = { version = "0.4.0-rc1", default-features = false, features
typst-ts-ast-exporter.workspace = true
typst-ts-canvas-exporter.workspace = true
typst-ts-svg-exporter.workspace = true
typst-ts-pdf-exporter.workspace = true

[dev-dependencies]
wasm-bindgen-test.workspace = true
Expand Down
27 changes: 16 additions & 11 deletions packages/compiler/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ use typst_ts_compiler::{
vfs::browser::ProxyAccessModel,
world::WorldSnapshot,
};
use typst_ts_core::{cache::FontInfoCache, error::prelude::*, Exporter, FontLoader, FontSlot};
use typst_ts_core::{
cache::FontInfoCache, error::prelude::*, DynExporter, Exporter, FontLoader, FontSlot,
TypstDocument,
};
use wasm_bindgen::prelude::*;

use crate::utils::console_log;
Expand Down Expand Up @@ -194,26 +197,28 @@ impl TypstCompiler {
}

pub fn get_artifact(&mut self, fmt: String) -> Result<Vec<u8>, JsValue> {
if fmt != "vector" {
return Err(error_once!("Unsupported fmt", format: fmt).into());
}

let ir_exporter = typst_ts_core::exporter_builtins::VecExporter::new(
typst_ts_svg_exporter::SvgModuleExporter::default(),
);
let vec_exporter: DynExporter<TypstDocument, Vec<u8>> = match fmt.as_str() {
"vector" => Box::new(typst_ts_core::exporter_builtins::VecExporter::new(
typst_ts_svg_exporter::SvgModuleExporter::default(),
)),
"pdf" => Box::<typst_ts_pdf_exporter::PdfDocExporter>::default(),
_ => {
return Err(error_once!("Unsupported fmt", format: fmt).into());
}
};

let doc = self.compiler.compile().map_err(|e| format!("{e:?}"))?;
let artifact_bytes = ir_exporter
let artifact_bytes = vec_exporter
.export(self.compiler.world(), doc)
.map_err(|e| format!("{e:?}"))?;
Ok(artifact_bytes)
}

pub fn compile(&mut self, main_file_path: String) -> Result<Vec<u8>, JsValue> {
pub fn compile(&mut self, main_file_path: String, fmt: String) -> Result<Vec<u8>, JsValue> {
self.compiler
.set_entry_file(Path::new(&main_file_path).to_owned());

self.get_artifact("vector".into())
self.get_artifact(fmt)
}
}

Expand Down
73 changes: 50 additions & 23 deletions packages/typst.ts/examples/compiler.html
Original file line number Diff line number Diff line change
Expand Up @@ -24,36 +24,54 @@

document.ready(() => {
const terminalContent = document.getElementById('terminal-content');
terminalContent.innerHTML = 'Compiling...';
terminalContent.innerHTML = 'Downloading font assets...';

const runCompile = async () => {
const runCompile = async fmt => {
const begin = performance.now();
compilerPlugin.reset();
const ast = await compilerPlugin.getAst('corpus/skyzh-cv/main.typ');
const end = performance.now();
const rounded = Math.round((end - begin) * 1000) / 1000;

const compileInfo = `---
<span style="color:#c0caf5">Compiled in <span style="color:#7dcfff">${rounded}</span>ms</span>`;
if (fmt === 'ast') {
const ast = await compilerPlugin.getAst('corpus/skyzh-cv/main.typ');
const end = performance.now();
const rounded = Math.round((end - begin) * 1000) / 1000;

terminalContent.innerHTML = [compileInfo, ast].join('\n');
const compileInfo = `---
<span style="color:#c0caf5">Compiled to AST in <span style="color:#7dcfff">${rounded}</span>ms</span>`;

terminalContent.innerHTML = [compileInfo, ast].join('\n');
} else if (fmt === 'pdf') {
const pdfData = await compilerPlugin.compile({
mainFilePath: 'corpus/skyzh-cv/main.typ',
format: 'pdf',
});
const end = performance.now();
const rounded = Math.round((end - begin) * 1000) / 1000;

const compileInfo = `<span style="color:#c0caf5">Compiled to PDF in <span style="color:#7dcfff">${rounded}</span>ms</span>`;

terminalContent.innerHTML = compileInfo;
console.log(pdfData);
var pdfFile = new Blob([pdfData], { type: 'application/pdf' });

// Create element with <a> tag
const link = document.createElement('a');

// Add file content in the object URL
link.href = URL.createObjectURL(pdfFile);

// Add file name
link.target = '_blank';

// Add click event to <a> tag to save file.
link.click();
URL.revokeObjectURL(link.href);
}
};

let compilerPlugin = window.TypstCompileModule.createTypstCompiler();
compilerPlugin
.init({
beforeBuild: [
window.TypstCompileModule.preloadRemoteFonts([
'http://localhost:20810/assets/fonts/LinLibertine_R.ttf',
'http://localhost:20810/assets/fonts/LinLibertine_RB.ttf',
'http://localhost:20810/assets/fonts/LinLibertine_RBI.ttf',
'http://localhost:20810/assets/fonts/LinLibertine_RI.ttf',
'http://localhost:20810/assets/fonts/NewCMMath-Book.otf',
'http://localhost:20810/assets/fonts/NewCMMath-Regular.otf',
]),
// window.TypstCompileModule.preloadSystemFonts({
// byFamily: ['Segoe UI Symbol'],
// }),
window.TypstCompileModule.withAccessModel(
new window.TypstCompileModule.FetchAccessModel('http://localhost:20810'),
),
Expand All @@ -63,9 +81,12 @@
})
.then(() => {
document.getElementById('compile-button').addEventListener('click', () => {
runCompile();
runCompile('ast');
});
document.getElementById('compile-to-pdf-button').addEventListener('click', () => {
runCompile('pdf');
});
return runCompile();
return runCompile('ast');
});
});
</script>
Expand Down Expand Up @@ -107,7 +128,12 @@
}

.terminal pre {
font-family: SFMono-Regular, Consolas, Liberation Mono, Menlo, monospace;
font-family:
SFMono-Regular,
Consolas,
Liberation Mono,
Menlo,
monospace;
color: white;
padding: 0 1rem 1rem;
margin: 0;
Expand All @@ -133,7 +159,8 @@
</div>
<div class="content">
<div>
<button id="compile-button">Compile</button>
<button id="compile-button">Export to AST</button>
<button id="compile-to-pdf-button">Export to PDF</button>
</div>
<div class="terminal">
<pre id="terminal-content">hello world</pre>
Expand Down
3 changes: 2 additions & 1 deletion packages/typst.ts/src/compiler.mts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { LazyWasmModule } from './wasm.mjs';

export interface CompileOptions {
mainFilePath: string;
format: 'vector' | 'pdf';
}

/**
Expand Down Expand Up @@ -137,7 +138,7 @@ class TypstCompilerDriver {

compile(options: CompileOptions): Promise<Uint8Array> {
return new Promise<Uint8Array>(resolve => {
resolve(this.compiler.compile(options.mainFilePath));
resolve(this.compiler.compile(options.mainFilePath, options.format || 'vector'));
});
}

Expand Down

0 comments on commit 70415af

Please sign in to comment.