Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

feat(stamp): Add QR code stamp type (#8492)

EthanHealy01b556439ff8b9
diff --git a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/StampController.java b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/StampController.java
index 0cd485d7d1..86c9d39b2f 100644
--- a/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/StampController.java
+++ b/app/core/src/main/java/stirling/software/SPDF/controller/api/misc/StampController.java
@@ -7,10 +7,13 @@ import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
+import java.util.EnumMap;
import java.util.List;
import java.util.Locale;
+import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -39,6 +42,13 @@ import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.multipart.MultipartFile;
+import com.google.zxing.BarcodeFormat;
+import com.google.zxing.EncodeHintType;
+import com.google.zxing.WriterException;
+import com.google.zxing.common.BitMatrix;
+import com.google.zxing.qrcode.QRCodeWriter;
+import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
+
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
@@ -71,6 +81,10 @@ public class StampController {
private static final Pattern CUSTOM_DATE_PATTERN = Pattern.compile("@date\\{([^}]{1,50})\\}");
// Placeholder for escaped @ symbol (using Unicode private use area)
private static final String ESCAPED_AT_PLACEHOLDER = "\uE000ESCAPED_AT\uE000";
+ // Counted in UTF-8 bytes, the unit QR byte mode is limited by. Must stay in sync with
+ // MAX_QR_CONTENT_BYTES in the frontend's useAddStampParameters.ts.
+ private static final int MAX_QR_CONTENT_BYTES = 1000;
+ private static final int QR_QUIET_ZONE_MODULES = 4;
/**
* Initialize data binder for multipart file uploads. This method registers a custom editor for
@@ -98,7 +112,7 @@ public class StampController {
summary = "Add stamp to a PDF file",
description =
"This endpoint adds a stamp to a given PDF file. Users can specify the stamp"
- + " type (text or image), rotation, opacity, width spacer, and height spacer.")
+ + " type (text, image or qr), rotation, opacity, width spacer, and height spacer.")
public ResponseEntity<Resource> addStamp(@ModelAttribute AddStampRequest request)
throws IOException, Exception {
MultipartFile pdfFile = request.getFileInput();
@@ -127,6 +141,8 @@ public class StampController {
"stamp image file path",
stampImageName);
}
+ } else if ("qr".equalsIgnoreCase(stampType)) {
+ requireEncodableQrContent(stampText);
}
String alphabet = request.getAlphabet();
float fontSize = request.getFontSize();
@@ -158,6 +174,21 @@ public class StampController {
PDRectangle pageSize = page.getMediaBox();
float margin = marginFactor * (pageSize.getWidth() + pageSize.getHeight()) / 2;
+ // Encoded before the content stream opens so a rejected expansion cannot
+ // leave a half-written stream on the page.
+ BitMatrix qrMatrix = null;
+ if ("qr".equalsIgnoreCase(stampType)) {
+ String qrContent =
+ processStampText(
+ stampText,
+ pageIndex,
+ document.getNumberOfPages(),
+ pdfFileName,
+ document);
+ requireEncodableQrContent(qrContent);
+ qrMatrix = encodeQrCode(qrContent);
+ }
+
PDPageContentStream contentStream =
new PDPageContentStream(
document,
@@ -198,6 +229,17 @@ public class StampController {
overrideX,
overrideY,
margin);
+ } else if (qrMatrix != null) {
+ addQrStamp(
+ contentStream,
+ qrMatrix,
+ page,
+ rotation,
+ position,
+ fontSize,
+ overrideX,
+ overrideY,
+ margin);
}
contentStream.close();
@@ -482,6 +524,122 @@ public class StampController {
// Convert the BufferedImage to PDImageXObject
PDImageXObject xobject = LosslessFactory.createFromImage(document, image);
+ enterStampBox(
+ contentStream,
+ page,
+ rotation,
+ position,
+ desiredPhysicalWidth,
+ desiredPhysicalHeight,
+ overrideX,
+ overrideY,
+ margin);
+ contentStream.drawImage(xobject, 0, 0, desiredPhysicalWidth, desiredPhysicalHeight);
+ contentStream.restoreGraphicsState();
+ }
+
+ /**
+ * Rejects QR content that is blank or over the byte limit. Applied to the raw text and again to
+ * each page's expansion, since a placeholder can resolve to nothing (@author with no metadata)
+ * or grow the text past the limit (@filename).
+ */
+ private static void requireEncodableQrContent(String content) {
+ if (content == null || content.isBlank()) {
+ throw ExceptionUtils.createIllegalArgumentException(
+ "error.stamp.qr.required",
+ "Stamp text must be provided when stamp type is 'qr'");
+ }
+ if (content.getBytes(StandardCharsets.UTF_8).length > MAX_QR_CONTENT_BYTES) {
+ throw ExceptionUtils.createIllegalArgumentException(
+ "error.stamp.qr.tooLong",
+ "QR code content must be at most {0} bytes of UTF-8 text",
+ MAX_QR_CONTENT_BYTES);
+ }
+ }
+
+ private BitMatrix encodeQrCode(String content) {
+ Map<EncodeHintType, Object> hints = new EnumMap<>(EncodeHintType.class);
+ hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
+ hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
+ hints.put(EncodeHintType.MARGIN, QR_QUIET_ZONE_MODULES);
+ try {
+ return new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, 0, 0, hints);
+ } catch (WriterException e) {
+ throw ExceptionUtils.createIllegalArgumentException(
+ "error.stamp.qr.tooLong", "QR code content is too long to encode");
+ }
+ }
+
+ /**
+ * Draws the QR code as filled vector modules on a white square of {@code size} points, so it
+ * stays sharp at any zoom.
+ */
+ private void addQrStamp(
+ PDPageContentStream contentStream,
+ BitMatrix matrix,
+ PDPage page,
+ float rotation,
+ int position,
+ float size,
+ float overrideX,
+ float overrideY,
+ float margin)
+ throws IOException {
+ // Fall back the same way text stamps do when no usable size is given.
+ float effectiveSize = size > 0 ? size : 40f;
+ enterStampBox(
+ contentStream,
+ page,
+ rotation,
+ position,
+ effectiveSize,
+ effectiveSize,
+ overrideX,
+ overrideY,
+ margin);
+ contentStream.setNonStrokingColor(Color.WHITE);
+ contentStream.addRect(0, 0, effectiveSize, effectiveSize);
+ contentStream.fill();
+
+ int modules = matrix.getWidth();
+ float moduleSize = effectiveSize / modules;
+ contentStream.setNonStrokingColor(Color.BLACK);
+ for (int row = 0; row < modules; row++) {
+ float y = effectiveSize - (row + 1) * moduleSize;
+ int col = 0;
+ while (col < modules) {
+ if (!matrix.get(col, row)) {
+ col++;
+ continue;
+ }
+ int runStart = col;
+ while (col < modules && matrix.get(col, row)) {
+ col++;
+ }
+ contentStream.addRect(
+ runStart * moduleSize, y, (col - runStart) * moduleSize, moduleSize);
+ }
+ }
+ contentStream.fill();
+ contentStream.restoreGraphicsState();
+ }
+
+ /**
+ * Saves the graphics state and maps the box (0,0)-(width,height) onto the stamp's placement on
+ * the page, rotated about its lower-left corner. The caller draws inside that box and must then
+ * call {@code restoreGraphicsState()}.
+ */
+ private void enterStampBox(
+ PDPageContentStream contentStream,
+ PDPage page,
+ float rotation,
+ int position,
+ float desiredPhysicalWidth,
+ float desiredPhysicalHeight,
+ float overrideX,
+ float overrideY,
+ float margin)
+ throws IOException {
PDRectangle pageSize = page.getMediaBox();
float x, y;
@@ -507,8 +665,6 @@ public class StampController {
contentStream.saveGraphicsState();
contentStream.transform(Matrix.getTranslateInstance(x, y));
contentStream.transform(Matrix.getRotateInstance(Math.toRadians(rotation), 0, 0));
- contentStream.drawImage(xobject, 0, 0, desiredPhysicalWidth, desiredPhysicalHeight);
- contentStream.restoreGraphicsState();
}
private float calculatePositionX(
diff --git a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/AddStampRequest.java b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/AddStampRequest.java
index 25a5f9e645..14cefaeefd 100644
--- a/app/core/src/main/java/stirling/software/SPDF/model/api/misc/AddStampRequest.java
+++ b/app/core/src/main/java/stirling/software/SPDF/model/api/misc/AddStampRequest.java
@@ -14,12 +14,14 @@ import stirling.software.SPDF.model.api.PDFWithPageNums;
public class AddStampRequest extends PDFWithPageNums {
@Schema(
- description = "The stamp type (text or image)",
- allowableValues = {"text", "image"},
+ description = "The stamp type (text, image or qr)",
+ allowableValues = {"text", "image", "qr"},
requiredMode = Schema.RequiredMode.REQUIRED)
private String stampType;
- @Schema(description = "The stamp text", defaultValue = "Stirling Software")
+ @Schema(
+ description = "The stamp text, or the QR code content when the stamp type is qr",
+ defaultValue = "Stirling Software")
private String stampText;
@Schema(description = "The stamp image")
diff --git a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/StampControllerMoreTest.java b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/StampControllerMoreTest.java
index 359b6506f1..c8313830c8 100644
--- a/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/StampControllerMoreTest.java
+++ b/app/core/src/test/java/stirling/software/SPDF/controller/api/misc/StampControllerMoreTest.java
@@ -18,6 +18,7 @@ import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
+import org.apache.pdfbox.rendering.PDFRenderer;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
@@ -32,6 +33,11 @@ import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
+import com.google.zxing.BinaryBitmap;
+import com.google.zxing.RGBLuminanceSource;
+import com.google.zxing.common.HybridBinarizer;
+import com.google.zxing.qrcode.QRCodeReader;
+
import stirling.software.SPDF.model.api.misc.AddStampRequest;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.service.CustomPDFDocumentFactory;
@@ -320,6 +326,132 @@ class StampControllerMoreTest {
}
}
+ @Nested
+ @DisplayName("QR code stamp")
+ class QrStamp {
+
+ private String stampAndDecodeQr(AddStampRequest req) throws Exception {
+ BufferedImage rendered;
+ try (InputStream is = stampController.addStamp(req).getBody().getInputStream();
+ PDDocument result = Loader.loadPDF(is.readAllBytes())) {
+ rendered = new PDFRenderer(result).renderImageWithDPI(0, 144);
+ }
+ int width = rendered.getWidth();
+ int height = rendered.getHeight();
+ int[] pixels = rendered.getRGB(0, 0, width, height, null, 0, width);
+ BinaryBitmap bitmap =
+ new BinaryBitmap(
+ new HybridBinarizer(new RGBLuminanceSource(width, height, pixels)));
+ return new QRCodeReader().decode(bitmap).getText();
+ }
+
+ @Test
+ @DisplayName("multi-byte content survives the UTF-8 round trip")
+ void qrStampEncodesUtf8() throws Exception {
+ AddStampRequest req = baseRequest(pdfFile(1));
+ req.setStampType("qr");
+ req.setStampText("日本語 café ✓");
+ req.setFontSize(200f);
+ req.setOpacity(1f);
+ assertThat(stampAndDecodeQr(req)).isEqualTo("日本語 café ✓");
+ }
+
+ @Test
+ @DisplayName("a rotated QR code still decodes")
+ void rotatedQrStampDecodes() throws Exception {
+ AddStampRequest req = baseRequest(pdfFile(1));
+ req.setStampType("qr");
+ req.setStampText("https://stirlingpdf.com/@filename");
+ req.setFontSize(200f);
+ req.setRotation(90f);
+ req.setOpacity(1f);
+ assertThat(stampAndDecodeQr(req)).isEqualTo("https://stirlingpdf.com/input");
+ }
+
+ @Test
+ @DisplayName("QR content whose placeholders resolve to nothing is rejected")
+ void rejectsContentExpandingToBlank() throws Exception {
+ AddStampRequest req = baseRequest(pdfFile(1));
+ req.setStampType("qr");
+ req.setStampText("@author");
+ assertThatThrownBy(() -> stampController.addStamp(req))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("must be provided");
+ }
+
+ @Test
+ @DisplayName("draws a QR code that decodes back to the resolved stamp text")
+ void qrStampDecodesToContent() throws Exception {
+ AddStampRequest req = baseRequest(pdfFile(1));
+ req.setStampType("qr");
+ req.setStampText("https://stirlingpdf.com/@filename");
+ req.setFontSize(200f);
+ req.setOpacity(1f);
+
+ assertThat(stampAndDecodeQr(req)).isEqualTo("https://stirlingpdf.com/input");
+ }
+
+ @Test
+ @DisplayName("blank QR content is rejected")
+ void rejectsBlankContent() throws Exception {
+ AddStampRequest req = baseRequest(pdfFile(1));
+ req.setStampType("qr");
+ req.setStampText(" ");
+ assertThatThrownBy(() -> stampController.addStamp(req))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ @DisplayName("QR content over the length limit is rejected")
+ void rejectsOverlongContent() throws Exception {
+ AddStampRequest req = baseRequest(pdfFile(1));
+ req.setStampType("qr");
+ req.setStampText("a".repeat(1001));
+ assertThatThrownBy(() -> stampController.addStamp(req))
+ .isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ @DisplayName("QR content is limited by UTF-8 bytes, not characters")
+ void rejectsMultiByteContentOverByteLimit() throws Exception {
+ AddStampRequest req = baseRequest(pdfFile(1));
+ req.setStampType("qr");
+ req.setStampText("日".repeat(334)); // 1002 bytes in 334 characters
+ assertThatThrownBy(() -> stampController.addStamp(req))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("bytes");
+ }
+
+ @Test
+ @DisplayName("a non-positive QR size falls back to the default size")
+ void qrStampZeroFontSizeFallsBackToDefaultSize() throws Exception {
+ AddStampRequest req = baseRequest(pdfFile(1));
+ req.setStampType("qr");
+ req.setStampText("https://stirlingpdf.com/@filename");
+ req.setFontSize(0f);
+ req.setOpacity(1f);
+
+ assertThat(stampAndDecodeQr(req)).isEqualTo("https://stirlingpdf.com/input");
+ }
+
+ @Test
+ @DisplayName("QR content expanded past the byte limit by placeholders is rejected")
+ void rejectsExpandedContentOverByteLimit() throws Exception {
+ MockMultipartFile longName =
+ new MockMultipartFile(
+ "fileInput",
+ "a".repeat(200) + ".pdf",
+ MediaType.APPLICATION_PDF_VALUE,
+ buildPdf(1));
+ AddStampRequest req = baseRequest(longName);
+ req.setStampType("qr");
+ req.setStampText("@filename@filename@filename@filename@filename@filename");
+ assertThatThrownBy(() -> stampController.addStamp(req))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("bytes");
+ }
+ }
+
@Nested
@DisplayName("Validation and error branches")
class Validation {
diff --git a/engine/src/stirling/models/tool_models.py b/engine/src/stirling/models/tool_models.py
index a251c552b7..62225cc78d 100644
--- a/engine/src/stirling/models/tool_models.py
+++ b/engine/src/stirling/models/tool_models.py
@@ -193,16 +193,17 @@ class Position1(IntEnum):
class StampType(StrEnum):
"""
- The stamp type (text or image)
+ The stamp type (text, image or qr)
"""
text = "text"
image = "image"
+ qr = "qr"
class AddStampParams(ApiModel):
"""
- This endpoint adds a stamp to a given PDF file. Users can specify the stamp type (text or image), rotation, opacity, width spacer, and height spacer. Input:PDF Output:PDF Type:SISO
+ This endpoint adds a stamp to a given PDF file. Users can specify the stamp type (text, image or qr), rotation, opacity, width spacer, and height spacer. Input:PDF Output:PDF Type:SISO
"""
alphabet: Alphabet = Field(Alphabet.roman, description="The selected alphabet of the stamp text")
@@ -227,8 +228,10 @@ class AddStampParams(ApiModel):
description="Position for stamp placement based on a 1-9 grid (1: bottom-left, 2: bottom-center, 3: bottom-right, 4: middle-left, 5: middle-center, 6: middle-right, 7: top-left, 8: top-center, 9: top-right)",
)
rotation: float = Field(0, description="The rotation of the stamp in degrees")
- stamp_text: str = Field("Stirling Software", description="The stamp text")
- stamp_type: StampType = Field(..., description="The stamp type (text or image)")
+ stamp_text: str = Field(
+ "Stirling Software", description="The stamp text, or the QR code content when the stamp type is qr"
+ )
+ stamp_type: StampType = Field(..., description="The stamp type (text, image or qr)")
class Alphabet1(StrEnum):
diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.toml
index be5f3251af..9faae849ce 100644
--- a/frontend/public/locales/en-US/translation.toml
+++ b/frontend/public/locales/en-US/translation.toml
@@ -370,6 +370,11 @@ pageVars = "Page Information"
position = "Position"
positionAndFormatting = "Position & Formatting"
preview = "Preview:"
+qrCode = "QR Code"
+qrCodeSize = "QR Code Size"
+qrContent = "QR Code Content"
+qrContentDescription = "Text or link to encode. Dynamic variables such as @filename and @page_number are supported."
+qrContentTooLong = "Too long to fit in a QR code. Shorten the content."
quickPosition = "Select a position on the page to place the stamp."
rotation = "Rotation"
selectedImageAlt = "Selected stamp image"
diff --git a/frontend/src/editor/core/components/tools/addStamp/StampPositionFormattingSettings.tsx b/frontend/src/editor/core/components/tools/addStamp/StampPositionFormattingSettings.tsx
index 4d4e30e34e..c968cd36a6 100644
--- a/frontend/src/editor/core/components/tools/addStamp/StampPositionFormattingSettings.tsx
+++ b/frontend/src/editor/core/components/tools/addStamp/StampPositionFormattingSettings.tsx
@@ -34,6 +34,13 @@ const StampPositionFormattingSettings = ({
}: StampPositionFormattingSettingsProps) => {
const { t } = useTranslation();
+ const sizeLabel =
+ parameters.stampType === "qr"
+ ? t("AddStampRequest.qrCodeSize", "QR Code Size")
+ : parameters.stampType !== "text"
+ ? t("AddStampRequest.imageSize", "Image Size")
+ : t("AddStampRequest.fontSize", "Font Size");
+
return (
<Stack gap="md" justify="space-between">
{/* Position Grid - shown in automation settings */}
@@ -108,20 +115,9 @@ const StampPositionFormattingSettings = ({
<Icon name="droplet" size="1.1rem" />
</ActionIcon>
</Tooltip>
- <Tooltip
- content={
- parameters.stampType === "image"
- ? t("AddStampRequest.imageSize", "Image Size")
- : t("AddStampRequest.fontSize", "Font Size")
- }
- position="top"
- >
+ <Tooltip content={sizeLabel} position="top">
<ActionIcon
- aria-label={
- parameters.stampType === "image"
- ? t("AddStampRequest.imageSize", "Image Size")
- : t("AddStampRequest.fontSize", "Font Size")
- }
+ aria-label={sizeLabel}
variant={
parameters._activePill === "fontSize" ? "primary" : "secondary"
}
@@ -136,11 +132,7 @@ const StampPositionFormattingSettings = ({
{/* Single slider bound to selected pill */}
{parameters._activePill === "fontSize" && (
<Stack gap="xs">
- <Text className={styles.labelText}>
- {parameters.stampType === "image"
- ? t("AddStampRequest.imageSize", "Image Size")
- : t("AddStampRequest.fontSize", "Font Size")}
- </Text>
+ <Text className={styles.labelText}>{sizeLabel}</Text>
<Group className={styles.sliderGroup} align="center">
<NumberInput
value={parameters.fontSize}
@@ -229,7 +221,7 @@ const StampPositionFormattingSettings = ({
</Stack>
)}
- {parameters.stampType !== "image" && (
+ {parameters.stampType === "text" && (
<ColorInput
label={t("AddStampRequest.customColor", "Custom Text Color")}
value={parameters.customColor}
diff --git a/frontend/src/editor/core/components/tools/addStamp/StampPreview.module.css b/frontend/src/editor/core/components/tools/addStamp/StampPreview.module.css
index 5a558656ed..53a4060881 100644
--- a/frontend/src/editor/core/components/tools/addStamp/StampPreview.module.css
+++ b/frontend/src/editor/core/components/tools/addStamp/StampPreview.module.css
@@ -50,6 +50,18 @@
pointer-events: none;
}
+/* QR over-limit notice: centered message replacing the unrenderable code */
+.qrOverLimitNotice {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 16px;
+ text-align: center;
+ pointer-events: none;
+}
+
/* Text stamp styles */
.textLine {
white-space: pre;
diff --git a/frontend/src/editor/core/components/tools/addStamp/StampPreview.tsx b/frontend/src/editor/core/components/tools/addStamp/StampPreview.tsx
index a5df74f77b..3e1d0a72f5 100644
--- a/frontend/src/editor/core/components/tools/addStamp/StampPreview.tsx
+++ b/frontend/src/editor/core/components/tools/addStamp/StampPreview.tsx
@@ -1,5 +1,10 @@
import React, { useEffect, useMemo, useRef, useState } from "react";
-import { AddStampParameters } from "@editor/components/tools/addStamp/useAddStampParameters";
+import { QRCodeSVG } from "qrcode.react";
+import { Text } from "@mantine/core";
+import {
+ AddStampParameters,
+ isQrContentWithinLimit,
+} from "@editor/components/tools/addStamp/useAddStampParameters";
import { pdfWorkerManager } from "@editor/services/pdfWorkerManager";
import { useThumbnailGeneration } from "@editor/hooks/useThumbnailGeneration";
import {
@@ -427,6 +432,43 @@ export default function StampPreview({
</div>
)}
+ {parameters.stampType === "qr" &&
+ isQrContentWithinLimit(parameters.stampText) && (
+ <div
+ className={`${styles.stampItem} ${showQuickGrid ? styles.stampItemGridMode : styles.stampItemDraggable}`}
+ style={style.item}
+ onPointerDown={(e) => handlePointerDown(e, "move")}
+ data-user-content-preview=""
+ >
+ <QRCodeSVG
+ value={parameters.stampText}
+ level="M"
+ marginSize={4}
+ className={styles.stampImage}
+ title={t("AddStampRequest.qrCode", "QR Code")}
+ />
+ {itemHandles}
+ </div>
+ )}
+
+ {/* Over-limit QR content renders no code, so say why instead of
+ leaving an empty preview; the setup-step error is collapsed away */}
+ {parameters.stampType === "qr" &&
+ parameters.stampText.trim().length > 0 &&
+ !isQrContentWithinLimit(parameters.stampText) && (
+ <div
+ className={styles.qrOverLimitNotice}
+ data-qr-over-limit-notice=""
+ >
+ <Text c="var(--c-danger)" size="sm" ta="center">
+ {t(
+ "AddStampRequest.qrContentTooLong",
+ "Too long to fit in a QR code. Shorten the content.",
+ )}
+ </Text>
+ </div>
+ )}
+
{/* Quick position overlay grid */}
{showQuickGrid && (
<div className={styles.quickGrid}>
diff --git a/frontend/src/editor/core/components/tools/addStamp/StampPreviewUtils.ts b/frontend/src/editor/core/components/tools/addStamp/StampPreviewUtils.ts
index 92ae1c1d6c..c18e5ede1c 100644
--- a/frontend/src/editor/core/components/tools/addStamp/StampPreviewUtils.ts
+++ b/frontend/src/editor/core/components/tools/addStamp/StampPreviewUtils.ts
@@ -150,7 +150,7 @@ export function computeStampPreviewStyle(
// Compute content dimensions
const heightPtsContent =
- parameters.stampType === "image"
+ parameters.stampType !== "text"
? parameters.fontSize
: parameters.fontSize * getAlphabetPreviewScale(parameters.alphabet);
let widthPtsContent = heightPtsContent;
@@ -294,7 +294,7 @@ export function computeStampPreviewStyle(
opacity: displayOpacity,
transform: `rotate(${-parameters.rotation}deg)`,
transformOrigin:
- parameters.stampType === "image" ? "left bottom" : "center center",
+ parameters.stampType !== "text" ? "left bottom" : "center center",
color: parameters.customColor,
display: "flex",
flexDirection: "column",
diff --git a/frontend/src/editor/core/components/tools/addStamp/StampSetupSettings.tsx b/frontend/src/editor/core/components/tools/addStamp/StampSetupSettings.tsx
index 4cbae29173..364569901a 100644
--- a/frontend/src/editor/core/components/tools/addStamp/StampSetupSettings.tsx
+++ b/frontend/src/editor/core/components/tools/addStamp/StampSetupSettings.tsx
@@ -15,7 +15,11 @@ import {
Paper,
} from "@mantine/core";
import { Button } from "@editor/ui/Button";
-import { AddStampParameters } from "@editor/components/tools/addStamp/useAddStampParameters";
+import {
+ AddStampParameters,
+ DEFAULT_QR_SIZE,
+ isQrContentWithinLimit,
+} from "@editor/components/tools/addStamp/useAddStampParameters";
import ButtonSelector from "@editor/components/shared/ButtonSelector";
import styles from "@editor/components/tools/addStamp/StampPreview.module.css";
import { getDefaultFontSizeForAlphabet } from "@editor/components/tools/addStamp/StampPreviewUtils";
@@ -235,10 +239,16 @@ const StampSetupSettings = ({
</Text>
<ButtonSelector
value={parameters.stampType}
- onChange={(v: "text" | "image") => onParameterChange("stampType", v)}
+ onChange={(v: "text" | "image" | "qr") => {
+ onParameterChange("stampType", v);
+ if (v === "qr" && parameters.fontSize < DEFAULT_QR_SIZE) {
+ onParameterChange("fontSize", DEFAULT_QR_SIZE);
+ }
+ }}
options={[
{ value: "text", label: t("watermark.type.1", "Text") },
{ value: "image", label: t("watermark.type.2", "Image") },
+ { value: "qr", label: t("AddStampRequest.qrCode", "QR Code") },
]}
disabled={disabled}
textClassName={styles.modeToggleButtonText}
@@ -663,6 +673,31 @@ const StampSetupSettings = ({
</>
)}
+ {parameters.stampType === "qr" && (
+ <Textarea
+ label={t("AddStampRequest.qrContent", "QR Code Content")}
+ description={t(
+ "AddStampRequest.qrContentDescription",
+ "Text or link to encode. Dynamic variables such as @filename and @page_number are supported.",
+ )}
+ value={parameters.stampText}
+ onChange={(e) =>
+ onParameterChange("stampText", e.currentTarget.value)
+ }
+ error={
+ isQrContentWithinLimit(parameters.stampText)
+ ? undefined
+ : t(
+ "AddStampRequest.qrContentTooLong",
+ "Too long to fit in a QR code. Shorten the content.",
+ )
+ }
+ autosize
+ minRows={2}
+ disabled={disabled}
+ />
+ )}
+
{parameters.stampType === "image" && (
<Stack gap="xs">
<input
diff --git a/frontend/src/editor/core/components/tools/addStamp/useAddStampOperation.ts b/frontend/src/editor/core/components/tools/addStamp/useAddStampOperation.ts
index 646b7121ba..ea30998afb 100644
--- a/frontend/src/editor/core/components/tools/addStamp/useAddStampOperation.ts
+++ b/frontend/src/editor/core/components/tools/addStamp/useAddStampOperation.ts
@@ -41,7 +41,7 @@ export const addStampToApiParams = (
alphabet: parameters.alphabet,
};
- if (stampType === "text") {
+ if (stampType !== "image") {
apiParams.stampText = parameters.stampText;
}
diff --git a/frontend/src/editor/core/components/tools/addStamp/useAddStampParameters.test.ts b/frontend/src/editor/core/components/tools/addStamp/useAddStampParameters.test.ts
new file mode 100644
index 0000000000..63a35a3421
--- /dev/null
+++ b/frontend/src/editor/core/components/tools/addStamp/useAddStampParameters.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from "vitest";
+import {
+ MAX_QR_CONTENT_BYTES,
+ defaultParameters,
+ isQrContentWithinLimit,
+ validateAddStampParameters,
+} from "@editor/components/tools/addStamp/useAddStampParameters";
+import { addStampToApiParams } from "@editor/components/tools/addStamp/useAddStampOperation";
+
+const qrParams = (stampText: string) => ({
+ ...defaultParameters,
+ stampType: "qr" as const,
+ stampText,
+});
+
+describe("QR stamp parameters", () => {
+ it("rejects blank content", () => {
+ expect(validateAddStampParameters(qrParams(" "))).toBe(false);
+ });
+
+ it("accepts content up to the byte limit", () => {
+ expect(
+ validateAddStampParameters(qrParams("a".repeat(MAX_QR_CONTENT_BYTES))),
+ ).toBe(true);
+ });
+
+ it("limits multi-byte content by UTF-8 bytes, not characters", () => {
+ const threeByteChars = "日".repeat(Math.ceil(MAX_QR_CONTENT_BYTES / 3) + 1);
+ expect(threeByteChars.length).toBeLessThan(MAX_QR_CONTENT_BYTES);
+ expect(isQrContentWithinLimit(threeByteChars)).toBe(false);
+ expect(validateAddStampParameters(qrParams(threeByteChars))).toBe(false);
+ });
+
+ it("sends the content as stampText", () => {
+ const apiParams = addStampToApiParams(qrParams("https://example.com"));
+ expect(apiParams.stampType).toBe("qr");
+ expect(apiParams.stampText).toBe("https://example.com");
+ });
+});
diff --git a/frontend/src/editor/core/components/tools/addStamp/useAddStampParameters.ts b/frontend/src/editor/core/components/tools/addStamp/useAddStampParameters.ts
index 10d2757900..f6794f1e8d 100644
--- a/frontend/src/editor/core/components/tools/addStamp/useAddStampParameters.ts
+++ b/frontend/src/editor/core/components/tools/addStamp/useAddStampParameters.ts
@@ -5,7 +5,7 @@ import {
} from "@editor/hooks/tools/shared/useBaseParameters";
export interface AddStampParameters extends BaseParameters {
- stampType?: "text" | "image";
+ stampType?: "text" | "image" | "qr";
stampText: string;
stampImage?: File;
alphabet: "roman" | "arabic" | "japanese" | "korean" | "chinese" | "thai";
@@ -21,6 +21,20 @@ export interface AddStampParameters extends BaseParameters {
_activePill: "fontSize" | "rotation" | "opacity";
}
+/**
+ * Must stay in sync with StampController.MAX_QR_CONTENT_BYTES, and below the 2331 bytes a
+ * level-M QR code holds: the preview's QRCodeSVG throws during render past that.
+ */
+export const MAX_QR_CONTENT_BYTES = 1000;
+
+/** Size in points to switch to for QR stamps: text-sized codes are too dense to scan. */
+export const DEFAULT_QR_SIZE = 120;
+
+const utf8Encoder = new TextEncoder();
+
+export const isQrContentWithinLimit = (content: string): boolean =>
+ utf8Encoder.encode(content).length <= MAX_QR_CONTENT_BYTES;
+
export const defaultParameters: AddStampParameters = {
stampType: "text",
stampText: "",
@@ -46,6 +60,12 @@ export function validateAddStampParameters(
if (params.stampType === "text") {
return params.stampText.trim().length > 0;
}
+ if (params.stampType === "qr") {
+ return (
+ params.stampText.trim().length > 0 &&
+ isQrContentWithinLimit(params.stampText)
+ );
+ }
return params.stampImage !== undefined;
}
diff --git a/frontend/src/editor/core/tools/AddStamp.tsx b/frontend/src/editor/core/tools/AddStamp.tsx
index 47c1b667fb..2f52a1b5ff 100644
--- a/frontend/src/editor/core/tools/AddStamp.tsx
+++ b/frontend/src/editor/core/tools/AddStamp.tsx
@@ -109,8 +109,7 @@ const AddStamp = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {
isVisible: hasFiles || hasResults,
content: (
<Stack gap="md" justify="space-between">
- {/* Mode toggle: Quick grid vs Custom drag - only show for image stamps */}
- {params.parameters.stampType === "image" && (
+ {params.parameters.stampType !== "text" && (
<ButtonSelector
value={quickPositionModeSelected ? "quick" : "custom"}
onChange={(v: "quick" | "custom") => {
@@ -130,7 +129,7 @@ const AddStamp = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {
/>
)}
- {params.parameters.stampType === "image" &&
+ {params.parameters.stampType !== "text" &&
customPositionModeSelected && (
<div className={styles.informationContainer}>
<Text className={styles.informationText}>
@@ -141,7 +140,7 @@ const AddStamp = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {
</Text>
</div>
)}
- {params.parameters.stampType === "image" &&
+ {params.parameters.stampType !== "text" &&
!customPositionModeSelected && (
<div className={styles.informationContainer}>
<Text className={styles.informationText}>
@@ -163,7 +162,7 @@ const AddStamp = ({ onPreviewFile, onComplete, onError }: BaseToolProps) => {
<ObscuredOverlay
obscured={
accordion.currentStep === AddStampStep.POSITION_FORMATTING &&
- ((params.parameters.stampType === "text" &&
+ ((params.parameters.stampType !== "image" &&
params.parameters.stampText.trim().length === 0) ||
(params.parameters.stampType === "image" &&
!params.parameters.stampImage))
diff --git a/frontend/src/editor/core/types/toolApiTypes.ts b/frontend/src/editor/core/types/toolApiTypes.ts
index a9a03c79b6..9a2081959b 100644
--- a/frontend/src/editor/core/types/toolApiTypes.ts
+++ b/frontend/src/editor/core/types/toolApiTypes.ts
@@ -164,13 +164,13 @@ export interface AddStampRequest {
rotation?: number;
stampImage?: File;
/**
- * The stamp text
+ * The stamp text, or the QR code content when the stamp type is qr
*/
stampText?: string;
/**
- * The stamp type (text or image)
+ * The stamp type (text, image or qr)
*/
- stampType: "text" | "image";
+ stampType: "text" | "image" | "qr";
}
export interface AddWatermarkRequest {
/**