A scan's text is a 1-bit mask, and shrinking it is not sampling it
“Our scanned invoices look right in Acrobat and wrong in our own viewer. The thin rules on the forms are just not there, and some of the text looks like it has been chewed. If I zoom in far enough everything comes back, so I cannot tell whether the files are bad or our rendering is.”
On 26 October someone filed an issue against a desktop PDF reader saying that scans from office printers rendered with thin, broken text, while the same files looked smooth in other viewers and ordinary non-scanned PDFs were fine. The issue is storytold/pdfcraft#4800, still open, reported against PdfCraft 0.14.0 on Windows 11 and titled "Scanned PDFs render with broken, jagged text: shrunk /ImageMask stencils are nearest-sampled".
The reporter had already found the line of code. What makes it worth a post is the reasoning
behind that line, because it is a reasonable-sounding mistake about what one PDF flag means.
/Interpolate is a hint about what a
renderer may do when an image is drawn larger than its own resolution. The patch that
caused this read it as a statement about whether the image needs filtering at all, and then
applied that to the opposite case, drawing it smaller. We rebuilt the file, measured four
independent renderers, and replayed both shrinking rules ourselves.
A scan is two images, and the text is the thin one
A scanner that produces small files does not store one picture of the page. It separates the
page into layers, a technique usually called MRC, for mixed raster content: a coarse,
continuous-tone background holding the paper and any photographs, and a hard-edged bilevel
layer holding the text and rules. The two have different resolutions on purpose, because they
are being asked to do different jobs. The issue describes exactly this shape: an 8-bit
background at about 150 dpi, plus the text as a 1-bit CCITT Group 4 image at about 300 dpi,
with no /Interpolate.
The text layer is not drawn as an image. It is drawn as a stencil: a 1-bit image whose samples do not carry colour at all, but say, per sample, whether the current fill colour is painted there. In the file it looks like this, which is the dictionary from the test file we built for this post:
<< /Type /XObject /Subtype /Image /Width 2550 /Height 3300
/ImageMask true /BitsPerComponent 1
/Filter /CCITTFaxDecode
/DecodeParms << /K -1 /Columns 2550 /Rows 3300 /BlackIs1 false >>
/Length 3392 >>
/ImageMask true with /BitsPerComponent 1 is the whole of it. There is no /ColorSpace,
because there are no colours to space: the samples select paint or no paint, and the paint is
whatever the content stream last set. /K -1 is Group 4, the same two-dimensional coding fax
machines use, which is why a 2550 by 3300 text layer compresses to 3,392 bytes here.
A US Letter page is 612 points wide. At 300 dpi that stencil is 2550 samples wide, so every device pixel of a page shown at one pixel per point covers about 4.17 stencil samples across and the same down. A stroke in the original that is one sample thick is therefore about a quarter of a pixel thick on screen. That is the entire problem, and it has one correct answer and several wrong ones.
What the flag actually governs
/Interpolate is an entry in the image dictionary, and its default is false. We could not
fetch ISO 32000 from the machine this was written on: opensource.adobe.com and pdfa.org
are both refused by this sandbox's network policy, so nothing in this post quotes the PDF
specification, and we are not going to paraphrase a standard we did not read.
What we can quote is what the renderers themselves say the flag is for, in their own source, which is the thing that actually decides how your file looks. PdfCraft's own code, in the comment on the function that now does the shrinking, puts it this way:
Nothing is invented between samples, which is what
/Interpolategoverns (ISO 32000-2 §8.9.5.3, for images drawn above their resolution)
That is their citation and their reading, not ours, and the parenthetical is the load-bearing part: for images drawn above their resolution. The flag is about magnification. It asks whether a renderer may invent plausible samples between the real ones when an image is blown up, so a low-resolution logo looks soft rather than blocky. It is a question about invention.
Shrinking an image asks a different question. Nothing has to be invented, because there is more data than there is room for. The question is whether the samples that do not survive are allowed to contribute. Averaging them is not interpolation and does not invent anything; it measures. And for a 1-bit stencil, that measurement is the only thing that can turn a quarter of a pixel of ink into a quarter of a pixel of grey.
The patch that answered the wrong question
PdfCraft vendors and patches the hayro rasterizer, and this is a patch of theirs, not
upstream behaviour. At the tag v0.18.1, the version in which a second reporter saw what they
believed was the same bug on 4 November, the vendored vendor/hayro/src/renderer.rs contains this, verbatim:
// PdfCraft patch (#624): `/Interpolate` governs the pre-minification pass too. Using
// Catmull-Rom here for an image that did not request interpolation blends hard edges
// before ImageQuality::Low gets a chance to sample it. Keep the pre-resize (and its
// bounded memory/performance behaviour), but use nearest-neighbour when interpolation
// is disabled. PDF's default for `/Interpolate` is false.
let nearest = Scaler::new(ResamplingFunction::Nearest);
let scaler = if interpolate { &self.scaler } else { &nearest };
The first sentence is the decision, stated plainly: /Interpolate governs the shrinking pass
too. The rest is a real concern, and a correct one for the case it has in mind. Pre-blurring a
QR code or a screenshot of text before a sampling step does produce a worse result than
leaving its hard edges alone. The patch generalised that to every image that does not set the
flag, and a 300 dpi scan of a page does not set the flag.
A second patch carrying the same issue number made the stencil case bypass filtering entirely:
// PdfCraft patch (#624): a minified image with a soft mask that is not interpolated is
// nearest-sampled straight into premultiplied target RGBA. That skips the full-resolution
// RGBA copy below and the premultiply pass after it.
let direct = match &alpha_data {
Some(alpha) if needs_resize && !interpolate => nearest_premultiplied_rgba(
A stencil arrives here as a solid colour plus a 1-bit alpha mask, so needs_resize && !interpolate is true for every scan shown below 300 dpi, which is every scan shown at
anything like page size. The sampling rule itself is four lines:
fn nearest_source_index(src: u32, dst: u32, index: u32) -> usize {
let step = (u64::from(src) << 32) / u64::from(dst);
((u64::from(index) * step + (step >> 1)) >> 32) as usize
}
For comparison, we read the upstream crate as well, hayro 0.9.0 from crates.io, built here.
Its src/image.rs calls its scaler unconditionally when an image needs resizing, with
ResamplingFunction::Hermite, and uses the image's interpolate only to choose between two
drawing qualities afterwards. The strings nearest_premultiplied_rgba, area_shrink and
PdfCraft patch do not appear anywhere in the crate. So this is not a flaw in the renderer
PdfCraft adopted. It is a flaw in an optimisation layered on top of it.
Building a file to measure
We built a synthetic MRC page rather than use a real scan, so that the ground truth is known to the pixel:
- background: 1275 by 1650, 8-bit
/DeviceGrayat 150 dpi, Flate, 3,191 bytes, an off-white plane with a faint horizontal texture - text layer: 2550 by 3300, the 1-bit
/ImageMaskabove, CCITT Group 4, 3,392 bytes, holding horizontal rules 1, 2, 3, 4, 5, 6, 8 and 12 samples thick and 1800 samples long, vertical bars at the same widths, and one line of DejaVu Serif at 42 pixels, which is about 10 point at 300 dpi - total ink in the stencil: 119,726 samples, or 1.423 per cent of it
- two files, identical except that one adds
/Interpolate trueto the stencil: 7,587 and 7,605 bytes - a third file with the background only, 3,921 bytes, as the control
That control matters. Counting dark pixels in a render does not measure ink, because the background is not white. Every figure below is the background-only render minus the full render, summed, which is ink in units of fully dark pixels and nothing else.
The useful property of this metric is that it tells you which rule a renderer used without reading its source. Area averaging conserves ink exactly: halve the linear scale and the ink quarters, because a stroke covering a quarter of a pixel contributes a quarter. Picking one sample in N does not conserve anything. Each stroke lands at some multiple of its true weight that depends on where the sampling grid happens to fall, and one of the available multiples is zero.
Four renderers, and no disagreement at all
We rendered both files at six widths with four independent engines: pdfium 159.0.8149.0
through pypdfium2 5.15.2, MuPDF 1.28.6 through PyMuPDF 2.1, poppler 24.02.0 through
pdftoppm, and hayro 0.9.0 built from crates.io. The widths are 2550 (one device pixel per
stencil sample), 1275, 918, 816, 612 and 110, the last being a thumbnail.
Whole-stencil ink, as a percentage of the 119,726 source samples scaled by device area, with
no /Interpolate:
| engine | 2550 | 1275 | 918 | 816 | 612 | 110 |
|---|---|---|---|---|---|---|
| pdfium 159.0.8149 | 99.9% | 100.0% | 99.9% | 99.8% | 99.9% | 99.7% |
| MuPDF 1.28.6 | 99.9% | 99.8% | 99.7% | 99.8% | 99.8% | 97.1% |
| poppler 24.02.0 | 99.9% | 100.0% | 97.0% | 102.1% | 101.4% | 100.5% |
| hayro 0.9.0 | 100.0% | 100.0% | 100.0% | 99.9% | 100.2% | 101.3% |
The single thinnest feature, the one-sample rule, which is the first thing a sampling rule loses:
| engine | 2550 | 1275 | 918 | 816 | 612 | 110 |
|---|---|---|---|---|---|---|
| pdfium 159.0.8149 | 99.6% | 100.0% | 99.3% | 98.6% | 100.0% | 104.4% |
| MuPDF 1.28.6 | 99.7% | 98.9% | 100.0% | 99.9% | 97.3% | 84.9% |
| poppler 24.02.0 | 99.7% | 100.1% | 91.8% | 104.0% | 103.3% | 104.4% |
| hayro 0.9.0 | 100.0% | 100.5% | 100.1% | 101.2% | 102.5% | 104.2% |
Every one of them averages. A hairline that is a quarter of a pixel wide survives as a quarter of a pixel of grey, at every scale we tried, right down to a 110 pixel thumbnail where it is one twenty-third of a pixel wide.
Adding /Interpolate true changed nothing that matters here. For pdfium, MuPDF and poppler
the two files produced identical figures to the digit at every width. For hayro the only
difference was at the thumbnail, 101.3 against 103.8 per cent. We also ran hayro with its
force_image_interpolation setting turned on, which again changed only the thumbnail. With the
flag or without it, every engine averaged.
We repeated the poppler and MuPDF measurements on a second machine, on a page we built again from scratch with the rules in different places, and with an older MuPDF, 1.23.10. Both engines again averaged at every width, and again the flag made no difference at all.
pdfium's source says why, and it is worth reading because it is the clearest statement of the distinction we found anywhere. pdfium does read the flag:
interpolate_ = !!pStreamDict->GetIntegerFor("Interpolate");
and it does act on it:
if (GetRenderOptions().GetOptions().bNoImageSmooth) {
resample_options_.bNoSmoothing = true;
} else if (image_object_->GetImage()->IsInterpol()) {
resample_options_.bInterpolateBilinear = true;
}
But bInterpolateBilinear is only ever consulted inside one branch of the weight-table
builder, and that branch is guarded like this, where scale is source length over destination
length:
if (options.bNoSmoothing || fabs(scale) < 1.0f) {
scale < 1 means the destination is larger than the source: the image is being enlarged.
Shrinking falls past this branch into a loop that computes, for each destination pixel, the
exact fractional overlap of every source pixel that lands in it. The flag reaches the
enlarging case and cannot reach the shrinking one. That is the same division PdfCraft's own
comment describes, implemented.
Replaying the two rules on the same stencil
To put a number on what the other choice costs, we took the stencil itself and applied both
rules in Python: PdfCraft's nearest_source_index, transcribed arithmetic for arithmetic from
v0.18.1, and an exact box filter. Same mask, same targets, no renderer involved.
Ink retained per rule thickness, and in brackets the share of device columns across that rule's own length that hold no ink at all, which is what "broken" means:
| target | rule | area averaging | nearest sampling |
|---|---|---|---|
| 1275 (0.50x) | 1 sample | 450.0, exact (0% empty) | 0.0 (100% empty) |
| 1275 (0.50x) | 5 samples | 2250.0, exact | 1800.0, 80.0% |
| 918 (0.36x) | 1 sample | 233.3, exact (0% empty) | 648.0, 277.8% |
| 816 (0.32x) | 1 sample | 184.3, exact (0% empty) | 0.0 (100% empty) |
| 816 (0.32x) | 2 samples | 368.6, exact (0% empty) | 0.0 (100% empty) |
| 612 (0.24x) | 1 sample | 103.7, exact (0% empty) | 0.0 (100% empty) |
| 612 (0.24x) | 2 samples | 207.4, exact (0% empty) | 0.0 (100% empty) |
| 612 (0.24x) | 3 samples | 311.0, exact | 432.0, 138.9% |
| 110 (0.043x) | 1 to 8 samples | exact, every rule present | 0.0, all eight gone |
| 110 (0.043x) | 12 samples | 40.4, exact | 78.0, 193.2% |
Area averaging reproduced the expected ink to the digit in every cell, which is what an exact box filter does. Nearest sampling is wrong in both directions. At 0.36x the hairline is not missing, it is 2.8 times too dark, because the one device row that happens to land on it takes the full sample and the rows either side take none. At 0.32x, a change of about one zoom step, the same hairline is gone completely. The rendered line of text tells the same story: the share of empty columns across it rises from 27.5 per cent at 1:1, which is the real gaps between words, to 44.6 per cent at 612 pixels under nearest against 14.8 per cent under averaging, and to 80.4 per cent against 1.8 per cent at the thumbnail.
Do not read the individual cells as properties of a one-sample rule at 0.36x. They are properties of where that rule sits relative to the sampling grid. On the second page we built, with the same rules in different positions, the one-sample rule was gone at 0.36x instead of too dark, the three-sample rule vanished at 0.24x, and the eight-sample rule survived the thumbnail. Area averaging gave the exact expected figure on both pages. The cells change from page to page; the pattern does not.
Whether your hairline exists depends on the zoom, not the file
Because the loss depends on where the sampling grid falls rather than on anything in the document, the same file renders differently at neighbouring zoom levels. We swept 33 device widths from 400 to 1200 pixels in steps of 25, and asked only whether each rule left any ink at all:
rule appears at
1 sample 11 of 33 ..#..#..#....#..#..#..#.##.#..#..
2 samples 21 of 33 ...#.#.#.##.#.#.#.######.#.######
3 samples 29 of 33 .###.###.###.####################
4 samples 32 of 33 ########.########################
5 samples 31 of 33 ..###############################
6 samples 33 of 33 #################################
A . is a zoom level at which that rule is absent from the raster entirely. Area averaging
keeps all six rules at all 33 widths, which we checked rather than assumed. The second page gave
the same shape with different dots: the one-sample rule appeared at 12 of 33 widths, the
two-sample rule at 22.
This is why "if I zoom in far enough everything comes back", in the complaint at the top of this post, is the signature of the bug rather than a sign that the file is fine. One step in that sweep is 25 pixels, about 3 per cent of the page width at these sizes. A line that is there at one width and gone at the next is not a property of the document.
The page total does not notice
The reason this can ship is in the same replay, read the other way. At the four screen-sized targets, 1275 to 612 pixels wide, the whole stencil's ink under nearest sampling stayed between 87.2 and 110.4 per cent of the true value; on the second page, between 91.1 and 101.0. The page-level number looks healthy. Meanwhile, at 0.24x, two of the eight rules had vanished and a third was 39 per cent too dark. Only the thumbnail of the second page moved the total further, to 120 per cent, and a thumbnail is the view nobody inspects.
That is the general shape: a per-stroke failure averaged over a page looks like noise, because the strokes that gain cancel the strokes that vanish. Any check on total ink, mean intensity, or a perceptual diff of the whole page will pass. The thing that catches it is asking about the thinnest feature you care about, separately, which for a scanned form is a rule on a table and for scanned prose is the stem of a letter.
What the fix looks like
PdfCraft's fix is in the vendored renderer now. The function doing the shrinking is
area_shrink, which first appears at tag v0.19.0, released on 6 November; it is absent from
v0.18.1 and v0.18.2. The decision is now made on the geometry rather than the flag:
// PdfCraft patch: an image that did not ask for interpolation and is drawn below its
// resolution is shrunk by area averaging (`area_shrink`), not nearest-neighbour, which
// broke up the text of scans shown at screen size. Type 3 glyph images keep the nearest
// shrink of #624: they are drawn with a frame of their own and never snapped.
Note what the fix preserves: the original concern was real, so images drawn at or above their own resolution still keep their hard pixels, and area averaging never enlarges. The fix is not "always filter". It is "filter when shrinking, and ask the flag only about enlarging". Note too what it leaves out. Bitmap glyphs in Type 3 fonts still take the nearest shrink, and so does any image more than 1,048,576 samples on a side.
The strangest part is that the right sentence was in the file all along. An earlier patch, for a
soft mask drawn at a different size from its image, already says it, and that comment is
present at v0.14.0, the very version the scan bug was reported against:
// Shrunk by nearest-neighbour it keeps one sample in N and drops every stroke thinner
// than N mask pixels, so a shrunk mask is filtered whatever its `/Interpolate`, which
// only asks for smoothing when the mask is enlarged.
That clause is the whole post in one line. It just was not applied to the stencil path, which is what the reporter of #4800 pointed out.
Issue #4800 is still open as of writing. A bot on the thread says the work is happening in #2288; #2288 is a pull request, still open, and it is attached to a narrower issue about Type 3 image-mask glyphs rather than to this one, which fits the exception above. We did not run PdfCraft itself, so we cannot tell you what any given build on your machine does. What we can tell you is which code is in which tag, because we read the tags.
Where AegisPDF fits
AegisPDF renders page previews with pdfium, so this failure mode is one it could have had. We
checked, at prod 6ec7a14.
The engine crate declares pdfium-render = { version = "0.9", features = ["pdfium_latest", "image_latest", "console_log"] }, and render_page hands pdfium a target size directly:
let config = PdfRenderConfig::new()
.set_target_size(target_width as Pixels, target_height as Pixels)
.render_form_data(true);
The callers pick sizes that do shrink a 300 dpi scan substantially. The main viewer uses
const SCALE = 1.5, so a Letter page renders at 918 by 1188, which is 0.36 of the stencil's
width. The page thumbnails are smaller still, THUMB_W = 110 and THUMB_H = 142. Both of
those are widths in the tables above, chosen for that reason, and pdfium kept the one-sample
rule at 99.3 per cent and 104.4 per cent of its true weight respectively. The OCR path renders
separately at const OCR_SCALE = 4.17, with the comment "OCR renders at ~300 DPI (4.17x of
72-DPI PDF points)", so it feeds the recognizer something close to the stencil's own
resolution and never shrinks it at all.
So: not affected, and for a structural reason rather than by luck. The averaging happens
inside pdfium's weight-table builder, below the API AegisPDF uses, and /Interpolate cannot
reach it. There is one switch that could: pdfium's FPDF_RENDER_NO_SMOOTHIMAGE render flag
sets the bNoSmoothing you can see in the guard above, and that sends shrinking down the
sampling branch too. In pdfium-render 0.9.1, the version AegisPDF locks, that flag is off
unless the caller asks for it, and AegisPDF never asks.
Two boundaries on that, stated because they are real gaps. First, the pdfium we measured is
159.0.8149.0, the build that ships with pypdfium2 5.15.2. AegisPDF ships a different build: its
justfile pins pdfium_version := "7623" and fetches a browser build of pdfium from the
pdfium-lib project at that release. We read pdfium's own chromium/7623 branch, and the
weight-table logic in cstretchengine.cpp and the flag handling in cpdf_imagerenderer.cpp
match the main source quoted above, line for line apart from formatting. We did not run that
build.
Second, the 918-pixel bitmap is not the end of the line. AegisPDF's zoom control does not re-render the page: it changes the displayed size of that fixed bitmap, so whenever the displayed size differs from the bitmap's own, the browser resamples it again. That is exactly the "viewer is not a library" case described below, and we did not measure it. What pdfium hands the browser is already averaged, so a hairline arrives as a light grey line rather than as a sampled one, but what each browser does with it next is its own business.
If you render PDFs
- Treat
/Interpolateas a question about enlarging only. It is not a statement that an image does not need filtering, and the two cases want opposite defaults: do not invent samples when blowing up unless asked, and always weigh samples when shrinking, asked or not. - Stencils are where it shows first. A
/ImageMaskis 1-bit by definition, so there is no intermediate value to lose gradually. A stroke is either sampled or it is not. - Pick the thinnest feature that matters and measure it on its own. We would not have found any of this from a whole-page ink total, which stayed within about 13 per cent of correct at screen sizes while rules were disappearing.
- Be suspicious of a sampling decision taken in a performance patch. The one here is well-reasoned about the case it names, cites the right default, and is still wrong, because the case it names is not the case that reaches it most often.
- If a scan looks broken in one viewer and fine in another, check the zoom dependence before the file. Content does not come and go with a 5 per cent zoom change.
What this does not cover
We measured two synthetic MRC pages, built to make the ground truth exact, rather than a corpus of real scanner output. Real scans vary in how they lay out the two layers, and some use a soft mask rather than a stencil, which is a different code path in every engine here.
We did not run PdfCraft, so every claim about it comes from its source at named tags and from the issue thread, and we cannot say what its shipped binaries render. We did not read ISO 32000: the specification was not reachable from this machine, so where the post needed the flag's meaning it quotes a renderer's own comment and its own citation rather than the standard.
The four engines were measured as libraries at fixed target sizes. A viewer is not a library: it may re-sample a cached tile, snap to device pixels, or render at a different scale than it displays, and any of those can reintroduce a sampling step after the engine has done the right thing. We measured the engines, not anybody's viewer.
Nothing here is a claim about which renderer is better. On this one question all four engines we measured agreed. The renderer that got it wrong, which we did not run, got it wrong in a local patch, and its own source has since replaced that patch.