Rasura

Quickstart

Four short programs covering the paths most callers need first.

Change a word

Edits are staged in a session and applied together. Nothing is written until commit(), which is what lets undo restore the exact prior bytes.

edit.js
1import { Pdf } from 'rasura'
2
3const doc = await Pdf.open(await file.arrayBuffer())
4const page = await doc.page(0)
5
6// Paragraphs come back reconstructed, in reading order.
7const [first] = page.paragraphs()
8console.log(first.text)
9
10// Edits are staged in a session, never on the document directly.
11const session = doc.edit()
12
13// Replace characters 0 to 5 of that paragraph.
14const outcome = await session.replaceText(first.id, { start: 0, end: 5 }, 'Hello')
15console.log(outcome.fidelity) // 'exact'
16
17const { bytes } = await session.commit()
18await doc.close()

The saved bytes are the original file with one revision appended. Everything you did not touch is byte-identical.

Read the structure

read.js
const info = await doc.info()
console.log(info.pageCount, info.documentKind, info.taggedStatus)
// Anything the file got wrong that Rasura tolerated to open it.
for (const l of info.leniencies) console.log(l.kind, l.detail)
const page = await doc.page(0)
console.log(page.paragraphs().length, 'paragraphs')
console.log(page.tables().length, 'tables')
console.log(page.images().length, 'images')

leniencies is worth reading even when nothing is wrong. It lists every specification deviation the parser accepted: a broken cross-reference table, a wrong /Length, a header that was not at byte zero. No viewer will tell you these.

Make a document

Describe the content as blocks and give it a typeface. The layout engine decides the measure, the leading, the pagination and the position of every line.

create.js
const font = await fetch('/Inter-Regular.ttf').then((r) => r.arrayBuffer())
const { document, report } = await Pdf.create(
[
{ kind: 'heading', level: 1, text: 'Invoice 0042' },
{ kind: 'paragraph', text: 'Due 30 days from receipt.' },
{ kind: 'list', items: ['Design, 12 hours', 'Build, 30 hours'] },
],
font,
{ pageSize: 'a4', title: 'Invoice 0042' },
)
console.log(report.pages, report.baseFont)
const { bytes } = await document.save()

The typeface is embedded and subset to the characters used. A three-line document set in Inter carries a few kilobytes of font, not the whole file.

Handle failure

Every failure carries a code. There are fourteen, and each one tells you what to do next.

open.js
import { Pdf, PdfError } from 'rasura'
try {
var doc = await Pdf.open(bytes)
} catch (e) {
if (e instanceof PdfError && e.code === 'encrypted-password-required') {
doc = await Pdf.open(bytes, { password: await askUser() })
} else {
throw e
}
}

Note Every example on this site runs in a browser with no server. The editor at /editor is the same library doing all of it live.