Saving documents
to: saves the document when the block ends. The extension picks the format, and a list of paths saves several formats:
<KScript.Document title="Notes" to="notes.pdf, notes.docx, notes.tex">
<Paragraph>Saved three ways.</Paragraph>
</KScript.Document>import KScript.Document
Document(title: 'Notes', to: ['notes.pdf', 'notes.docx', 'notes.tex']) {
Paragraph "Saved three ways."
}| Extension | What you get |
|---|---|
.pdf |
A PDF, laid out by KScript: page numbers, a clickable table of contents and bookmarks, links, and images. |
.docx |
A Word document with real headings, numbered lists, footnotes, equations Word can edit, and a table of contents Word fills in. |
.tex |
A LaTeX file for pdflatex, with \section, \label/\ref, amsmath, booktabs and \bibitems. Images are referred to by path. |
.md |
Markdown with $...$ maths, GitHub tables and footnotes. |
.html |
One HTML page: styles, MathML maths and images are all inside it. |
into: keeps the document in a variable instead (or as well), so you can save it later or turn it into text:
<import package="KScript.Document" />
<Document title="Report" into="doc">
<Paragraph>Hello.</Paragraph>
</Document>
<do>$doc->save('report.pdf')</do>
<echo>{ $doc->pages() } pages, { $doc->words() } words</echo>import KScript.Document
Document(title: 'Report', into: doc) {
Paragraph "Hello."
}
$doc->save('report.pdf')
echo "{ $doc->pages() } pages, { $doc->words() } words"| Method | What it does |
|---|---|
->save(path, as?) |
Saves in the format selected by the filename extension or by as:. |
->pages() |
How many pages the PDF has. |
->words() |
How many words the text has, not counting maths and code. |
->convert(to: markdown), ->convert(to: latex) and ->convert(to: html) |
The document as text, to print, send or save yourself. |
->bytes(as: pdf|docx|html) |
The rendered file as a base64 value, without writing a file. |
$doc.title is the title.
A route can send a document without saving it first. ->bytes(as: pdf) renders it in memory, and @response() sends the bytes:
<import package="KScript.Http" />
<import package="KScript.Document" />
<fn name="invoice" params="id: int">
<Document title="Invoice { $id }" into="doc">
<Paragraph>Thank you for your order.</Paragraph>
</Document>
<return value="@response($doc->bytes(as: pdf), type: 'application/pdf', headers: { 'Content-Disposition': "inline; filename=invoice-{ $id }.pdf" })" />
</fn>import KScript.Http
import KScript.Document
fn invoice(id: int) {
Document(title: "Invoice { $id }", into: doc) {
Paragraph "Thank you for your order."
}
return @response($doc->bytes(as: pdf), type: 'application/pdf', headers: { 'Content-Disposition': "inline; filename=invoice-{ $id }.pdf" })
}