Commit 436d7e81c for llama.cpp

commit 436d7e81ca593e294761428b4fe3d6cafef6800f
Author: Jesse <jesse@createthis.com>
Date:   Thu Nov 26 08:57:50 2026 -0500

    DPI setting for PDF as Images - Inkling-2-Mini-BF16's work (#33061)

diff --git a/tools/server/README.md b/tools/server/README.md
index e854ea2ea..62cc57551 100644
--- a/tools/server/README.md
+++ b/tools/server/README.md
@@ -2671,6 +2671,12 @@ You can specify default preferences for Llama Chat using `--ui-config <JSON conf
 ./llama-server -m model.gguf --ui-config '{"pasteLongTextToFileLen": 0, "renderUserContentAsMarkdown": true}'
 ```

+You can also set the DPI used when parsing a PDF as images (default 108), e.g. 216 for dense tables:
+
+```bash
+./llama-server -m model.gguf --ui-config '{"pdfAsImage": true, "pdfDpi": 216}'
+```
+
 > **Note:** The old flags `--webui-config` and `--webui-config-file` are deprecated but still work as aliases.

 You may find available preferences in [settings-keys.ts](../ui/src/lib/constants/settings-keys.ts).
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemPdf.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemPdf.svelte
index 07a08026c..3471d13b3 100644
--- a/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemPdf.svelte
+++ b/ui/apps/chat/src/lib/components/app/chat/ChatAttachments/ChatAttachmentsPreview/ChatAttachmentsPreviewCurrentItem/ChatAttachmentsPreviewCurrentItemPdf.svelte
@@ -5,9 +5,11 @@
 	import { SyntaxHighlightedCode } from '#lib/components/app/index.ts';
 	import { ICON_CLASS_DEFAULT, PDF_AS_IMAGES_LEGACY_CONTENT_REGEX } from '#lib/constants/index.ts';
 	import { AttachmentType, MimeTypeApplication, PdfViewMode } from '#lib/enums/index.ts';
+	import { settingsStore } from '#lib/stores/settings/index.svelte.ts';
 	import type { ChatAttachmentDisplayItem } from '#lib/types/index.ts';
 	import { convertPDFToImage, convertPDFToText } from '#lib/utils/browser-only.ts';
 	import { getLanguageFromFilename } from '#lib/utils/index.ts';
+	import { clampPdfDpi } from '#lib/utils/pdf-dpi.ts';

 	interface Props {
 		currentItem: ChatAttachmentDisplayItem | null;
@@ -23,7 +25,9 @@
 	let pdfViewMode = $state<PdfViewMode>(PdfViewMode.PAGES);
 	let pdfImages = $state<string[]>([]);
 	let pdfImagesLoading = $state(false);
-	// a failure stays on screen: the effect does not retry while an error is set
+	// DPI the last fresh render (or failed attempt) used; stored attachment images are shown as-is
+	let pdfImagesDpi = $state<number | null>(null);
+	// a failure stays on screen: the effect does not retry while an error is set at the current DPI
 	let pdfImagesError = $state<string | null>(null);
 	let pdfText = $state<string | null>(null);
 	let pdfTextLoading = $state(false);
@@ -64,7 +68,7 @@
 	}

 	async function loadPdfImages() {
-		if (pdfImages.length > 0 || pdfImagesLoading || !currentItem) return;
+		if (!currentItem) return;

 		if (
 			currentItem.attachment?.type === AttachmentType.PDF &&
@@ -75,9 +79,16 @@
 			return;
 		}

-		if (pdfImagesError) return;
+		const dpi = clampPdfDpi(settingsStore.config.pdfDpi);
+
+		if (pdfImagesLoading) return;
+
+		if (pdfImages.length > 0 && pdfImagesDpi === dpi) return;
+
+		if (pdfImagesError && pdfImagesDpi === dpi) return;

 		pdfImagesLoading = true;
+		pdfImagesError = null;

 		try {
 			const file = getPdfFile();
@@ -86,10 +97,12 @@
 				throw new Error('No PDF file available for conversion');
 			}

-			pdfImages = await convertPDFToImage(file);
+			pdfImages = await convertPDFToImage(file, dpi);
 		} catch (error) {
 			pdfImagesError = error instanceof Error ? error.message : 'Failed to load PDF images';
 		} finally {
+			// remember the attempt even on failure, so a DPI change is the one retry
+			pdfImagesDpi = dpi;
 			pdfImagesLoading = false;
 		}
 	}
