Skip to content

C API ​

libhypercompress is the Hyper Compress engine as a small C library, for C, C++ and any language that can call C. It exports exactly five functions, and new versions only add to them within a major version.

Each release attaches a prebuilt libhypercompress.dylib for macOS Apple silicon in libhypercompress-<version>-macos-arm64.tar.gz. The header is sdk/native/hpdf.h in the repository.

c
#include "hpdf.h"

What the library leaves to you ​

The C library is the engine pass alone. The other surfaces (Node.js SDK, Rust crate, CLI, HTTP API) add these on top, and with the C library they are yours to do:

  • Keeping the original when the output is not smaller.
  • The size target search.
  • The repack pass with qpdf that merges objects into compressed object streams.
  • PDF/A detection, and warnings for options skipped for safety.
  • Running each file in a separate process, so a crash or hang cannot take down your program.

If your input is untrusted, run the worker program in a child process instead of calling the library in your own process.

Functions ​

c
int hpdf_compress_file(const char* in_path,
                       const char* out_path,
                       const int* option_ids,
                       const int* option_values,
                       int option_count,
                       const char* password);

unsigned char* hpdf_compress_buffer(const unsigned char* in_data,
                                    unsigned long in_size,
                                    const int* option_ids,
                                    const int* option_values,
                                    int option_count,
                                    const char* password,
                                    unsigned long* out_size,
                                    int* out_status);

void hpdf_free(unsigned char* buffer);
const char* hpdf_last_error(void);
const char* hpdf_version(void);

hpdf.h also defines HPDF_VERSION, the version as a string, for example "1.1.4".

The library is safe to call from any number of threads. It starts the engine once on first use, and runs one compression at a time: calls made at the same moment from other threads wait their turn, so extra threads add safety but not speed. For several compressions at once, run several processes, or use the CLI, Node.js SDK or HTTP service, which run each job in its own engine process. hpdf_last_error returns the message of the calling thread's last call.

hpdf_compress_file ​

Compresses the PDF at one path and writes the result to another.

NameTypeDescription
in_pathconst char*Path of the input PDF.
out_pathconst char*Path to write. An existing file is replaced.
option_idsconst int*Option ids, see Option ids.
option_valuesconst int*One value for each id, in the same order.
option_countintNumber of id and value pairs. 0 uses the engine defaults.
passwordconst char*Password for an encrypted input. NULL or "" for none.
ReturnsMeaning
0Compressed. The output is written.
2The input is digitally signed, so it was not compressed. The output is an unchanged copy, and the signature stays valid.
1Failed. hpdf_last_error() says why. The output may be missing or incomplete.

hpdf_compress_buffer ​

Compresses a PDF in memory and returns the result in a new buffer.

NameTypeDescription
in_dataconst unsigned char*The input PDF bytes.
in_sizeunsigned longNumber of input bytes. At most 2 GB (INT_MAX bytes).
option_idsconst int*Option ids.
option_valuesconst int*One value for each id.
option_countintNumber of pairs.
passwordconst char*Password for an encrypted input, or NULL.
out_sizeunsigned long*Set to the output size on success, 0 on failure. May be NULL.
out_statusint*Set to 0 (compressed), 2 (signed, unchanged copy) or 1 (failed). May be NULL.
ReturnsMeaning
a bufferThe output PDF. You own it; release it with hpdf_free.
NULLFailed. hpdf_last_error() says why.

hpdf_free ​

Releases a buffer returned by hpdf_compress_buffer. Passing NULL is safe.

hpdf_last_error ​

Returns the message of the calling thread's most recent failure, or "" after a compress call that succeeded. Each thread has its own message. The string belongs to the library and changes on that thread's next call.

MessageCause
cannot open input (missing, corrupt, or wrong password)hpdf_compress_file could not open the input.
cannot parse input (corrupt or wrong password)hpdf_compress_buffer could not parse the input.
input larger than 2 GB is not supportedhpdf_compress_buffer got more than INT_MAX bytes.
engine pass failedThe engine could not process the document.
cannot open output for writinghpdf_compress_file could not create out_path.
save failedWriting the output failed.

hpdf_version ​

Returns the library version, the same string as HPDF_VERSION.

Example ​

This program compresses input.pdf with the medium preset. The id and value lists are what the Node.js SDK sends to the engine for medium (see Presets as id and value pairs).

c
#include <stdio.h>
#include "hpdf.h"

