### Install and Start REST Server
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/apps/server-side/nextjs.md
Installs dependencies, builds the project, and starts the server for the REST API component.
```typescript
npm install
npm run build
npm run start
```
--------------------------------
### Install and Start Client
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/apps/server-side/nextjs.md
Installs dependencies and starts the development server for the Next.js client component.
```typescript
npm install
npm run dev
```
--------------------------------
### Install Dependencies with npm ci
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/examples/electron/README.md
Run this command to install all project dependencies before starting the development server or building the project.
```bash
npm ci
```
--------------------------------
### Install MuPDF.js using yarn
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/faq/index.md
Demonstrates the command to install the mupdf package using yarn.
```bash
yarn add mupdf
```
--------------------------------
### Install MuPDF.js using pnpm
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/faq/index.md
Demonstrates the command to install the mupdf package using pnpm.
```bash
pnpm add mupdf
```
--------------------------------
### Serve local files for browser example
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/README.md
Use the http-server package to serve your local files, which is necessary for Web Workers and WASM loading in the browser example.
```bash
npx http-server -o index.html
```
--------------------------------
### Start Development Server
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/apps/client-side/vanilla.md
Execute this command to launch the HTTP server and automatically open the application in your browser.
```bash
npm start
```
--------------------------------
### Start Development Server
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/apps/client-side/vue.md
Execute this command to launch the local development server for the Vue application.
```bash
npm run dev
```
--------------------------------
### Install Sphinx and Dependencies
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/README.md
Install Sphinx and required modules within a virtual environment using pip.
```bash
python -m venv .venv
source .venv/bin/activate
pip install -r docs/requirements.txt
```
--------------------------------
### Install and Use Sphinx Autobuild
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/README.md
Install Sphinx Autobuild for live editing and hot-reloading of documentation during development.
```bash
pip install sphinx-autobuild
sphinx-autobuild --open-browser docs build
```
--------------------------------
### Run MuPDF.js Example in Node.js
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/INSTALL.md
Example script to load a PDF, render each page, and save as PNG. Requires an 'input.pdf' file and the 'fs' module.
```javascript
import * as mupdf from "mupdf"
var doc = mupdf.Document.openDocument("input.pdf")
var n = doc.countPages()
for (var i = 0; i < n; ++i) {
console.log(`Rendering page ${i+1} / ${n}.`)
var page = doc.loadPage(i)
var pixmap = page.toPixmap(mupdf.Matrix.scale(96 / 72, 96 / 72), mupdf.ColorSpace.DeviceRGB)
fs.writeFileSync(`page${i+1}.png`, pixmap.asPNG())
}
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/apps/client-side/angular.md
Run this command in your terminal to install all necessary Node.js dependencies for the Angular project.
```bash
npm install
```
--------------------------------
### Run MuPDF.js Example in Browser
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/INSTALL.md
Example HTML file to load and render the first page of a PDF in the browser. Serves the file using a local web server.
```html
```
--------------------------------
### Install MuPDF.js via Yarn/PNPM
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/llms/llms-full.txt
Alternative installation commands for MuPDF.js using Yarn or PNPM package managers.
```bash
yarn add mupdf
pnpm add mupdf
```
--------------------------------
### Package Application with npm run package
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/examples/electron/README.md
Use this command to create an installer for your Electron application on Windows or macOS. The installer file will be located in the 'release/' directory.
```bash
npm run package
```
--------------------------------
### Start Angular Development Server
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/apps/client-side/angular.md
Use this command to launch the Angular development server, which will serve your application and provide live reloading.
```bash
npx ng serve
```
--------------------------------
### Install MuPDF.js from NPM
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/INSTALL.md
Install the mupdf module using npm. Ensure your project is configured for ESM modules.
```bash
npm install mupdf
```
```bash
npm pkg set type=module
```
--------------------------------
### Verify MuPDF.js Installation
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/llms/llms-full.txt
A simple Node.js script to verify the correct installation of the mupdf package by logging the imported object.
```js
import mupdf from "mupdf";
console.log(mupdf);
```
--------------------------------
### Create Node.js Test File
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/getting-started/setup.md
Create a test file (e.g., test.mjs) to verify the NPM installation by importing and logging the mupdf object.
```javascript
import * as mupdf from "mupdf"
console.log(mupdf)
```
--------------------------------
### Render first PDF page to canvas in Browser
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/README.md
This browser example shows how to fetch a PDF, open it, render the first page to a PNG pixmap at 96 DPI, and display it as an image element on the page. Requires serving the files with a local server.
```html
```
--------------------------------
### Install MuPDF.js via NPM
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/getting-started/setup.md
Install the MuPDF.js dependency into your project using NPM. This command adds the library to your package.json.
```bash
npm install mupdf
```
--------------------------------
### Start Local HTTP Server with Python
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/getting-started/setup.md
Run a local HTTP server using Python's http.server module. This is required to serve web worker files correctly in a browser context.
```bash
python -m http.server
```
--------------------------------
### Render Page to PNG with Scaling
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/llms/llms-full.txt
Renders a page to a PNG image with a specified zoom level (DPI). This example scales the page by 2x (equivalent to 144 DPI) and includes annotations.
```javascript
const matrix = mupdf.Matrix.scale(2, 2); // 2x zoom = 144 DPI
const pixmap = page.toPixmap(
matrix,
mupdf.ColorSpace.DeviceRGB,
false, // no alpha
true // include annotations
);
const pngData = pixmap.asPNG();
fs.writeFileSync("page1.png", pngData);
```
--------------------------------
### Run a Single MuPDF.js Test File
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/examples/tests/README.md
To run a specific test file, provide its path as a parameter after the test command. For example, to run the journal test file.
```bash
npm run test -- src/journal.test.ts
```
--------------------------------
### Draw a Polygon Annotation
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/how-to-guide/annotations/drawing-and-shapes/index.md
This example shows how to create a 'Polygon' annotation by adding vertices and setting stroke and fill colors. This is used for creating triangular or other polygonal shapes.
```javascript
let fileData = fs.readFileSync("test.pdf")
let document = mupdf.Document.openDocument(fileData, "application/pdf")
let page = document.loadPage(0)
let annotation = page.createAnnotation("Polygon")
annotation.setColor([0, 0, 1])
annotation.setInteriorColor([0, 0, 1])
annotation.addVertex([10, 100])
annotation.addVertex([200, 200])
annotation.addVertex([30, 300])
annotation.update()
fs.writeFileSync("output-polygon.pdf", document.saveToBuffer("incremental").asUint8Array())
```
--------------------------------
### Draw a Square Annotation with Custom Properties
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/how-to-guide/annotations/drawing-and-shapes/index.md
This example demonstrates how to create a 'Square' annotation with specific dimensions, stroke and fill colors, border effects, and opacity. The API for 'Circle' is identical.
```javascript
let fileData = fs.readFileSync("test.pdf")
let document = mupdf.Document.openDocument(fileData, "application/pdf")
let page = document.loadPage(0)
let annotation = page.createAnnotation("Square")
annotation.setRect([100, 100, 300, 300])
annotation.setColor([0, 0, 0])
annotation.setInteriorColor([0.5, 0, 0])
annotation.setBorderEffect("Cloudy")
annotation.setBorderEffectIntensity(0.3)
annotation.setBorderWidth(5)
annotation.setOpacity(0.5)
fs.writeFileSync("output-circle.pdf", document.saveToBuffer("incremental").asUint8Array())
```
--------------------------------
### Render all PDF pages to PNG in Node.js
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/README.md
This Node.js example demonstrates how to open a PDF document, iterate through all its pages, render each page to a PNG image at 96 DPI, and save them to files. Ensure you have the 'fs' module imported.
```javascript
import * as fs from "fs"
import * as mupdf from "mupdf"
const doc = mupdf.Document.openDocument(fs.readFileSync("input.pdf"), "application/pdf")
const n = doc.countPages()
for (let i = 0; i < n; i++) {
const page = doc.loadPage(i)
const pixmap = page.toPixmap(
mupdf.Matrix.scale(96 / 72, 96 / 72), // 96 DPI
mupdf.ColorSpace.DeviceRGB
)
fs.writeFileSync(`page${i + 1}.png`, pixmap.asPNG())
pixmap.destroy()
page.destroy()
}
doc.destroy()
```
--------------------------------
### Convert PDF Page to Pixmap in TypeScript
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/README.md
Demonstrates loading a PDF, extracting a specific page, converting it to a Pixmap (image representation) using specified transformation matrices and color spaces, and saving it as a PNG. This example uses TypeScript.
```typescript
import * as mupdf from "mupdf"
import * as fs from "fs"
const buffer: Buffer = fs.readFileSync("input.pdf")
const doc: mupdf.Document = mupdf.Document.openDocument(buffer, "application/pdf")
const page: mupdf.PDFPage = doc.loadPage(0) as mupdf.PDFPage
const pixmap: mupdf.Pixmap = page.toPixmap(
mupdf.Matrix.identity,
mupdf.ColorSpace.DeviceRGB,
false,
true
)
fs.writeFileSync("output.png", pixmap.asPNG())
pixmap.destroy()
page.destroy()
doc.destroy()
```
--------------------------------
### Render PDF in a React Component
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/faq/index.md
Shows a React component that dynamically imports MuPDF.js and renders a PDF to a canvas element. This example demonstrates client-side rendering with asynchronous loading.
```javascript
// React component example
import { useEffect, useState, useRef } from 'react';
export default function PdfViewer({ pdfUrl }) {
const canvasRef = useRef(null);
useEffect(() => {
async function renderPdf() {
const mupdf = await import('mupdf');
const response = await fetch(pdfUrl);
const buffer = await response.arrayBuffer();
const doc = mupdf.Document.openDocument(
new Uint8Array(buffer),
"application/pdf"
);
const page = doc.loadPage(0);
// ... render to canvas
}
renderPdf();
}, [pdfUrl]);
return ;
}
```
--------------------------------
### Decorate Text with Highlight Annotation
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/how-to-guide/annotations/text/index.md
This example demonstrates how to add a highlight annotation to specific areas of text on a PDF page. The `setQuadPoints` method is used to define the rectangular areas to be highlighted, and the color can be set using `setColor`.
```javascript
let fileData = fs.readFileSync("test.pdf")
let document = mupdf.PDFDocument.openDocument(fileData, "application/pdf")
let page = document.loadPage(0)
let annotation = page.createAnnotation("Highlight")
annotation.setColor([1, 1, 0])
annotation.setQuadPoints([
[
20, 65,
230, 65,
20, 85,
230, 85,
],
[
20, 90,
230, 90,
20, 110,
230, 110,
],
])
annotation.update()
// Save the changes to a new file.
fs.writeFileSync("output-hl-text.pdf", document.saveToBuffer("incremental").asUint8Array())
```
--------------------------------
### Basic TypeScript Usage of MuPDF.js
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/llms/llms-full.txt
Demonstrates opening a PDF document from a buffer, loading a specific page, and converting it to a Pixmap using MuPDF.js in TypeScript. Ensure the 'mupdf' package is installed.
```ts
import mupdf from "mupdf";
import type { Document, Page, Pixmap } from "mupdf";
const doc: Document = mupdf.Document.openDocument(buffer, "application/pdf");
const page: Page = doc.loadPage(0);
const pixmap: Pixmap = page.toPixmap(
mupdf.Matrix.identity,
mupup.ColorSpace.DeviceRGB,
false,
true
);
```
--------------------------------
### Get Page Links
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/how-to-guide/annotations/links/index.md
Retrieve all links from a page and access their properties like bounds, URI, and external status. Returns an empty array if no links are found.
```javascript
let links = page.getLinks()
if (links.length) {
let link = links[0]
let linkBounds = link.getBounds()
let linkURI = link.getURI()
let linkIsExternal = link.isExternal()
}
```
--------------------------------
### Serve HTML file with http-server
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/INSTALL.md
Command to serve the example.html file using http-server for browser testing.
```bash
npx http-server -o example.html
```
--------------------------------
### Use Helper Script to Build Documentation
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/README.md
Execute the provided bash script to build the documentation. The script can also be used for live building.
```bash
bash docs/build.sh
```
```bash
bash docs/build.sh live
```
--------------------------------
### Build HTML Documentation
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/README.md
Build the HTML documentation using the sphinx-build command.
```bash
sphinx-build docs build
```
--------------------------------
### Document Page Count
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/how-to-guide/document.md
Get the total number of pages in a document.
```APIDOC
## Document Page Count
### Description
Obtain the total number of pages within a document.
### Method
- `countPages()`: Returns the number of pages in the document.
### Example
```javascript
const numPages = document.countPages();
```
```
--------------------------------
### Count Document Pages
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/how-to-guide/document.md
Use `countPages` to get the total number of pages in a document.
```javascript
const numPages = document.countPages()
```
--------------------------------
### Get Page Text
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/llms/llms-full.txt
Extracts all plain text content from a specific PDF page. Returns the text as a string.
```typescript
import * as mupdf from "mupdf"
export function getPageText(document: mupdf.PDFDocument, pageNumber: number): string {
return document.loadPage(pageNumber).toStructuredText().asText()
```
--------------------------------
### Getting Document Links
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/how-to-guide/document.md
Retrieves all the links present on a document's page, returning an array of Link objects.
```APIDOC
## Getting Document Links
Retrieves an array of Link objects from a page.
### Method
```javascript
let links = page.getLinks()
```
### Response
#### Success Response
- **links** (Array) - An array of Link objects, each containing bounds and a URI.
```
--------------------------------
### Get Page Bounds
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/how-to-guide/page.md
Retrieve the bounding box coordinates of a page. The result is an array [ulx, uly, lrx, lry].
```javascript
let rect = page.getBounds()
```
--------------------------------
### Create HTML Test File for Browser
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/getting-started/setup.md
Set up an HTML file to test MuPDF.js in a browser environment. It initializes a web worker to load the library.
```html
```
--------------------------------
### Get Page Resources XObjects
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/llms/llms-full.txt
Retrieves a list of XObject resources associated with a PDF page. Each resource is identified by a key and its value.
```typescript
export function getPageResourcesXObjects(page: mupdf.PDFPage): { key: string | number; value: string }[]
```
--------------------------------
### Get Page Annotations
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/how-to-guide/page.md
Retrieve all Annotation objects from a page by calling the getAnnotations() method. The returned value is a list of annotation objects.
```javascript
const annots = page.getAnnotations()
console.log(`Annotations=${annots}`)
```
--------------------------------
### Fresh Rebuild of Documentation
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/README.md
Perform a fresh rebuild of the documentation, ignoring cached files, by using the -E and -a flags with sphinx-build.
```bash
sphinx-build -E -a docs build
```
--------------------------------
### Get Page Resources XObjects
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/deprecated.md
Retrieves all XObjects associated with a PDF page. Ensure the page object is resolved if it's indirect.
```typescript
import * as mupdf from "mupdf"
export function getPageResourcesXObjects(page: mupdf.PDFPage): { key: string | number; value: string }[] {
let pageObj = page.getObject()
var isIndirect = pageObj.isIndirect()
if (isIndirect) {
pageObj = pageObj.resolve()
}
let res = pageObj.get("Resources")
let resXObj = res.get("XObject")
let arr: { key: string | number; value: string }[] = []
resXObj.forEach(function (value: mupdf.PDFObject, key: string | number) {
arr.push({ key: key, value: value.toString() })
})
return arr
}
```
--------------------------------
### Load a PDF document
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/faq/index.md
Opens a PDF document from a buffer and logs its name and page count. Ensure the buffer contains valid PDF data.
```javascript
const doc = mupdf.Document.openDocument(
new Uint8Array(buffer),
"application/pdf"
);
console.log(`Loaded: ${file.name}, ${doc.countPages()} pages`);
// Process document...
});
```
--------------------------------
### Get Document Metadata
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/how-to-guide/document.md
Retrieve document metadata using `getMetaData`. Common keys include 'format', 'encryption', 'info:ModDate', and 'info:Title'.
```javascript
const format = document.getMetaData("format")
const modificationDate = document.getMetaData("info:ModDate")
const author = document.getMetaData("info:Author")
```
--------------------------------
### Get Document Links in MuPDF.js
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/how-to-guide/document.md
Retrieve all hyperlink objects from a page using the `getLinks()` method. Each Link object contains its bounding box and the target URI.
```javascript
let links = page.getLinks()
```
--------------------------------
### Open PDF File in Node.js
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/faq/index.md
Demonstrates how to read a PDF file into a buffer using Node.js 'fs' module and then open it with MuPDF.js.
```javascript
import * as fs from "fs";
import mupdf from "mupdf";
// Read file as buffer
```
--------------------------------
### Get Document Metadata
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/llms/llms-full.txt
Retrieves various metadata information about the PDF document, such as page count, title, author, and creation date. Also checks if the document is a PDF.
```javascript
console.log(`Pages: ${doc.countPages()}`);
console.log(`Title: ${doc.getMetaData("info:Title")}`);
console.log(`Author: ${doc.getMetaData("info:Author")}`);
console.log(`Subject: ${doc.getMetaData("info:Subject")}`);
console.log(`Creator: ${doc.getMetaData("info:Creator")}`);
console.log(`Producer: ${doc.getMetaData("info:Producer")}`);
console.log(`CreationDate: ${doc.getMetaData("info:CreationDate")}`);
console.log(`Is PDF: ${doc.isPDF()}`);
```
--------------------------------
### Search for Text and Get Locations
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/README.md
Searches for a specific text string on the first page of a PDF and returns an array of quad coordinates for each match. Requires the input.pdf file.
```javascript
import * as fs from "fs"
import * as mupdf from "mupdf"
const doc = mupdf.Document.openDocument(fs.readFileSync("input.pdf"), "application/pdf")
const page = doc.loadPage(0)
const hits = page.search("invoice number") // returns array of Quad arrays
console.log(`Found ${hits.length} matches`)
page.destroy()
```
--------------------------------
### Build a page navigation system
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/faq/index.md
Provides functions to load a document, render pages, and navigate between them. Updates the UI to display current page information. Assumes `doc` is a loaded MuPDF document and `renderCurrentPage` and `updateUI` are defined elsewhere.
```javascript
let doc = null;
let currentPage = 0;
async function loadDocument(buffer) {
doc = mupdf.Document.openDocument(new Uint8Array(buffer), "application/pdf");
currentPage = 0;
renderCurrentPage();
updateUI();
}
function renderCurrentPage() {
const page = doc.loadPage(currentPage);
// ... render to canvas
page.destroy();
}
function nextPage() {
if (currentPage < doc.countPages() - 1) {
currentPage++;
renderCurrentPage();
updateUI();
}
}
function prevPage() {
if (currentPage > 0) {
currentPage--;
renderCurrentPage();
updateUI();
}
}
function goToPage(num) {
if (num >= 0 && num < doc.countPages()) {
currentPage = num;
renderCurrentPage();
updateUI();
}
}
function updateUI() {
document.getElementById("pageInfo").textContent =
`Page ${currentPage + 1} of ${doc.countPages()}`;
}
```
--------------------------------
### Run All MuPDF.js Tests
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/examples/tests/README.md
Execute this command to run the complete test suite for MuPDF.js.
```bash
npm run test
```
--------------------------------
### Get Structured Text as JSON
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/how-to-guide/page.md
Retrieve a structured representation of page text, including positional and font data, as a JSON object. Use 'preserve-spans' to retain span information.
```javascript
const json = page.toStructuredText("preserve-spans").asJSON()
console.log(`json=${json}`)
```
--------------------------------
### Open PDF Document and Count Pages
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/faq/index.md
Opens a PDF document from a buffer and logs the total number of pages. Ensure the document is destroyed after use to free resources.
```javascript
const buffer = fs.readFileSync("input.pdf");
// Open document
const doc = mupdf.Document.openDocument(buffer, "application/pdf");
console.log(`Pages: ${doc.countPages()}`);
// Always close when done
doc.destroy();
```
--------------------------------
### Render PDF Page to PNG
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/faq/index.md
Renders the first page of a PDF document to a PNG image file. Adjust the scaling matrix for different resolutions. Remember to destroy all created objects.
```javascript
import * as fs from "fs";
import mupdf from "mupdf";
const buffer = fs.readFileSync("input.pdf");
const doc = mupdf.Document.openDocument(buffer, "application/pdf");
const page = doc.loadPage(0);
// Create pixmap at 2x zoom (144 DPI)
const matrix = mupdf.Matrix.scale(2, 2);
const pixmap = page.toPixmap(
matrix,
mupdf.ColorSpace.DeviceRGB,
false, // no alpha
true // include annotations
);
// Save as PNG
const pngData = pixmap.asPNG();
fs.writeFileSync("page1.png", pngData);
// Cleanup
pixmap.destroy();
page.destroy();
doc.destroy();
```
--------------------------------
### Example Structured Text JSON Output
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/how-to-guide/document.md
This JSON represents the structured text extracted from a document page. It includes blocks, lines, and spans with detailed positional, font, and text content.
```json
{
"blocks": [
{
"type": "text",
"bbox": {
"x": 30,
"y": 32,
"w": 216,
"h": 13
},
"lines": [
{
"wmode": 0,
"bbox": {
"x": 30,
"y": 32,
"w": 216,
"h": 13
},
"font": {
"name": "FKGYDX+Arial",
"family": "sans-serif",
"weight": "normal",
"style": "normal",
"size": 12
},
"x": 30,
"y": 43,
"text": "Welcome to the Node server test.pdf file."
}
]
},
{
"type": "text",
"bbox": {
"x": 30,
"y": 68,
"w": 190,
"h": 13
},
"lines": [
{
"wmode": 0,
"bbox": {
"x": 30,
"y": 68,
"w": 190,
"h": 13
},
"font": {
"name": "FKGYDX+Arial",
"family": "sans-serif",
"weight": "normal",
"style": "normal",
"size": 12
},
"x": 30,
"y": 79,
"text": "Sorry there is not much to see here!"
}
]
},
{
"type": "text",
"bbox": {
"x": 568,
"y": 31,
"w": 6,
"h": 13
},
"lines": [
{
"wmode": 0,
"bbox": {
"x": 568,
"y": 31,
"w": 6,
"h": 13
},
"font": {
"name": "YDTIJL+Arial",
"family": "sans-serif",
"weight": "normal",
"style": "normal",
"size": 12
},
"x": 568,
"y": 42,
"text": "1"
}
]
},
{
"type": "text",
"bbox": {
"x": 28,
"y": 744,
"w": 84,
"h": 19
},
"lines": [
{
"wmode": 0,
"bbox": {
"x": 28,
"y": 744,
"w": 84,
"h": 19
},
"font": {
"name": "Arial",
"family": "sans-serif",
"weight": "normal",
"style": "normal",
"size": 14
},
"x": 28,
"y": 759,
"text": "Page 1 footer"
}
]
}
]
}
```
--------------------------------
### Create Internal Document Link
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/how-to-guide/annotations/links/index.md
Create an internal document link by formatting a LinkDestination object and then creating the link with the specified bounding box. Page numbers are zero-indexed.
```javascript
page.createLink([x, y, x + width, y + height], document.formatLinkURI({ type: "Fit", page: 1 }))
```
--------------------------------
### Handle User-Uploaded PDF Files
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/llms/llms-full.txt
Listens for file input changes to load and process user-uploaded PDF files. Logs the file name and page count to the console.
```html
```
--------------------------------
### Copy Page Between Documents
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/how-to-guide/page.md
Use graftPage to copy a page from one PDF document to another. This example copies the first page (index 0) of 'anotherDocument' to the end of the current document.
```javascript
let anotherDocument = mupdf.PDFDocument.openDocument(fs.readFileSync("test.pdf"), "application/pdf")
document.graftPage(-1, anotherDocument, 0)
```
--------------------------------
### Run Node.js Test Script
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/getting-started/setup.md
Execute the test script using Node.js from the command line to confirm the mupdf object is accessible.
```bash
node test.mjs
```
--------------------------------
### Implement a PDF Page Content Tracer Device
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/how-to-guide/page.md
Define a traceDevice object with methods to intercept and log PDF rendering operations. This includes handling paths, text, shades, images, and structural elements. Use this to debug or understand PDF content.
```javascript
const Q = JSON.stringify
function print(...args) {
console.log(args.join(" "))
}
var pathPrinter = {
moveTo: function (x,y) { print("moveTo", x, y) },
lineTo: function (x,y) { print("lineTo", x, y) },
curveTo: function (x1,y1,x2,y2,x3,y3) { print("curveTo", x1, y1, x2, y2, x3, y3) },
closePath: function () { print("closePath") },
}
var textPrinter = {
beginSpan: function (f,m,wmode, bidi, dir, lang) {
print("beginSpan",f,m,wmode,bidi,dir,Q(lang));
},
showGlyph: function (f,m,g,u,v,b) { print("glyph",f,m,g,String.fromCodePoint(u),v,b) },
endSpan: function () { print("endSpan"); }
}
var traceDevice = {
fillPath: function (path, evenOdd, ctm, colorSpace, color, alpha) {
print("fillPath", evenOdd, ctm, colorSpace, color, alpha)
path.walk(pathPrinter)
},
clipPath: function (path, evenOdd, ctm) {
print("clipPath", evenOdd, ctm)
path.walk(pathPrinter)
},
strokePath: function (path, stroke, ctm, colorSpace, color, alpha) {
print("strokePath", Q(stroke), ctm, colorSpace, color, alpha)
path.walk(pathPrinter)
},
clipStrokePath: function (path, stroke, ctm) {
print("clipStrokePath", Q(stroke), ctm)
path.walk(pathPrinter)
},
fillText: function (text, ctm, colorSpace, color, alpha) {
print("fillText", ctm, colorSpace, color, alpha)
text.walk(textPrinter)
},
clipText: function (text, ctm) {
print("clipText", ctm)
text.walk(textPrinter)
},
strokeText: function (text, stroke, ctm, colorSpace, color, alpha) {
print("strokeText", Q(stroke), ctm, colorSpace, color, alpha)
text.walk(textPrinter)
},
clipStrokeText: function (text, stroke, ctm) {
print("clipStrokeText", Q(stroke), ctm)
text.walk(textPrinter)
},
ignoreText: function (text, ctm) {
print("ignoreText", ctm)
text.walk(textPrinter)
},
fillShade: function (shade, ctm, alpha) {
print("fillShade", shade, ctm, alpha)
},
fillImage: function (image, ctm, alpha) {
print("fillImage", image, ctm, alpha)
},
fillImageMask: function (image, ctm, colorSpace, color, alpha) {
print("fillImageMask", image, ctm, colorSpace, color, alpha)
},
clipImageMask: function (image, ctm) {
print("clipImageMask", image, ctm)
},
beginMask: function (area, luminosity, colorspace, color) {
print("beginMask", area, luminosity, colorspace, color)
},
endMask: function () {
print("endMask")
},
popClip: function () {
print("popClip")
},
beginGroup: function (area, isolated, knockout, blendmode, alpha) {
print("beginGroup", area, isolated, knockout, blendmode, alpha)
},
endGroup: function () {
print("endGroup")
},
beginTile: function (area, view, xstep, ystep, ctm, id) {
print("beginTile", area, view, xstep, ystep, ctm, id)
return 0
},
endTile: function () {
print("endTile")
},
beginLayer: function (name) {
print("beginLayer", name)
},
endLayer: function () {
print("endLayer")
},
beginStructure: function (structure, raw, uid) {
print("beginStructure", structure, raw, uid)
},
endStructure: function () {
print("endStructure")
},
beginMetatext: function (meta, metatext) {
print("beginMetatext", meta, metatext)
},
endMetatext: function () {
print("endMetatext")
},
renderFlags: function (set, clear) {
print("renderFlags", set, clear)
},
setDefaultColorSpaces: function (colorSpaces) {
print("setDefaultColorSpaces", colorSpaces.getDefaultGray(),
colorSpaces.getDefaultRGB(), colorSpaces.getDefaultCMYK(),
colorSpaces.getOutputIntent())
},
close: function () {
print("close")
},
}
var doc = mupdf.PDFDocument.openDocument(fs.readFileSync("test.pdf"), "application/pdf")
var page = doc.loadPage(0)
var device = new mupdf.Device(traceDevice)
page.run(device, mupdf.Matrix.identity)
```
--------------------------------
### Define Scaling Matrices for DPI
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/llms/llms-full.txt
Provides examples of creating scaling matrices for different DPI values. MuPDF's default resolution is 72 DPI, and the scale factor is calculated as desired DPI / 72.
```javascript
const matrix150 = mupdf.Matrix.scale(150/72, 150/72); // 150 DPI
const matrix300 = mupdf.Matrix.scale(300/72, 300/72); // 300 DPI
```
--------------------------------
### Retrieve All Annotations from a Document
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/how-to-guide/annotations/getting-started/index.md
Iterates through each page of a document to fetch and log all annotations. Ensure the document object is properly loaded before execution.
```javascript
let i = 0
while (i < document.countPages()) {
const page = document.loadPage(i)
const annots = page.getAnnotations()
console.log(`Page=${page}, Annotations=${annots}`)
i++
}
```
--------------------------------
### Draw a Line Annotation with Arrow Ending
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/how-to-guide/annotations/drawing-and-shapes/index.md
Create a 'Line' annotation with custom stroke and fill colors, defining its start and end points, and applying a 'ClosedArrow' ending style. The interior color affects the arrow fill.
```javascript
let fileData = fs.readFileSync("test.pdf")
let document = mupdf.Document.openDocument(fileData, "application/pdf")
let page = document.loadPage(0)
let annotation = page.createAnnotation("Line")
annotation.setColor([1, 0, 0])
annotation.setInteriorColor([0, 0, 1])
annotation.setLine([10, 300], [200, 500])
annotation.setLineEndingStyles("None", "ClosedArrow")
annotation.update()
fs.writeFileSync("output-line.pdf", document.saveToBuffer("incremental").asUint8Array())
```
--------------------------------
### Convert Document Page to Image
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/how-to-guide/files.md
Loads a PDF document, converts its first page to a PNG image, and saves it. Ensures resources are properly destroyed.
```javascript
let doc = mupdf.PDFDocument.openDocument(fs.readFileSync("sample.pdf"))
try {
const page = doc.loadPage(0)
try {
const pixmap = page.toPixmap(mupdf.Matrix.identity, mupdf.ColorSpace.DeviceRGB, false, true)
try {
fs.writeFileSync("output.png", pixmap.asPNG())
} finally {
pixmap.destroy()
}
} finally {
page.destroy()
}
} finally {
doc.destroy()
}
```
--------------------------------
### Node.js Memory Management with try-finally
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/faq/index.md
Demonstrates proper memory management in Node.js using nested try-finally blocks to ensure `destroy()` is called on MuPDF objects, even if errors occur.
```javascript
const doc = mupdf.Document.openDocument(buffer, "application/pdf");
try {
const page = doc.loadPage(0);
try {
const pixmap = page.toPixmap(/\*...\");*/
try {
// Use pixmap...
const png = pixmap.asPNG();
} finally {
pixmap.destroy();
}
} finally {
page.destroy();
}
} finally {
doc.destroy();
}
```
--------------------------------
### Open and Render PDF with MuPDF.js
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/examples/super-simple-viewer/index.html
Handles file opening, document loading, and page rendering. Renders pages asynchronously to prevent blocking the browser UI. Uses `URL.createObjectURL` to display rendered PNGs.
```javascript
"use strict"
import * as mupdf from "./node_modules/mupdf/dist/mupdf.js"
window.openFile = async function openFile(file) {
console.log("OPEN DOCUMENT", file.name)
window.pageRoot.replaceChildren()
let pdf = mupdf.Document.openDocument(await file.arrayBuffer(), file.name)
document.title = pdf.getMetaData(mupdf.Document.META_INFO_TITLE) || file.name
// Fire off page renders on a timer to avoid blocking the browser.
let n = pdf.countPages()
for (let i = 0; i < n; ++i)
setTimeout(() => renderPage(pdf, i), 0)
}
function renderPage(pdf, i) {
console.log("RENDER PAGE", i+1)
let z = window.devicePixelRatio * 96 / 72
let png = pdf.loadPage(i).toPixmap([z,0,0,z,0,0], mupdf.ColorSpace.DeviceRGB).asPNG()
let img = new Image()
img.src = URL.createObjectURL(new Blob([png], { type: "image/png" }))
img.onload = function () {
img.style.width = img.width / window.devicePixelRatio + "px"
window.pageRoot.appendChild(img)
}
}
```
--------------------------------
### Load and Print Document Outline
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/llms/llms-full.txt
Loads the document's outline (table of contents) and recursively prints the titles with indentation. Requires the document to have an outline structure.
```javascript
const outline = doc.loadOutline();
if (outline) {
function printOutline(items, indent = 0) {
for (const item of items) {
console.log(" ".repeat(indent) + item.title);
if (item.down) printOutline(item.down, indent + 2);
}
}
printOutline(outline);
}
```
--------------------------------
### Get document information and metadata
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/faq/index.md
Retrieves various details about a loaded PDF document, including page count, metadata (Title, Author, etc.), document type, and outline (bookmarks). Ensure `doc` is a valid MuPDF document object.
```javascript
const doc = mupdf.Document.openDocument(buffer, "application/pdf");
// Page count
console.log(`Pages: ${doc.countPages()}`);
// Metadata
console.log(`Title: ${doc.getMetaData("info:Title")}`);
console.log(`Author: ${doc.getMetaData("info:Author")}`);
console.log(`Subject: ${doc.getMetaData("info:Subject")}`);
console.log(`Creator: ${doc.getMetaData("info:Creator")}`);
console.log(`Producer: ${doc.getMetaData("info:Producer")}`);
console.log(`CreationDate: ${doc.getMetaData("info:CreationDate")}`);
// Check document type
console.log(`Is PDF: ${doc.isPDF()}`);
// Get outline (bookmarks/TOC)
const outline = doc.loadOutline();
if (outline) {
function printOutline(items, indent = 0) {
for (const item of items) {
console.log(" ".repeat(indent) + item.title);
if (item.down) printOutline(item.down, indent + 2);
}
}
printOutline(outline);
}
```
--------------------------------
### Configure TypeScript for MuPDF.js
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/INSTALL.md
Create a tsconfig.json file to enable 'nodenext' module resolution for TypeScript projects.
```json
{
"compilerOptions": {
"module": "nodenext"
}
}
```
--------------------------------
### Create Browser Worker Script
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/getting-started/setup.md
Create a worker.js file to import MuPDF.js from the dist directory and log its exported names and values to the console.
```javascript
"use strict"
import * as mupdf from "../../dist/mupdf.js"
for (var name in mupdf) {
console.log(`mupdf.${name}=${mupdf[name]}`)
}
```
--------------------------------
### Load Local File
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/how-to-guide/files.md
Loads a local PDF file using its file path. Ensure the file exists in the current directory.
```javascript
let document = mupdf.PDFDocument.openDocument(fs.readFileSync("test.pdf"),
"application/pdf")
```
--------------------------------
### Create a Highlight Annotation from Search Results
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/llms/llms-full.txt
Creates a 'Highlight' annotation on a page based on search results (quadrilateral points). Sets the annotation color to yellow and updates the page.
```javascript
const quads = stext.search("important text");
if (quads.length > 0) {
const annot = page.createAnnotation("Highlight");
annot.setQuadPoints(quads);
annot.setColor([1, 1, 0]); // Yellow
annot.update();
}
```
--------------------------------
### Load Local PDF File (Node.js)
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/llms/llms-full.txt
Loads a PDF document from the local file system using Node.js. Requires the 'fs' module for file reading and 'mupdf' for PDF processing.
```javascript
import * as fs from "fs";
import mupdf from "mupdf";
const buffer = fs.readFileSync("input.pdf");
const doc = mupdf.Document.openDocument(buffer, "application/pdf");
```
--------------------------------
### Create a FreeText (Text Box) Annotation
Source: https://github.com/artifexsoftware/mupdf.js/blob/master/docs/llms/llms-full.txt
Creates a 'FreeText' annotation, defines its rectangle, sets the content, and configures its default appearance with font, size, and color.
```javascript
const annot = page.createAnnotation("FreeText");
annot.setRect([100, 100, 300, 150]);
annot.setContents("This is editable text");
annot.setDefaultAppearance("Helv", 12, [0, 0, 0]); // Font, size, color
annot.update();
```