feat(conversion): add SVG to PDF conversion functionality (#5431)

# Description of Changes


This pull request introduces a new SVG to PDF conversion feature,
including both backend and frontend changes. The backend adds a secure,
vector-preserving SVG-to-PDF conversion endpoint with comprehensive SVG
sanitization to prevent XSS and SSRF attacks. The frontend is updated to
route SVG-to-PDF conversions through this new endpoint and to
distinguish SVG from other image formats. Additionally, a new dependency
is added for PDF rendering.

**Backend: SVG to PDF Conversion and Security**

* Adds a new API endpoint and controller (`ConvertSvgToPDF`) for
converting SVG files to PDF, using Batik and PDFBox with vector graphics
preservation and robust error handling.
* Implements SVG sanitization (`SvgSanitizer`) to remove scripts, event
handlers, and dangerous URLs, protecting against XSS and SSRF attacks.
* Introduces a utility (`SvgToPdf`) for rendering SVG to PDF with
timeout protection against resource exhaustion attacks.
* Defines a new request model (`SvgToPdfRequest`) for SVG to PDF
conversion requests.
* Adds the `pdfbox-graphics2d` dependency for vector graphics PDF
rendering.

**Frontend: Routing and Format Handling**

* Updates conversion endpoint constants to add `svg-pdf` and maps SVG
files to use the new `svg-to-pdf` route instead of the generic
image-to-PDF route.
* Removes SVG from the generic image format list and introduces a
dedicated check for SVG format (`isSvgFormat`).
<img width="1133" height="995" alt="image"
src="https://github.com/user-attachments/assets/dec8cf27-ccb9-490d-af76-bff69feb0423"
/>

<!--
Please provide a summary of the changes, including:

- What was changed
- Why the change was made
- Any challenges encountered

Closes #(issue_number)
-->

---

## Checklist

### General

- [X] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [X] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md)
(if applicable)
- [X] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [X] I have performed a self-review of my own code
- [X] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### Translations (if applicable)

- [ ] I ran
[`scripts/counter_translation.py`](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/docs/counter_translation.md)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [X] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing)
for more details.

---------