int main(void) {
  const int ids[]  = {1, 2, 3, 8, 18, 7, 63, 6, 10, 13, 14, 16, 17, 20, 67};
  const int vals[] = {150, 50, 4, 1, 1, 1, 10, 1, 1, 1, 1, 1, 1, 8322, 6};
  const int n = sizeof ids / sizeof ids[0];

  int rc = hpdf_compress_file("input.pdf", "output.pdf", ids, vals, n, NULL);
  if (rc == 1) {
    fprintf(stderr, "compress failed: %s\n", hpdf_last_error());
    return 1;
  }
  if (rc == 2) printf("signed document, copied unchanged\n");
  printf("engine %s\n", hpdf_version());
  return 0;
}

Save it as demo.c and build it on macOS from the root of a repository checkout, with the library in sdk/native/lib (from the release file, or from make build):

bash
clang demo.c -I sdk/native -L sdk/native/lib -lhypercompress \
  -Wl,-rpath,@executable_path/sdk/native/lib -o demo
./demo
text
engine 1.1.4

The output is not guaranteed to be smaller than the input. Compare the sizes and keep the original when it is not smaller.

Presets as id and value pairs ​

PresetPairs
low1=200 2=80 3=4 8=1 18=1 7=1 63=10 10=1 13=1 14=1 16=1 17=1 20=8322 67=6
medium1=150 2=50 3=4 8=1 18=1 7=1 63=10 6=1 10=1 13=1 14=1 16=1 17=1 20=8322 67=6
high1=72 59=150 2=20 3=4 8=1 18=1 7=1 63=10 6=1 10=1 12=1 9=1 13=1 14=1 16=1 17=1 20=565442 67=6
lossless3=0 7=1 10=1 13=1 14=1 16=1 17=1 20=8322

For any other combination, let the Node.js SDK translate an options object:

bash
node -e "import('hyper-compress').then(m => console.log(m.buildHyperTokens(m.normalizeHyperOptions({ ...m.HYPER_PRESETS.medium, grayscale: true }))))"

Option ids ​

Ids are defined in core/include/fpdf_compress.h and stay the same within a major version. An id you do not pass keeps the engine default shown here, which is not the same as the medium preset. Unknown ids are ignored. If you pass an id twice, the last value wins.

Images ​

IdNameEngine defaultValues
1IMAGE_MAX_DPI0Resolution limit for colour and gray images. 0 is no limit.
57IMAGE_COLOR_MAX_DPI0Limit for colour images. 0 uses id 1.
58IMAGE_GRAY_MAX_DPI0Limit for gray images. 0 uses id 1.
59IMAGE_MONO_MAX_DPI0Limit for 1-bit (black and white) images. 0 is no limit.
50IMAGE_THRESHOLD_DPI0Only resample images above this resolution. 0 uses the built-in rule.
52IMAGE_RESAMPLE_QUALITY10 nearest, 1 bilinear, 2 high.
2IMAGE_QUALITY75JPEG quality, 5 to 100.
3IMAGE_ENCODING40 keep the original encoding (lossless), 1 JPEG, 2 Flate, 3 JPEG 2000, 4 automatic.
5IMAGE_GRAYSCALE01 converts images to gray.
51IMAGE_COLOR_TARGET00 original, 1 sRGB, 2 CMYK, 3 gray.
69CONVERT_PAGE_COLORS01 also converts text and vector colours to the colour target.
53JPEG_SUBSAMPLE00 encoder default, 1 4:2:0, 2 4:2:2, 3 4:4:4.
54JPEG_OPTIM_HUFFMAN01 writes optimized Huffman tables.
55JPEG_PROGRESSIVE01 writes progressive JPEG.
18IMAGE_PREFER_JPX01 lets JPEG 2000 compete with JPEG for each image.
6CLIP_IMAGES01 crops image data hidden outside the clip.
7REDUCE_COLOR_COMPLEXITY01 reduces colours where it does not change appearance.
63IMAGE_LOSSY_INDEX0With id 7, also tries lossy palette images with this allowed error. 0 is off; the SDK uses 10.
56IMAGE_INDEX_MIN_DPI150With id 7, only images placed at this resolution or more are tried as palette images.
70SPEED00 balanced, 1 quality, 2 fast.
8FLATTEN_ICC01 flattens ICC colour profiles.

Scans ​

IdNameEngine defaultValues
40MRC_MODE0Mixed raster content, which splits scans into text and background layers. 0 off, 1 auto, 2 force.
41MRC_SELECTOR_DPI300Resolution limit of the MRC text mask.
42MRC_BG_DPI75Background and ink layer resolution.
43MRC_BG_QUALITY30Background JPEG quality.
44MRC_FG_QUALITY50Ink layer JPEG quality.
72MRC_DETECT_PHOTOS10 turns off photo detection.
73JBIG2_SYMBOLS01 allows lossy JBIG2 symbol reuse.
60CONVERT_TO_BITMAP01 rasterizes every page unless the document has text, 2 rasterizes even with text.
61CONVERT_TO_BITMAP_DPI150Rasterize resolution. Values under 36 become 36.
62CONVERT_TO_BITMAP_QUALITY50Rasterize JPEG quality.

