CloudPDF
DocsPricing
Start building

Quick start

This guide opens a PDF, shows its first page, searches it, highlights a match and saves the result.

1. Install#

npm install @cloudpdf/engine@next

2. Create the engine#

Create one engine for your whole app and reuse it.

import { cloudEngine } from '@cloudpdf/engine';
 
const engine = cloudEngine();

It connects to CloudPDF SaaS. Your own server names itself: cloudEngine({ baseUrl: 'https://pdf.example.com' }). Creating the engine makes no request yet.

3. Open a PDF#

Open the document with a token your backend created for this user and this document. The token also says what the user may do with it.

const doc = await engine.open({ kind: 'token', token: () => fetchDocumentToken('invoice') });

Authentication shows how your backend creates the token, and the other ways to open a document.

doc is your handle to the open document. Everything else starts from it.

4. Show the first page#

List the pages, then render the first one as an image:

const { pages } = await doc.pages.list();
const firstPage = doc.page(pages[0].ref);
 
const image = await firstPage.render.image({ viewport: { kind: 'width', width: 800 } });
const { url } = await image.objectUrl();
 
document.querySelector('img')!.src = url;

Each page has a ref: its address in the document. doc.page(ref) gives you a handle for that page, and you pass the same ref to anything that works on pages.

5. Read the text#

const { text } = await firstPage.text.get();
console.log(text);

Search the whole document. Each match says which page it’s on and where it is:

const { matches } = await doc.search.query({ text: 'total' });
 
console.log(`${matches.length} matches`);

7. Highlight a match#

A match carries one segment per line it covers, each with the four corners of that piece of text. A highlight takes exactly those corners:

const match = matches[0];
 
await doc.page(match.page).annotations.create({
  subtype: 'highlight',
  quadPoints: match.segments.map((segment) => segment.quad),
  color: '#ffd700',
});

Render the page again and the highlight is there. See Highlights & text markup for underlines, strikeouts and the other fields.

8. Save#

download() returns the PDF with your changes, as bytes:

const bytes = await doc.download();

You don’t need to save to keep the highlight: the server stored it when you created it. download() is for when you want the file itself.

9. Clean up#

Close the document when you’re done with it. Keep the engine for the next one.

await doc.close();

Every call returns a promise you can cancel: keep it and call .abort(), for example when the user scrolls past a page before its image arrives. See Errors & cancelling.

Next steps#