Signed-off-by: Balázs Szücs <[email protected]>
This commit is contained in:
Balázs Szücs
2026-01-16 18:45:50 +00:00
committed by GitHub
parent 3e061516a5
commit cb5c2a5803
17 changed files with 1150 additions and 27 deletions
@@ -77,15 +77,26 @@ export const ImageUploader: React.FC<ImageUploaderProps> = ({
setCurrentFile(file);
onImageChange(file);
const originalDataUrl = await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => resolve(e.target?.result as string);
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(file);
});
let dataUrlToProcess: string;
// Check if file is SVG
const isSvg = file.type === 'image/svg+xml' || file.name.toLowerCase().endsWith('.svg');
if (isSvg) {
// For SVG, convert to PNG so it can be embedded in PDF
dataUrlToProcess = await convertSvgToPng(file);
} else {
// For other images, read as data URL directly
dataUrlToProcess = await new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => resolve(e.target?.result as string);
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(file);
});
}
setOriginalImageData(originalDataUrl);
await processImage(file, removeBackground);
setOriginalImageData(dataUrlToProcess);
await processImage(dataUrlToProcess, removeBackground);
} catch (error) {
console.error('Error processing image file:', error);
}
@@ -98,6 +109,115 @@ export const ImageUploader: React.FC<ImageUploaderProps> = ({
}
};
// Helper function to convert SVG to PNG
const convertSvgToPng = async (file: File): Promise<string> => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = async (e) => {
try {
const svgText = e.target?.result as string;
// Parse SVG to get dimensions
const parser = new DOMParser();
const svgDoc = parser.parseFromString(svgText, 'image/svg+xml');
const svgElement = svgDoc.documentElement;
// Get SVG dimensions
let width = 800; // Default width
let height = 600; // Default height
if (svgElement.hasAttribute('width') && svgElement.hasAttribute('height')) {
width = parseFloat(svgElement.getAttribute('width') || '800');
height = parseFloat(svgElement.getAttribute('height') || '600');
} else if (svgElement.hasAttribute('viewBox')) {
const viewBox = svgElement.getAttribute('viewBox')?.split(/\s+|,/);
if (viewBox && viewBox.length === 4) {
width = parseFloat(viewBox[2]);
height = parseFloat(viewBox[3]);
}
}
// Ensure reasonable dimensions
if (width === 0 || height === 0 || !isFinite(width) || !isFinite(height)) {
width = 800;
height = 600;
}
// Scale large SVGs down
const maxDimension = 2048;
if (width > maxDimension || height > maxDimension) {
const scale = Math.min(maxDimension / width, maxDimension / height);
width *= scale;
height *= scale;
}
console.log('Converting SVG to PNG:', { width, height });
// Create an image element to render SVG
const img = new Image();
const blob = new Blob([svgText], { type: 'image/svg+xml;charset=utf-8' });
const url = URL.createObjectURL(blob);
img.onload = () => {
try {
// Use computed dimensions or image natural dimensions
const finalWidth = img.naturalWidth || img.width || width;
const finalHeight = img.naturalHeight || img.height || height;
console.log('Image loaded:', { naturalWidth: img.naturalWidth, naturalHeight: img.naturalHeight, finalWidth, finalHeight });
// Create canvas to convert to PNG
const canvas = document.createElement('canvas');
canvas.width = finalWidth;
canvas.height = finalHeight;
const ctx = canvas.getContext('2d');
if (!ctx) {
URL.revokeObjectURL(url);
reject(new Error('Failed to get canvas context'));
return;
}
// Fill with white background (optional, for transparency support)
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, finalWidth, finalHeight);
// Draw SVG
ctx.drawImage(img, 0, 0, finalWidth, finalHeight);
URL.revokeObjectURL(url);
// Convert canvas to PNG data URL
const pngDataUrl = canvas.toDataURL('image/png');
console.log('SVG converted to PNG successfully');
resolve(pngDataUrl);
} catch (error) {
URL.revokeObjectURL(url);
console.error('Error during canvas rendering:', error);
reject(error);
}
};
img.onerror = (error) => {
URL.revokeObjectURL(url);
console.error('Failed to load SVG image:', error);
reject(new Error('Failed to load SVG image'));
};
img.src = url;
} catch (error) {
console.error('Error parsing SVG:', error);
reject(error);
}
};
reader.onerror = () => {
console.error('Error reading file:', reader.error);
reject(reader.error);
};
reader.readAsText(file);
});
};
const handleBackgroundRemovalChange = async (checked: boolean) => {
if (isProcessing) return; // Prevent race conditions
setRemoveBackground(checked);
@@ -59,7 +59,7 @@ export const ImageTool: React.FC<ImageToolProps> = ({
disabled={disabled}
label="Upload Image"
placeholder="Select image file"
hint="Upload a PNG, JPG, or other image file to place on the PDF"
hint="Upload a PNG, JPG, SVG, or other image file to place on the PDF. SVG files will be converted to PNG for compatibility."
/>
</Stack>
</BaseAnnotationTool>
@@ -0,0 +1,41 @@
import { Stack, Text, Switch } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { ConvertParameters } from "@app/hooks/tools/convert/useConvertParameters";
interface ConvertFromSvgSettingsProps {
parameters: ConvertParameters;
onParameterChange: <K extends keyof ConvertParameters>(key: K, value: ConvertParameters[K]) => void;
disabled?: boolean;
}
const ConvertFromSvgSettings = ({
parameters,
onParameterChange,
disabled = false
}: ConvertFromSvgSettingsProps) => {
const { t } = useTranslation();
return (
<Stack gap="sm" data-testid="svg-pdf-options-section">
<Text size="sm" fw={500}>{t("convert.svgPdfOptions", "SVG to PDF Options")}:</Text>
<Switch
data-testid="combine-svgs-switch"
label={t("convert.combineSvgs", "Combine SVGs into single PDF")}
description={t("convert.combineSvgsDescription", "Combine all SVG files into one PDF with multiple pages, or create separate PDFs for each SVG")}
checked={parameters.imageOptions.combineImages}
onChange={(event) => onParameterChange('imageOptions', {
...parameters.imageOptions,
combineImages: event.currentTarget.checked
})}
disabled={disabled}
/>
<Text size="xs" c="dimmed" mt="xs">
{t("convert.svgVectorNote", "SVG files are rendered as vector graphics for crisp output at any resolution. Dimensions from the SVG determine the PDF page size.")}
</Text>
</Stack>
);
};
export default ConvertFromSvgSettings;
@@ -20,6 +20,7 @@ import ConvertToPdfaSettings from "@app/components/tools/convert/ConvertToPdfaSe
import ConvertFromCbrSettings from "@app/components/tools/convert/ConvertFromCbrSettings";
import ConvertToCbrSettings from "@app/components/tools/convert/ConvertToCbrSettings";
import ConvertFromEbookSettings from "@app/components/tools/convert/ConvertFromEbookSettings";
import ConvertFromSvgSettings from "@app/components/tools/convert/ConvertFromSvgSettings";
import ConvertToEpubSettings from "@app/components/tools/convert/ConvertToEpubSettings";
import { ConvertParameters } from "@app/hooks/tools/convert/useConvertParameters";
import {
@@ -331,6 +332,18 @@ const ConvertSettings = ({
</>
) : null}
{/* SVG to PDF options */}
{parameters.fromExtension === 'svg' && parameters.toExtension === 'pdf' && (
<>
<Divider />
<ConvertFromSvgSettings
parameters={parameters}
onParameterChange={onParameterChange}
disabled={disabled}
/>
</>
)}
{/* Web to PDF options */}
{((isWebFormat(parameters.fromExtension) && parameters.toExtension === 'pdf') ||
(parameters.isSmartDetection && parameters.smartDetectionType === 'web')) ? (
@@ -21,6 +21,7 @@ export const CONVERSION_ENDPOINTS = {
'office-pdf': '/api/v1/convert/file/pdf',
'pdf-image': '/api/v1/convert/pdf/img',
'image-pdf': '/api/v1/convert/img/pdf',
'svg-pdf': '/api/v1/convert/svg/pdf',
'cbz-pdf': '/api/v1/convert/cbz/pdf',
'pdf-cbz': '/api/v1/convert/pdf/cbz',
'pdf-office-word': '/api/v1/convert/pdf/word',
@@ -46,6 +47,7 @@ export const ENDPOINT_NAMES = {
'office-pdf': 'file-to-pdf',
'pdf-image': 'pdf-to-img',
'image-pdf': 'img-to-pdf',
'svg-pdf': 'svg-to-pdf',
'cbz-pdf': 'cbz-to-pdf',
'pdf-cbz': 'pdf-to-cbz',
'pdf-office-word': 'pdf-to-word',
@@ -171,7 +173,8 @@ export const EXTENSION_TO_ENDPOINT: Record<string, Record<string, string>> = {
'xlsx': { 'pdf': 'file-to-pdf' }, 'xls': { 'pdf': 'file-to-pdf' }, 'ods': { 'pdf': 'file-to-pdf' },
'pptx': { 'pdf': 'file-to-pdf' }, 'ppt': { 'pdf': 'file-to-pdf' }, 'odp': { 'pdf': 'file-to-pdf' },
'jpg': { 'pdf': 'img-to-pdf' }, 'jpeg': { 'pdf': 'img-to-pdf' }, 'png': { 'pdf': 'img-to-pdf' },
'gif': { 'pdf': 'img-to-pdf' }, 'bmp': { 'pdf': 'img-to-pdf' }, 'tiff': { 'pdf': 'img-to-pdf' }, 'webp': { 'pdf': 'img-to-pdf' }, 'svg': { 'pdf': 'img-to-pdf' },
'gif': { 'pdf': 'img-to-pdf' }, 'bmp': { 'pdf': 'img-to-pdf' }, 'tiff': { 'pdf': 'img-to-pdf' }, 'webp': { 'pdf': 'img-to-pdf' },
'svg': { 'pdf': 'svg-to-pdf' },
'html': { 'pdf': 'html-to-pdf' },
'zip': { 'pdf': 'html-to-pdf' },
'md': { 'pdf': 'markdown-to-pdf' },
@@ -15,6 +15,8 @@ export const shouldProcessFilesSeparately = (
// Image to PDF with combineImages = false
((isImageFormat(parameters.fromExtension) || parameters.fromExtension === 'image') &&
parameters.toExtension === 'pdf' && !parameters.imageOptions.combineImages) ||
// SVG to PDF with combineIntoSinglePdf = false
(parameters.fromExtension === 'svg' && parameters.toExtension === 'pdf' && !parameters.imageOptions.combineImages) ||
// PDF to image conversions (each PDF should generate its own image file)
(parameters.fromExtension === 'pdf' && isImageFormat(parameters.toExtension)) ||
// PDF to PDF/A conversions (each PDF should be processed separately)
@@ -66,6 +68,8 @@ export const buildConvertFormData = (parameters: ConvertParameters, selectedFile
formData.append("fitOption", imageOptions.fitOption);
formData.append("colorType", imageOptions.colorType);
formData.append("autoRotate", imageOptions.autoRotate.toString());
} else if (fromExtension === 'svg' && toExtension === 'pdf') {
formData.append("combineIntoSinglePdf", imageOptions.combineImages.toString());
} else if ((fromExtension === 'html' || fromExtension === 'zip') && toExtension === 'pdf') {
formData.append("zoom", htmlOptions.zoomLevel.toString());
} else if ((fromExtension === 'eml' || fromExtension === 'msg') && toExtension === 'pdf') {
+12 -8
View File
@@ -1,4 +1,4 @@
import {
import {
CONVERSION_ENDPOINTS,
ENDPOINT_NAMES,
EXTENSION_TO_ENDPOINT,
@@ -11,15 +11,15 @@ import {
*/
export const getEndpointName = (fromExtension: string, toExtension: string): string => {
if (!fromExtension || !toExtension) return '';
let endpointKey = EXTENSION_TO_ENDPOINT[fromExtension]?.[toExtension];
// If no explicit mapping exists and we're converting to PDF,
// If no explicit mapping exists and we're converting to PDF,
// fall back to 'any' which uses file-to-pdf endpoint
if (!endpointKey && toExtension === 'pdf' && fromExtension !== 'any') {
endpointKey = EXTENSION_TO_ENDPOINT['any']?.[toExtension];
}
return endpointKey || '';
};
@@ -29,7 +29,7 @@ export const getEndpointName = (fromExtension: string, toExtension: string): str
export const getEndpointUrl = (fromExtension: string, toExtension: string): string => {
const endpointName = getEndpointName(fromExtension, toExtension);
if (!endpointName) return '';
// Find the endpoint URL from CONVERSION_ENDPOINTS using the endpoint name
for (const [key, endpoint] of Object.entries(CONVERSION_ENDPOINTS)) {
if (ENDPOINT_NAMES[key as keyof typeof ENDPOINT_NAMES] === endpointName) {
@@ -50,7 +50,11 @@ export const isConversionSupported = (fromExtension: string, toExtension: string
* Checks if the given extension is an image format
*/
export const isImageFormat = (extension: string): boolean => {
return ['png', 'jpg', 'jpeg', 'gif', 'tiff', 'bmp', 'webp', 'svg'].includes(extension.toLowerCase());
return ['png', 'jpg', 'jpeg', 'gif', 'tiff', 'bmp', 'webp'].includes(extension.toLowerCase());
};
export const isSvgFormat = (extension: string): boolean => {
return extension.toLowerCase() === 'svg';
};
/**
@@ -99,4 +103,4 @@ export const getAvailableToExtensions = (fromExtension: string): Array<{value: s
return TO_FORMAT_OPTIONS.filter(option =>
supportedExtensions.includes(option.value)
);
};
};
@@ -194,7 +194,6 @@ export async function flattenSignatures(options: SignatureFlatteningOptions): Pr
if (imageDataUrl && typeof imageDataUrl === 'string' && imageDataUrl.startsWith('data:image')) {
try {
// Convert data URL to bytes
const base64Data = imageDataUrl.split(',')[1];
const imageBytes = Uint8Array.from(atob(base64Data), c => c.charCodeAt(0));
@@ -206,6 +205,7 @@ export async function flattenSignatures(options: SignatureFlatteningOptions): Pr
} else if (imageDataUrl.includes('data:image/png')) {
image = await pdfDoc.embedPng(imageBytes);
} else {
// Default to PNG for other formats (including converted SVGs)
image = await pdfDoc.embedPng(imageBytes);
}