Mercurial > hgrepos > Python2 > PyMuPDF
comparison mupdf-source/docs/cookbook/javascript/basics.md @ 2:b50eed0cc0ef upstream
ADD: MuPDF v1.26.7: the MuPDF source as downloaded by a default build of PyMuPDF 1.26.4.
The directory name has changed: no version number in the expanded directory now.
| author | Franz Glasner <fzglas.hg@dom66.de> |
|---|---|
| date | Mon, 15 Sep 2025 11:43:07 +0200 |
| parents | |
| children |
comparison
equal
deleted
inserted
replaced
| 1:1d09e1dec1d9 | 2:b50eed0cc0ef |
|---|---|
| 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 } |
