pdfops 0.4.1

Fast PDF operations with JSON output for AI agents: CLI, MCP server and library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
//! PDF fixtures built in memory, so no binary files live in the repository.

#![allow(dead_code)]

use std::path::{Path, PathBuf};

use lopdf::{Dictionary, Document, Object, ObjectId, Stream, dictionary};
use serde_json::{Value, json};

pub fn call(tool: &str, args: Value) -> Value {
    pdfops::tools::call(tool, args).unwrap_or_else(|e| panic!("{tool} failed: {e:#}"))
}

pub fn call_err(tool: &str, args: Value) -> String {
    format!(
        "{:#}",
        pdfops::tools::call(tool, args).expect_err("expected an error")
    )
}

pub fn page_count(path: &Path) -> u64 {
    call("pdf_info", json!({"input": path}))["pages"]
        .as_u64()
        .unwrap()
}

/// Text of every page, in order.
pub fn texts(path: &Path) -> Vec<String> {
    let v = call("pdf_text", json!({"input": path}));
    v["pages"]
        .as_array()
        .unwrap()
        .iter()
        .map(|p| p["text"].as_str().unwrap().to_string())
        .collect()
}

fn skeleton(doc: &mut Document, pages_id: ObjectId, kids: Vec<Object>, extra: Dictionary) {
    let font = doc.add_object(dictionary! {
        "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica", "Encoding" => "WinAnsiEncoding",
    });
    // MediaBox and Resources sit on the tree node, so pages inherit them.
    doc.objects.insert(
        pages_id,
        Object::Dictionary(dictionary! {
            "Type" => "Pages",
            "Count" => kids.len() as i64,
            "Kids" => kids,
            "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
            "Resources" => dictionary! { "Font" => dictionary! { "F1" => font } },
        }),
    );
    let mut catalog = dictionary! { "Type" => "Catalog", "Pages" => pages_id };
    catalog.extend(&extra);
    let catalog = doc.add_object(catalog);
    doc.trailer.set("Root", catalog);
    let info = doc.add_object(dictionary! { "Title" => Object::string_literal("Sample"), "Author" => Object::string_literal("Ada") });
    doc.trailer.set("Info", info);
}

fn text_page(doc: &mut Document, pages_id: ObjectId, text: &str) -> ObjectId {
    content_page(
        doc,
        pages_id,
        &format!("BT /F1 18 Tf 72 720 Td ({text}) Tj ET"),
    )
}

fn content_page(doc: &mut Document, pages_id: ObjectId, content: &str) -> ObjectId {
    let content = doc.add_object(Stream::new(Dictionary::new(), content.as_bytes().to_vec()));
    doc.add_object(dictionary! { "Type" => "Page", "Parent" => pages_id, "Contents" => content })
}

/// `pages` pages reading "Page N of the sample. Keyword alpha-N.", with an outline entry for page 2.
pub fn sample(dir: &Path, name: &str, pages: u32) -> PathBuf {
    let mut doc = Document::with_version("1.5");
    let pages_id = doc.new_object_id();
    let ids: Vec<ObjectId> = (1..=pages)
        .map(|n| {
            text_page(
                &mut doc,
                pages_id,
                &format!("Page {n} of the sample. Keyword alpha-{n}."),
            )
        })
        .collect();
    let mut extra = Dictionary::new();
    if pages >= 2 {
        let outlines = doc.new_object_id();
        let item = doc.add_object(dictionary! {
            "Title" => Object::string_literal("Second chapter"),
            "Parent" => outlines,
            "Dest" => vec![ids[1].into(), "Fit".into()],
        });
        doc.objects.insert(
            outlines,
            Object::Dictionary(
                dictionary! { "Type" => "Outlines", "First" => item, "Last" => item, "Count" => 1 },
            ),
        );
        extra.set("Outlines", outlines);
    }
    skeleton(
        &mut doc,
        pages_id,
        ids.into_iter().map(Object::from).collect(),
        extra,
    );
    let path = dir.join(name);
    doc.save(&path).unwrap();
    path
}

