Zig Requires Chilkat v11.7.0+
Zig
Extract PDF Text to a StringBuilder and Save to a File
See more PDF Text Extraction Examples
Demonstrates ExtractTextSb, which writes the extracted text to a StringBuilder instead of returning it as a JSON string. Use it for large documents. The JSON output still receives the quality report.Chilkat Zig Downloads
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 is available at long_report.pdf
const pdf = try chilkat.Pdf.init();
defer pdf.deinit();
pdf.loadFile("qa_data/pdf/long_report.pdf") catch {
std.debug.print("{s}\n", .{try pdf.getLastErrorText(alloc)});
return;
};
std.debug.print("Number of pages: {d}\n", .{pdf.getNumPages()});
// ExtractTextSb takes the same operation and options as ExtractText, but the text
// goes to a StringBuilder. This avoids building a very large JSON string for
// documents with many pages.
const json = try chilkat.JsonObject.init();
defer json.deinit();
const sb_text = try chilkat.StringBuilder.init();
defer sb_text.deinit();
const json_out = try chilkat.JsonObject.init();
defer json_out.deinit();
pdf.extractTextSb("text", json, sb_text, json_out) catch {
std.debug.print("{s}\n", .{try pdf.getLastErrorText(alloc)});
return;
};
std.debug.print("Extracted {d} characters.\n", .{sb_text.getLength()});
// Save the text to a file.
sb_text.writeFile("qa_output/long_report.txt", "utf-8", false) catch {
std.debug.print("{s}\n", .{try sb_text.getLastErrorText(alloc)});
return;
};
// The JSON output does not contain the text, but it still has the quality report.
std.debug.print("Quality: {s}\n", .{try json_out.stringOf(alloc, "quality.rating")});
std.debug.print("Pages with no text (need OCR): [{s}]\n", .{try json_out.stringOf(alloc, "quality.pagesNeedingOcr")});
// Sample output:
// Number of pages: 3
// Extracted 4522 characters.
// Quality: good
// Pages with no text (need OCR): []
}