| 1 |
# Basics |
| 2 |
|
| 3 |
## Loading a PDF |
| 4 |
|
| 5 |
The following example demonstrates how to load a document and then print out the page count. |
| 6 |
Ensure you have a PDF file named "test.pdf" alongside this example before running it. |
| 7 |
|
| 8 |
import * as mupdf from "mupdf" |
| 9 |
|
| 10 |
var doc = mupdf.Document.openDocument("test.pdf") |
| 11 |
console.log(doc.countPages()) |
| 12 |
|
| 13 |
## Creating a PDF |
| 14 |
|
| 15 |
How to create a new PDF file with a single blank page: |
| 16 |
|
| 17 |
import * as mupdf from "mupdf" |
| 18 |
|
| 19 |
var doc = new mupdf.PDFDocument() |
| 20 |
doc.insertPage(-1, doc.addPage([0, 0, 595, 842], 0, null, "")) |
| 21 |
doc.save("blank.pdf") |
| 22 |
|
| 23 |
## Adding an annotation |
| 24 |
|
| 25 |
How to add a simple annotation to a PDF file: |
| 26 |
|
| 27 |
import * as mupdf from "mupdf" |
| 28 |
|
| 29 |
var doc = mupdf.Document.openDocument("blank.pdf") |
| 30 |
|
| 31 |
var page = doc.loadPage(0) |
| 32 |
|
| 33 |
var annot = page.createAnnotation("FreeText") |
| 34 |
annot.setRect([10, 10, 200, 100]) |
| 35 |
annot.setContents("Hello, world!") |
| 36 |
|
| 37 |
page.update() |
| 38 |
|
| 39 |
doc.save("annotation.pdf") |
| 40 |
|
| 41 |
## Converting a PDF to plain text |
| 42 |
|
| 43 |
import * as mupdf from "mupdf" |
| 44 |
|
| 45 |
var doc = mupdf.Document.openDocument("test.pdf") |
| 46 |
for (var i = 0; i < doc.countpages(); ++i) { |
| 47 |
var page = doc.loadPage(i) |
| 48 |
var text = page.toStructuredText().asText() |
| 49 |
console.log(text) |
| 50 |
} |
| 51 |
|
| 52 |
## Converting a PDF to image files |
| 53 |
|
| 54 |
import * as fs from "fs" |
| 55 |
import * as mupdf from "mupdf" |
| 56 |
|
| 57 |
var doc = mupdf.Document.openDocument("test.pdf") |
| 58 |
for (var i = 0; i < doc.countpages(); ++i) { |
| 59 |
var page = doc.loadPage(i) |
| 60 |
var pixmap = page.toPixmap( |
| 61 |
mupdf.Matrix.scale(96 / 72, 96 / 72), |
| 62 |
mupdf.ColorSpace.DeviceRGB |
| 63 |
) |
| 64 |
var buffer = pixmap.asPNG() |
| 65 |
fs.writeFileSync("page" + (i+1) + ".png", buffer) |
| 66 |
} |