/// One page with a text field `name`, a checkbox `agree`, a choice `color`, a multiline
/// text field `notes` and a 2x2 RGB image.
pub fn form(dir: &Path) -> PathBuf {
    let mut doc = Document::with_version("1.5");
    let pages_id = doc.new_object_id();
    let page = content_page(
        &mut doc,
        pages_id,
        "BT /F1 18 Tf 72 720 Td (Registration form) Tj ET q 20 0 0 20 400 700 cm /Im1 Do Q",
    );

    let image = doc.add_object(Stream::new(
        dictionary! {
            "Type" => "XObject", "Subtype" => "Image", "Width" => 2, "Height" => 2,
            "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8,
        },
        vec![255, 0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255],
    ));
    let font = doc.add_object(
        dictionary! { "Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica" },
    );
    let on = doc.add_object(Stream::new(dictionary! { "Type" => "XObject", "Subtype" => "Form", "BBox" => vec![0.into(), 0.into(), 12.into(), 12.into()] }, b"0 0 12 12 re f".to_vec()));
    let off = doc.add_object(Stream::new(dictionary! { "Type" => "XObject", "Subtype" => "Form", "BBox" => vec![0.into(), 0.into(), 12.into(), 12.into()] }, Vec::new()));

    let widget = |ft: &str, name: &str, rect: [i64; 4]| {
        dictionary! {
            "Type" => "Annot", "Subtype" => "Widget", "FT" => ft, "T" => Object::string_literal(name), "P" => page,
            "Rect" => rect.iter().map(|&v| v.into()).collect::<Vec<Object>>(),
        }
    };
    let name = doc.add_object(widget("Tx", "name", [72, 600, 300, 620]));
    let mut agree = widget("Btn", "agree", [72, 560, 84, 572]);
    agree.set("V", "Off");
    agree.set("AS", "Off");
    agree.set(
        "AP",
        dictionary! { "N" => dictionary! { "Yes" => on, "Off" => off } },
    );
    let agree = doc.add_object(agree);
    let mut color = widget("Ch", "color", [72, 520, 300, 540]);
    color.set(
        "Opt",
        vec![
            Object::string_literal("red"),
            Object::string_literal("green"),
        ],
    );
    let color = doc.add_object(color);

    let mut notes = widget("Tx", "notes", [72, 400, 300, 500]);
    notes.set("Ff", 4096);
    let notes = doc.add_object(notes);

    let fields: Vec<Object> = vec![name.into(), agree.into(), color.into(), notes.into()];
    doc.get_dictionary_mut(page)
        .unwrap()
        .set("Annots", fields.clone());
    doc.get_dictionary_mut(page).unwrap().set(
        "Resources",
        dictionary! { "Font" => dictionary! { "F1" => font }, "XObject" => dictionary! { "Im1" => image } },
    );
    let mut extra = Dictionary::new();
    extra.set(
        "AcroForm",
        dictionary! {
            "Fields" => fields,
            "DA" => Object::string_literal("/Helv 10 Tf 0 g"),
            "DR" => dictionary! { "Font" => dictionary! { "Helv" => font } },
        },
    );
    skeleton(&mut doc, pages_id, vec![page.into()], extra);
    let path = dir.join("form.pdf");
    doc.save(&path).unwrap();
    path
}