Fonts and objects ​

IdNameEngine defaultValues
10FONT_SUBSET10 keeps full fonts.
12FONT_REMOVE_STANDARD01 unembeds the standard 14 fonts.
9UNEMBED_ALIASED_FONTS01 unembeds copies of the standard fonts.
13FONT_MERGE01 merges duplicate font programs.
14FONT_DEDUP_DICTS01 merges duplicate font dictionaries.
16DEDUP_OBJECTS01 merges duplicate objects.
17OPTIMIZE_RESOURCES01 merges duplicate resource dictionaries.

Content and output ​

IdNameEngine defaultValues
30RECOMPRESS_CONTENT_STREAMS10 leaves page content streams as they are.
67CONTENT_PRECISION00 exact, or 3 to 8 significant digits. 1 and 2 become 3; values over 8 become 8.
64PDFA_MODE03 keeps a PDF/A file conformant.
65STREAM_CODEC01 uses PDF 2.0 Brotli streams.
66BROTLI_QUALITY11Brotli quality, 1 to 11.
68THREADS0Threads for one compression. 0 uses the machine's cores, up to 8. At most 64.
71REPORT01 prints notes for each image to stderr, for the report.

Id 20: what to remove or flatten ​

Id 20 is a bit mask. Add the values of everything you want to remove or flatten:

BitRemoves or flattensOptions name
0x1structure tree (tags)removeStructTree
0x2page thumbnailsremoveThumbnails
0x4bookmarksremoveBookmarks
0x8all annotations
0x10form fields
0x20attachmentsremoveAttachments
0x40alternate imagesremoveAlternates
0x80document piece inforemoveAppData (with 0x2000)
0x100document info and XMP metadataremoveMetadata
0x200print settingsremovePrintSettings
0x400web capture search indexremoveSearchIndex
0x800named destinationsremoveNamedDests
0x1000actions and JavaScriptremoveActions
0x2000page piece inforemoveAppData (with 0x80)
0x4000output intentsremoveOutputIntents
0x8000article threadsremoveThreads
0x10000appearances of empty signature fieldsremoveSignatureAppearances
0x20000links
0x40000flatten markup annotations, keep forms and linksannotations: 'flatten'
0x80000web capture inforemoveSpiderInfo
0x100000flatten form fieldsflattenForms
0x200000flatten linksflattenLinks
0x400000digital signaturesremoveSignatures
0x800000markup annotations, keep forms and linksannotations: 'remove'

Bits without an options name are only reachable from the C API and the worker program. For example, 8322 (0x2000 + 0x80 + 0x2) removes page and document piece info and page thumbnails.

What the library guarantees ​

These guarantees live inside the library and hold for every program that embeds it:

  • Signed documents are not changed, unless you set bit 0x400000 of id 20.
  • PDFA_MODE=3 keeps a PDF/A file conformant.
  • Rasterizing (id 60 set to 1) skips documents that have text. Only 2 rasterizes them.

The output never being larger than the input, the size target search, PDF/A detection and warnings live in the other surfaces, not in the library.

The worker program ​

hpdf-worker is the engine as a command, the same one the Node.js SDK, the Rust crate, the CLI and the HTTP service run for every file. It ships in every release file and npm platform package.

bash
hpdf-worker input.pdf output.pdf 1=150 2=50 3=4 20=8322

It takes the input path, the output path and any number of id=value pairs. Arguments that are not id=value pairs are ignored. It has no password option, so decrypt encrypted files first; the SDKs run qpdf --decrypt.

Exit codeMeaning
0Success, including a signed input written unchanged.
1The engine pass failed.
2Fewer than two paths were given.
3The input could not be opened, for example because it is missing, damaged or encrypted.
4The output could not be created.

What it prints on stderr:

Line starts withMeaning
SIGNED_SKIPThe input is signed and was written unchanged.
SIGNATURES_REMOVEDBit 0x400000 of id 20 removed the signatures.
[hyper] rasterize skipped: document has a text layerId 60 was 1 and the document has text, so no page was rasterized.

A crash or hang ends only that process, which is why the other surfaces use it for every file.

Build the library ​

sdk/native/build-dylib.sh builds sdk/native/lib/libhypercompress.dylib on macOS, exporting only the five hpdf_* functions; make build runs it after the engine build. The script is macOS only. On other platforms, compile sdk/native/hpdf_wrap.c and link it with the engine archive and jpegli as sdk/native/build-dylib.sh does. Building from source covers the engine build.

Next steps ​

Dual-licensed under AGPL-3.0 and Commercial License.