@@ -123,6 +136,9 @@
 	}

 	$effect(() => {
+		// reaching the DPI here re-runs the effect when the setting changes
+		void settingsStore.config.pdfDpi;
+
 		if (pdfViewMode === PdfViewMode.PAGES) {
 			loadPdfImages();
 		} else {
diff --git a/ui/apps/chat/src/lib/constants/settings-keys.constants.ts b/ui/apps/chat/src/lib/constants/settings-keys.constants.ts
index c6b4921e3..bd317913d 100644
--- a/ui/apps/chat/src/lib/constants/settings-keys.constants.ts
+++ b/ui/apps/chat/src/lib/constants/settings-keys.constants.ts
@@ -46,6 +46,7 @@ export const SETTINGS_KEYS = {
 	// Display
 	PASTE_LONG_TEXT_TO_FILE_LEN: 'pasteLongTextToFileLen',
 	PDF_AS_IMAGE: 'pdfAsImage',
+	PDF_DPI: 'pdfDpi',
 	// Performance
 	PRE_ENCODE_CONVERSATION: 'preEncodeConversation',
 	PRESENCE_PENALTY: 'presence_penalty',
diff --git a/ui/apps/chat/src/lib/constants/settings.constants.ts b/ui/apps/chat/src/lib/constants/settings.constants.ts
index db19f27d2..7f8d8c71c 100644
--- a/ui/apps/chat/src/lib/constants/settings.constants.ts
+++ b/ui/apps/chat/src/lib/constants/settings.constants.ts
@@ -3,6 +3,7 @@ import { CLI_FLAGS } from './cli-flags.constants';
 import { COMPACTION } from './compaction.constants';
 import { DEFAULT_MCP_CONFIG } from './mcp.constants';
 import { SETTINGS_KEYS } from './settings-keys.constants';
+import { PDF_RENDERING } from './supported-file-types.constants';
 import { TITLE_GENERATION } from './title-generation.constants';
 import { VOICE_TRANSCRIPTION_MODEL_AUTO } from './voice.constants';
 import { FILE_GLOB_SEARCH_PICKERS } from './working-directory.constants';
@@ -233,6 +234,18 @@ export const SETTINGS_REGISTRY: SettingsSectionEntry[] = [
 				label: 'Parse PDF as image',
 				type: SettingsFieldType.CHECKBOX
 			},
+			{
+				defaultValue: PDF_RENDERING.DEFAULT_DPI,
+				dependsOn: SETTINGS_KEYS.PDF_AS_IMAGE,
+				help: 'Pixels per inch each PDF page renders as when it is parsed as images. 108 is the default; 216 is a good fit for dense tables.',
+				isPositiveInteger: true,
+				key: SETTINGS_KEYS.PDF_DPI,
+				label: 'PDF image DPI',
+				max: PDF_RENDERING.MAX_DPI,
+				min: PDF_RENDERING.MIN_DPI,
+				placeholder: String(PDF_RENDERING.DEFAULT_DPI),
+				type: SettingsFieldType.INPUT
+			},
 			{
 				defaultValue: 0,
 				help: 'Images larger than this will be resized before sending to server. Set to 0 to disable.',
diff --git a/ui/apps/chat/src/lib/constants/supported-file-types.constants.ts b/ui/apps/chat/src/lib/constants/supported-file-types.constants.ts
index 88ca4145f..85cd19892 100644
--- a/ui/apps/chat/src/lib/constants/supported-file-types.constants.ts
+++ b/ui/apps/chat/src/lib/constants/supported-file-types.constants.ts
@@ -74,6 +74,14 @@ export const IMAGE_FILE_TYPES = {
 	}
 } as const;

+/** Rendering defaults for PDF pages converted to images. PDF.js maps 1.0 scale to 72 DPI. */
+export const PDF_RENDERING = {
+	DEFAULT_DPI: 108,
+	MAX_DPI: 600,
+	MIN_DPI: 72,
+	POINTS_PER_INCH: 72
+} as const;
+
 /** `content` that messages stored before the text was kept carry for a PDF sent as images. */
 export const PDF_AS_IMAGES_LEGACY_CONTENT_REGEX = /^PDF file with \d+ pages$/;

diff --git a/ui/apps/chat/src/lib/utils/convert-files-to-extra.ts b/ui/apps/chat/src/lib/utils/convert-files-to-extra.ts
index 4e50b089c..0faeb8170 100644
--- a/ui/apps/chat/src/lib/utils/convert-files-to-extra.ts
+++ b/ui/apps/chat/src/lib/utils/convert-files-to-extra.ts
@@ -1,3 +1,4 @@
+import { clampPdfDpi } from './pdf-dpi';
 import { convertPDFToImage, convertPDFToText } from './pdf-processing';
 import { isSvgMimeType, svgBase64UrlToPngDataURL } from './svg-to-png';
 import { isLikelyTextFile, readFileAsText } from './text-files';
@@ -152,7 +153,7 @@ export async function parseFilesToMessageExtras(
 				if (shouldProcessAsImages) {
 					// Process PDF as images (only for vision models)
 					try {
-						const images = await convertPDFToImage(file.file);
+						const images = await convertPDFToImage(file.file, clampPdfDpi(currentConfig.pdfDpi));
 						// kept for the preview's Text view; the model only receives the images
 						const content = file.textContent ?? (await convertPDFToText(file.file).catch(() => ''));

diff --git a/ui/apps/chat/src/lib/utils/pdf-dpi.ts b/ui/apps/chat/src/lib/utils/pdf-dpi.ts
new file mode 100644
index 000000000..0ed602da2
--- /dev/null
+++ b/ui/apps/chat/src/lib/utils/pdf-dpi.ts
@@ -0,0 +1,25 @@
+import { PDF_RENDERING } from '#lib/constants/index.ts';
+
+/**
+ * A PDF.js scale is the ratio of rendered pixels to PDF points: at 1.0 a page renders at
+ * 72 DPI, so scale is DPI / 72.
+ * @param dpi - the DPI to convert
+ * @returns the PDF.js scale factor for the given DPI
+ */
+export function pdfDpiToScale(dpi: number): number {
+	return dpi / PDF_RENDERING.POINTS_PER_INCH;
+}
+
+/**
+ * Clamp a user-supplied DPI into the supported range. Anything that is not a finite number
+ * (missing key, empty field, junk) falls back to the default the setting ships with.
+ * @param value - the raw value from the settings config
+ * @returns a DPI between MIN_DPI and MAX_DPI
+ */
+export function clampPdfDpi(value: unknown): number {
+	const dpi = typeof value === 'string' ? (value.trim() === '' ? undefined : Number(value)) : value;
+
+	if (typeof dpi !== 'number' || !Number.isFinite(dpi)) return PDF_RENDERING.DEFAULT_DPI;
+
+	return Math.min(Math.max(Math.round(dpi), PDF_RENDERING.MIN_DPI), PDF_RENDERING.MAX_DPI);
+}
diff --git a/ui/apps/chat/src/lib/utils/pdf-processing.ts b/ui/apps/chat/src/lib/utils/pdf-processing.ts
index ca5074db1..c9de5b97a 100644
--- a/ui/apps/chat/src/lib/utils/pdf-processing.ts
+++ b/ui/apps/chat/src/lib/utils/pdf-processing.ts
@@ -3,7 +3,9 @@
  * Handles PDF text extraction and image conversion in the browser
  */

+import { PDF_RENDERING } from '#lib/constants/index.ts';
 import { MimeTypeApplication, MimeTypeImage } from '#lib/enums/index.ts';
+import { clampPdfDpi, pdfDpiToScale } from '#lib/utils/pdf-dpi.ts';
 import { browser } from '$app/env';
 import pdfWorkerUrl from 'pdfjs-dist/build/pdf.worker.min.mjs?url';

@@ -87,10 +89,13 @@ export async function convertPDFToText(file: File): Promise<string> {
 /**
  * Convert PDF pages to PNG images as data URLs
  * @param file - The PDF file to convert
- * @param scale - Rendering scale factor (default: 1.5)
+ * @param dpi - Rendering DPI (default: 108, the scale the app shipped with)
  * @returns Promise resolving to array of PNG data URLs
  */
-export async function convertPDFToImage(file: File, scale: number = 1.5): Promise<string[]> {
+export async function convertPDFToImage(
+	file: File,
+	dpi: number = PDF_RENDERING.DEFAULT_DPI
+): Promise<string[]> {
 	if (!browser) {
 		throw new Error('PDF processing is only available in the browser');
 	}
@@ -99,6 +104,7 @@ export async function convertPDFToImage(file: File, scale: number = 1.5): Promis
 		const [pdfjs, buffer] = await Promise.all([loadPdfjs(), getFileAsBuffer(file)]);
 		const doc = await pdfjs.getDocument({ data: buffer }).promise;
 		const pages: Promise<string>[] = [];
+		const scale = pdfDpiToScale(clampPdfDpi(dpi));

 		for (let i = 1; i <= doc.numPages; i++) {
 			const page = await doc.getPage(i);
diff --git a/ui/apps/chat/tests/client/pdf-processing.svelte.test.ts b/ui/apps/chat/tests/client/pdf-processing.svelte.test.ts
index 63e941306..1ca49134e 100644
--- a/ui/apps/chat/tests/client/pdf-processing.svelte.test.ts
+++ b/ui/apps/chat/tests/client/pdf-processing.svelte.test.ts
@@ -32,6 +32,16 @@ function pdfWithText(text: string): File {
 	return new File([body], 'hello.pdf', { type: 'application/pdf' });
 }

+function imageDimensions(dataUrl: string): Promise<{ width: number; height: number }> {
+	return new Promise((resolve, reject) => {
+		const img = new Image();
+
+		img.onload = () => resolve({ height: img.naturalHeight, width: img.naturalWidth });
+		img.onerror = () => reject(new Error('Failed to decode the rendered PNG'));
+		img.src = dataUrl;
+	});
+}
+
 describe('pdf-processing', () => {
 	it('extracts the text of a PDF', async () => {
 		const text = await convertPDFToText(pdfWithText('Hello from a PDF'));
@@ -45,4 +55,32 @@ describe('pdf-processing', () => {
 		expect(pages).toHaveLength(1);
 		expect(pages[0]).toMatch(/^data:image\/png;base64,/);
 	});
+
+	it('renders pages at the requested DPI', async () => {
+		const onePage = pdfWithText('Page one');
+		const atDefault = await convertPDFToImage(onePage);
+		const at216 = await convertPDFToImage(onePage, 216);
+		const at72 = await convertPDFToImage(onePage, 72);
+
+		expect(atDefault[0]).toMatch(/^data:image\/png;base64,/);
+
+		const defaultSize = await imageDimensions(atDefault[0]);
+		const highSize = await imageDimensions(at216[0]);
+		const lowSize = await imageDimensions(at72[0]);
+
+		// the fixture page is 612 x 792 PDF points, so 72 DPI is 1:1
+		expect(lowSize.width).toBe(612);
+		expect(lowSize.height).toBe(792);
+		// 216 DPI is 2x the scale the default (108) renders at
+		expect(highSize.width).toBeCloseTo(defaultSize.width * 2, 0);
+		expect(highSize.height).toBeCloseTo(defaultSize.height * 2, 0);
+	});
+
+	it('clamps an out-of-range DPI instead of rendering it', async () => {
+		const pages = await convertPDFToImage(pdfWithText('Page one'), 10);
+		const size = await imageDimensions(pages[0]);
+
+		// 10 DPI clamps to 72, the 1:1 scale
+		expect(size.width).toBe(612);
+	});
 });
diff --git a/ui/apps/chat/tests/unit/pdf-dpi.test.ts b/ui/apps/chat/tests/unit/pdf-dpi.test.ts
new file mode 100644
index 000000000..25a1284fb
--- /dev/null
+++ b/ui/apps/chat/tests/unit/pdf-dpi.test.ts
@@ -0,0 +1,38 @@
+import { PDF_RENDERING, SETTING_CONFIG_DEFAULT, SETTINGS_KEYS } from '#lib/constants/index.ts';
+import { clampPdfDpi, pdfDpiToScale } from '#lib/utils/pdf-dpi.ts';
+import { describe, expect, it } from 'vitest';
+
+describe('pdf-dpi', () => {
+	it('converts DPI to a PDF.js scale factor of pixels per PDF point', () => {
+		expect(pdfDpiToScale(72)).toBe(1);
+		expect(pdfDpiToScale(108)).toBeCloseTo(1.5, 10);
+		expect(pdfDpiToScale(216)).toBe(3);
+	});
+
+	it('rounds, clamps and falls back to the default', () => {
+		expect(clampPdfDpi(108)).toBe(108);
+		expect(clampPdfDpi(216.4)).toBe(216);
+		expect(clampPdfDpi(1000)).toBe(PDF_RENDERING.MAX_DPI);
+		expect(clampPdfDpi(10)).toBe(PDF_RENDERING.MIN_DPI);
+		expect(clampPdfDpi('216')).toBe(216);
+		expect(clampPdfDpi('junk')).toBe(PDF_RENDERING.DEFAULT_DPI);
+		expect(clampPdfDpi('')).toBe(PDF_RENDERING.DEFAULT_DPI);
+		expect(clampPdfDpi('   ')).toBe(PDF_RENDERING.DEFAULT_DPI);
+		expect(clampPdfDpi(undefined)).toBe(PDF_RENDERING.DEFAULT_DPI);
+		expect(clampPdfDpi(null)).toBe(PDF_RENDERING.DEFAULT_DPI);
+		expect(clampPdfDpi(NaN)).toBe(PDF_RENDERING.DEFAULT_DPI);
+		expect(clampPdfDpi(Infinity)).toBe(PDF_RENDERING.DEFAULT_DPI);
+	});
+});
+
+describe('PDF DPI setting', () => {
+	it('ships a default that is inside its own range', () => {
+		expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.PDF_DPI]).toBe(PDF_RENDERING.DEFAULT_DPI);
+		expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.PDF_DPI]).toBeGreaterThanOrEqual(
+			PDF_RENDERING.MIN_DPI
+		);
+		expect(SETTING_CONFIG_DEFAULT[SETTINGS_KEYS.PDF_DPI]).toBeLessThanOrEqual(
+			PDF_RENDERING.MAX_DPI
+		);
+	});
+});