/// One page drawing the given image streams side by side, each 100 points wide.
pub fn with_images(dir: &Path, name: &str, images: Vec<Stream>) -> PathBuf {
    let mut doc = Document::with_version("1.5");
    let pages_id = doc.new_object_id();
    let mut xobjects = Dictionary::new();
    let mut content = String::new();
    for (i, image) in images.into_iter().enumerate() {
        let id = doc.add_object(image);
        xobjects.set(format!("Im{i}"), id);
        content += &format!("q 100 0 0 100 {} 600 cm /Im{i} Do Q\n", 50 + i * 120);
    }
    let page = content_page(&mut doc, pages_id, &content);
    doc.get_dictionary_mut(page)
        .unwrap()
        .set("Resources", dictionary! { "XObject" => xobjects });
    skeleton(&mut doc, pages_id, vec![page.into()], Dictionary::new());
    let path = dir.join(name);
    doc.save(&path).unwrap();
    path
}

pub fn image_stream(
    width: i64,
    height: i64,
    color_space: Object,
    bits: i64,
    data: Vec<u8>,
) -> Stream {
    Stream::new(
        dictionary! {
            "Type" => "XObject", "Subtype" => "Image", "Width" => width, "Height" => height,
            "ColorSpace" => color_space, "BitsPerComponent" => bits,
        },
        data,
    )
}

/// A page that shows page 1 of `source` as a picture only, like a scanner would produce.
pub fn scan(dir: &Path, source: &Path) -> PathBuf {
    let v = call(
        "pdf_render",
        json!({"input": source, "out_dir": dir.join("scan"), "pages": "1", "dpi": 150}),
    );
    let bytes = std::fs::read(v["files"][0]["file"].as_str().unwrap()).unwrap();
    let mut reader = png::Decoder::new(std::io::Cursor::new(bytes))
        .read_info()
        .unwrap();
    let mut buf = vec![0; reader.output_buffer_size().unwrap()];
    let info = reader.next_frame(&mut buf).unwrap();
    let channels = buf.len() / (info.width * info.height) as usize;
    let gray: Vec<u8> = buf.chunks(channels).map(|p| p[0]).collect();

    let mut doc = Document::with_version("1.5");
    let pages_id = doc.new_object_id();
    let image = doc.add_object(image_stream(
        info.width as i64,
        info.height as i64,
        "DeviceGray".into(),
        8,
        gray,
    ));
    let page = content_page(&mut doc, pages_id, "q 612 0 0 792 0 0 cm /Im1 Do Q");
    doc.get_dictionary_mut(page).unwrap().set(
        "Resources",
        dictionary! { "XObject" => dictionary! { "Im1" => image } },
    );
    skeleton(&mut doc, pages_id, vec![page.into()], Dictionary::new());
    let path = dir.join("scan.pdf");
    doc.save(&path).unwrap();
    path
}

/// A tesseract language to test with, if the engine and any language data are installed.
pub fn ocr_lang() -> Option<String> {
    let out = std::process::Command::new("tesseract")
        .arg("--list-langs")
        .output()
        .ok()?;
    let text = String::from_utf8([out.stdout, out.stderr].concat()).ok()?;
    let langs: Vec<&str> = text
        .lines()
        .skip(1)
        .map(str::trim)
        .filter(|l| !l.is_empty() && *l != "osd")
        .collect();
    langs
        .iter()
        .find(|l| **l == "eng")
        .or(langs.first())
        .map(|l| l.to_string())
}

