Sample code for 30+ languages & platforms
Zig Requires Chilkat v11.7.0+

Extract Text from a PDF that Forbids Copying

See more PDF Text Extraction Examples

Demonstrates a PDF that opens without a password but whose permissions do not allow copying text. The "text", "markdown", "search" and "tables" operations fail with that reason; "assess" always works. Loading the PDF with the OwnerPassword property set grants owner rights, and extraction works.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    // The PDF used in this example (owner password: owner-secret; copying not permitted) is available at no_copy_permission.pdf

    const pdf = try chilkat.Pdf.init();
    defer pdf.deinit();
    const json = try chilkat.JsonObject.init();
    defer json.deinit();
    const json_out = try chilkat.JsonObject.init();
    defer json_out.deinit();

    // The PDF opens without a password.
    pdf.loadFile("qa_data/pdf/no_copy_permission.pdf") catch {
        std.debug.print("{s}\n", .{try pdf.getLastErrorText(alloc)});
        return;
    };

    // Extracting text is refused, because the PDF's permissions do not allow copying.
    pdf.extractText("text", json, json_out) catch {
        std.debug.print("Extraction refused: {s}\n", .{try pdf.getLastErrorText(alloc)});
    };

    // "assess" reports only counts and ratings, never text, so it is always allowed.
    pdf.extractText("assess", json, json_out) catch {
        std.debug.print("{s}\n", .{try pdf.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("rating: {s}\n", .{try json_out.stringOf(alloc, "quality.rating")});

    // Load with the owner password to get owner rights, which include copying.
    pdf.setOwnerPassword("owner-secret");
    pdf.loadFile("qa_data/pdf/no_copy_permission.pdf") catch {
        std.debug.print("{s}\n", .{try pdf.getLastErrorText(alloc)});
        return;
    };

    pdf.extractText("text", json, json_out) catch {
        std.debug.print("{s}\n", .{try pdf.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("{s}\n", .{try json_out.stringOf(alloc, "text")});

    // Sample output:

    // Extraction refused: ChilkatLog:
    //   ExtractText:
    //     ...
    //       The PDF's permissions do not allow copying or extracting text (load it with the owner password to extract).
    //     ...
    // rating: good
    // Visitor Leaflet
    //
    // Welcome to the harbor lighthouse. The tower is open on weekends from July to September.
    //
    // Please keep to the marked paths and do not climb on the breakwater.
    //
    // The lantern room is closed in high winds.
}