/// Serves fixed responses over HTTP on a local port and returns the base URL.
pub fn serve(routes: Vec<(&'static str, Vec<u8>)>) -> String {
    use std::io::{Read, Write};
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let base = format!("http://{}", listener.local_addr().unwrap());
    std::thread::spawn(move || {
        for mut stream in listener.incoming().flatten() {
            let mut request = Vec::new();
            let mut byte = [0u8; 1];
            while !request.ends_with(b"\r\n\r\n") && stream.read(&mut byte).is_ok_and(|n| n == 1) {
                request.push(byte[0]);
            }
            let path = String::from_utf8_lossy(&request)
                .split_whitespace()
                .nth(1)
                .unwrap_or("")
                .to_string();
            let reply = match routes.iter().find(|r| r.0 == path) {
                Some((_, body)) => {
                    let mut out = format!(
                        "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                        body.len()
                    )
                    .into_bytes();
                    out.extend_from_slice(body);
                    out
                }
                None => b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
                    .to_vec(),
            };
            let _ = stream.write_all(&reply);
        }
    });
    base
}

/// A server whose address is known before what it serves is: returns the address and
/// a function that hands it the body to answer every request with.
pub fn serve_later() -> (String, impl FnOnce(Vec<u8>)) {
    use std::io::{Read, Write};
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let address = format!("http://{}/list.crl", listener.local_addr().unwrap());
    let (give, taken) = std::sync::mpsc::channel::<Vec<u8>>();
    std::thread::spawn(move || {
        let Ok(body) = taken.recv() else { return };
        for mut stream in listener.incoming().flatten() {
            let mut request = Vec::new();
            let mut byte = [0u8; 1];
            while !request.ends_with(b"\r\n\r\n") && stream.read(&mut byte).is_ok_and(|n| n == 1) {
                request.push(byte[0]);
            }
            let mut reply = format!(
                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                body.len()
            )
            .into_bytes();
            reply.extend_from_slice(&body);
            let _ = stream.write_all(&reply);
        }
    });
    (address, move |body| give.send(body).unwrap())
}

/// Dark pixel counts inside page rectangles given in PDF points, at 72 dpi.
pub fn ink<const N: usize>(
    pdf: &std::path::Path,
    dir: &std::path::Path,
    rects: [[usize; 4]; N],
) -> [usize; N] {
    let v = call(
        "pdf_render",
        json!({"input": pdf, "out_dir": dir, "dpi": 72}),
    );
    let bytes = std::fs::read(v["files"][0]["file"].as_str().unwrap()).unwrap();
    let mut reader = png::Decoder::new(std::io::Cursor::new(bytes))
        .read_info()
        .unwrap();
    let mut buf = vec![0; reader.output_buffer_size().unwrap()];
    let info = reader.next_frame(&mut buf).unwrap();
    let (width, height) = (info.width as usize, info.height as usize);
    let channels = buf.len() / (width * height);
    rects.map(|[x0, y0, x1, y1]| {
        (height - y1..height - y0)
            .flat_map(|y| (x0..x1).map(move |x| (x, y)))
            .filter(|&(x, y)| buf[(y * width + x) * channels] < 128)
            .count()
    })
}

/// A document whose pages have exactly the given content streams, with Helvetica as /F1.
pub fn custom(dir: &Path, name: &str, contents: &[&str]) -> PathBuf {
    let mut doc = Document::with_version("1.5");
    let pages_id = doc.new_object_id();
    let ids: Vec<Object> = contents
        .iter()
        .map(|c| content_page(&mut doc, pages_id, c).into())
        .collect();
    skeleton(&mut doc, pages_id, ids, Dictionary::new());
    let path = dir.join(name);
    doc.save(&path).unwrap();
    path
}

/// The decoded content stream of a page, for checking what is really in the file.
pub fn content_of(path: &Path, page: u32) -> String {
    let doc = Document::load(path).unwrap();
    let id = doc.get_pages()[&page];
    String::from_utf8_lossy(&doc.get_page_content(id)).into_owned()
}

/// Words of a page with their boxes, as `layout` reports them.
pub fn words(path: &Path, page: u32) -> Vec<(String, [f64; 4])> {
    let v = call(
        "pdf_layout",
        json!({"input": path, "pages": page.to_string(), "level": "words"}),
    );
    v["pages"][0]["words"]
        .as_array()
        .unwrap()
        .iter()
        .map(|w| {
            let b: Vec<f64> = w["bbox"]
                .as_array()
                .unwrap()
                .iter()
                .map(|v| v.as_f64().unwrap())
                .collect();
            (
                w["text"].as_str().unwrap().to_string(),
                [b[0], b[1], b[2], b[3]],
            )
        })
        .collect()
}

/// A signing identity issued by an authority made for it, as PEM files: the signer's
/// certificate followed by nothing else, its private key, and the authority's certificate.
pub fn issued_identity(dir: &Path, name: &str) -> (PathBuf, PathBuf, PathBuf) {
    let (cert, key, authority, _) = issued_identity_with_lists(dir, name, None);
    (cert, key, authority)
}

/// The same, with the signer's certificate naming `list_address` as the place of the
/// authority's revocation list. Also returns two such lists in DER form: one that names
/// nobody, and one that names the signer's certificate.
pub fn issued_identity_with_lists(
    dir: &Path,
    name: &str,
    list_address: Option<String>,
) -> (PathBuf, PathBuf, PathBuf, [Vec<u8>; 2]) {
    let authority_key = rcgen::KeyPair::generate().unwrap();
    let mut authority = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
    authority
        .distinguished_name
        .push(rcgen::DnType::CommonName, format!("{name} Authority"));
    authority.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
    authority.key_usages = vec![
        rcgen::KeyUsagePurpose::KeyCertSign,
        rcgen::KeyUsagePurpose::CrlSign,
    ];
    let authority_cert = authority.self_signed(&authority_key).unwrap();
    let issuer = rcgen::Issuer::new(authority, authority_key);

    let key = rcgen::KeyPair::generate().unwrap();
    let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
    params
        .distinguished_name
        .push(rcgen::DnType::CommonName, name);
    let serial = rcgen::SerialNumber::from(vec![0x51, 0x07]);
    params.serial_number = Some(serial.clone());
    params.crl_distribution_points = list_address
        .into_iter()
        .map(|address| rcgen::CrlDistributionPoint {
            uris: vec![address],
        })
        .collect();
    let cert = params.signed_by(&key, &issuer).unwrap();
    let list = |revoked: Vec<rcgen::RevokedCertParams>| {
        rcgen::CertificateRevocationListParams {
            this_update: rcgen::date_time_ymd(2026, 1, 1),
            next_update: rcgen::date_time_ymd(2046, 1, 1),
            crl_number: rcgen::SerialNumber::from(1u64),
            issuing_distribution_point: None,
            revoked_certs: revoked,
            key_identifier_method: rcgen::KeyIdMethod::Sha256,
        }
        .signed_by(&issuer)
        .unwrap()
        .der()
        .to_vec()
    };
    let lists = [
        list(Vec::new()),
        list(vec![rcgen::RevokedCertParams {
            serial_number: serial,
            revocation_time: rcgen::date_time_ymd(2026, 2, 2),
            reason_code: None,
            invalidity_date: None,
        }]),
    ];
    let stem = name.replace(' ', "-");
    let (cert_path, key_path, authority_path) = (
        dir.join(format!("{stem}.crt")),
        dir.join(format!("{stem}.key")),
        dir.join(format!("{stem}-authority.crt")),
    );
    std::fs::write(&cert_path, cert.pem()).unwrap();
    std::fs::write(&key_path, key.serialize_pem()).unwrap();
    std::fs::write(&authority_path, authority_cert.pem()).unwrap();
    (cert_path, key_path, authority_path, lists)
}

/// A self-signed P-256 signing identity as PEM files: (certificate, private key).
pub fn identity(dir: &Path, name: &str) -> (PathBuf, PathBuf) {
    let key = rcgen::KeyPair::generate().unwrap();
    let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
    params
        .distinguished_name
        .push(rcgen::DnType::CommonName, name);
    let cert = params.self_signed(&key).unwrap();
    let stem = name.replace(' ', "-");
    let (cert_path, key_path) = (
        dir.join(format!("{stem}.crt")),
        dir.join(format!("{stem}.key")),
    );
    std::fs::write(&cert_path, cert.pem()).unwrap();
    std::fs::write(&key_path, key.serialize_pem()).unwrap();
    (cert_path, key_path)
}