An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Improve PDF rectangle annotation image quality https://github.com/siyuan-note/siyuan/issues/16665
Daniel47c4b04d10cc
diff --git a/app/src/asset/anno.ts b/app/src/asset/anno.tsindex b50a649bed..9ec0cf1b15 100644--- a/app/src/asset/anno.ts+++ b/app/src/asset/anno.ts@@ -14,6 +14,14 @@ import {filesize} from "filesize";import md5 from "blueimp-md5";import {getRectImageName, hideRectResizeHandles, moveRectBounds, resizeRectBounds} from "./rectAnnotationResize";import type {RectBounds, RectResizeDirection} from "./rectAnnotationResize";+import {+ getCaptureCanvasBounds,+ getCaptureDisplayWidth,+ getLimitedCaptureScale,+ PDF_RECT_CAPTURE_PROFILE,+ PDF_RECT_CAPTURE_SCALE,+ PDF_RECT_DISPLAY_SCALE,+} from "./pdfRectCapture";const RECT_RESIZE_MIN_SIZE = 8;@@ -912,29 +920,33 @@ const copyAnno = (idPath: string, fileName: string, pdf: any) => {const annotation = getConfig(pdf)?.[annotationElement.getAttribute("data-node-id")] as IPdfAnno;const positions = annotation?.pages?.find(item => item.index === pageIndex)?.positions;const positionHash = positions ? md5(JSON.stringify(positions)).substring(0, 7) : "";+ const position = positions?.[0];setTimeout(() => {if (mode === "rect" ||(mode === "" && annotationElement.childElementCount === 1 && content.startsWith(fileName)) // 兼容历史,以前没有 mode) {- getRectImgData(pdf, annotationElement).then((imageData) => {- fetch(imageData.url).then((response) => {- return response.blob();- }).then((blob) => {- let msg = "";- if (Constants.SIZE_UPLOAD_TIP_SIZE <= blob.size) {- msg = window.siyuan.languages.uploadFileTooLarge.replace("${x}", content + ".png").replace("${y}", filesize(blob.size, {standard: "iec"}));- }- confirmDialog(msg ? window.siyuan.languages.upload : "", msg, () => {- const formData = new FormData();- const imageName = getRectImageName(content, imageData.rotation, positionHash);- formData.append("file[]", blob, imageName);- formData.append("skipIfDuplicated", "true");- fetchPost(Constants.UPLOAD_ADDRESS, formData, (response) => {- writeText(`<<${idPath} "${content}">>-`);- });+ if (!position || pageIndex < 0) {+ return;+ }+ getRectImgData(pdf, pageIndex + 1, position).then((imageData) => {+ let msg = "";+ if (Constants.SIZE_UPLOAD_TIP_SIZE <= imageData.blob.size) {+ msg = window.siyuan.languages.uploadFileTooLarge.replace("${x}", content + ".png")+ .replace("${y}", filesize(imageData.blob.size, {standard: "iec"}));+ }+ confirmDialog(msg ? window.siyuan.languages.upload : "", msg, () => {+ const formData = new FormData();+ const imageName = getRectImageName(content, imageData.rotation, positionHash,+ PDF_RECT_CAPTURE_PROFILE);+ formData.append("file[]", imageData.blob, imageName);+ formData.append("skipIfDuplicated", "true");+ fetchPost(Constants.UPLOAD_ADDRESS, formData, (response) => {+ writeText(`<<${idPath} "${content}">>+{: style="width: ${imageData.displayWidth}px;"}`);});});+ }).catch((error) => {+ console.error(error);});} else {writeText(`<<${idPath} "${content}">>`);@@ -942,69 +954,60 @@ const copyAnno = (idPath: string, fileName: string, pdf: any) => {}, Constants.TIMEOUT_DBLCLICK);};-async function getRectImgData(pdfObj: any, annotationElement: HTMLElement) {- const pageElement = hasClosestByClassName(annotationElement, "page");- if (!pageElement) {- return;- }-- const pageNumber = parseInt(pageElement.getAttribute("data-page-number"));+async function getRectImgData(pdfObj: any, pageNumber: number, position: number[]) {const pageView = pdfObj.pdfViewer.getPageView(pageNumber - 1);if (!pageView) {- return;+ throw new Error(`PDF page view ${pageNumber} is unavailable`);}- // PDF 截图时的缩放倍数,用于提高截图清晰度- const CAPTURE_SCALE_RATIO = 1.5;-const pdfPage = await pdfObj.pdfDocument.getPage(pageNumber);+ const totalRotation = ((pageView.rotation + pageView.pdfPageRotate) % 360 + 360) % 360;+ const targetViewport = pdfPage.getViewport({+ scale: PDF_RECT_CAPTURE_SCALE,+ rotation: totalRotation,+ });+ const targetRect = targetViewport.convertToViewportRectangle(position);+ const captureScale = getLimitedCaptureScale(targetRect);+ if (captureScale <= 0) {+ throw new Error("PDF rectangle annotation has invalid coordinates");+ }++ const viewport = pdfPage.getViewport({scale: captureScale, rotation: totalRotation});+ const captureBounds = getCaptureCanvasBounds(viewport.convertToViewportRectangle(position));const captureViewport = pdfPage.getViewport({- scale: pdfObj.pdfViewer.currentScale * window.pdfjsLib.PixelsPerInch.PDF_TO_CSS_UNITS * CAPTURE_SCALE_RATIO,- rotation: 0+ scale: captureScale,+ rotation: totalRotation,+ offsetX: -captureBounds.left,+ offsetY: -captureBounds.top,});const captureCanvas = document.createElement("canvas");- captureCanvas.width = Math.floor(captureViewport.width);- captureCanvas.height = Math.floor(captureViewport.height);+ captureCanvas.width = captureBounds.width;+ captureCanvas.height = captureBounds.height;const captureCtx = captureCanvas.getContext("2d");+ if (!captureCtx) {+ throw new Error("Unable to create a canvas context for the PDF rectangle annotation");+ }await pdfPage.render({canvasContext: captureCtx,- viewport: captureViewport+ viewport: captureViewport,}).promise;- const rectStyle = (annotationElement.firstElementChild as HTMLElement).style;- const captureImageData = captureCtx.getImageData(- CAPTURE_SCALE_RATIO * parseFloat(rectStyle.left),- CAPTURE_SCALE_RATIO * parseFloat(rectStyle.top),- CAPTURE_SCALE_RATIO * parseFloat(rectStyle.width),- CAPTURE_SCALE_RATIO * parseFloat(rectStyle.height)+ const displayViewport = pdfPage.getViewport({scale: PDF_RECT_DISPLAY_SCALE, rotation: totalRotation});+ const displayWidth = Math.min(+ getCaptureDisplayWidth(displayViewport.convertToViewportRectangle(position)),+ captureBounds.width,);-- const resultCanvas = document.createElement("canvas");- resultCanvas.width = captureImageData.width;- resultCanvas.height = captureImageData.height;- // 页面实际旋转角度 = 用户旋转 + PDF 本身旋转- const totalRotation = (pageView.rotation + pageView.pdfPageRotate) % 360;- const resultCtx = resultCanvas.getContext("2d");- if (totalRotation === 0) {- resultCtx.putImageData(captureImageData, 0, 0);- } else {- // 交换宽高- if (totalRotation === 90 || totalRotation === 270) {- [resultCanvas.width, resultCanvas.height] = [resultCanvas.height, resultCanvas.width];- }- resultCtx.translate(resultCanvas.width / 2, resultCanvas.height / 2);- resultCtx.rotate((totalRotation * Math.PI) / 180);- // 在旋转后的画布坐标系上绘制图片- const tempCanvas = document.createElement("canvas");- tempCanvas.width = captureImageData.width;- tempCanvas.height = captureImageData.height;- const tempCtx = tempCanvas.getContext("2d");- tempCtx.putImageData(captureImageData, 0, 0);- resultCtx.drawImage(tempCanvas, -tempCanvas.width / 2, -tempCanvas.height / 2);- }-- return {url: resultCanvas.toDataURL(), rotation: totalRotation};+ const blob = await new Promise<Blob>((resolve, reject) => {+ captureCanvas.toBlob((result) => {+ if (result) {+ resolve(result);+ } else {+ reject(new Error("Unable to encode the PDF rectangle annotation"));+ }+ }, "image/png");+ });+ return {blob, rotation: totalRotation, displayWidth};}const setConfig = (pdf: any, id: string, data: IPdfAnno) => {diff --git a/app/src/asset/pdfRectCapture.test.ts b/app/src/asset/pdfRectCapture.test.tsnew file mode 100644index 0000000000..bf6f988f93--- /dev/null+++ b/app/src/asset/pdfRectCapture.test.ts@@ -0,0 +1,70 @@+import {describe, it} from "node:test";+import * as assert from "node:assert/strict";+import {+ getCaptureCanvasBounds,+ getCaptureDisplayWidth,+ getLimitedCaptureScale,+ normalizePdfRect,+ PDF_RECT_CAPTURE_MAX_EDGE,+ PDF_RECT_CAPTURE_MAX_PIXELS,+ PDF_RECT_CAPTURE_SCALE,+} from "./pdfRectCapture";++describe("PDF rectangle capture", () => {+ it("normalizes viewport rectangles in every coordinate direction", () => {+ assert.deepEqual(normalizePdfRect([80, 90, 20, 30]), {+ left: 20,+ top: 30,+ right: 80,+ bottom: 90,+ width: 60,+ height: 60,+ });+ });++ it("uses the target scale for regular rectangles", () => {+ assert.equal(getLimitedCaptureScale([10, 20, 410, 220]), PDF_RECT_CAPTURE_SCALE);+ });++ it("reduces the scale when an edge or the pixel count is too large", () => {+ const edgeLimited = getLimitedCaptureScale([0, 0, 16384, 100]);+ const pixelLimited = getLimitedCaptureScale([0, 0, 8000, 4000]);+ assert.ok(edgeLimited < 2);+ assert.ok(pixelLimited < PDF_RECT_CAPTURE_SCALE);+ assert.ok(pixelLimited > 2);+ });++ it("keeps rounded canvases within the configured limits", () => {+ const viewportRect = [0.4, 0.4, 8000.4, 4000.4];+ const captureScale = getLimitedCaptureScale(viewportRect);+ const ratio = captureScale / PDF_RECT_CAPTURE_SCALE;+ const bounds = getCaptureCanvasBounds([+ viewportRect[0] * ratio,+ viewportRect[1] * ratio,+ viewportRect[2] * ratio,+ viewportRect[3] * ratio,+ ]);+ assert.ok(bounds.width <= PDF_RECT_CAPTURE_MAX_EDGE);+ assert.ok(bounds.height <= PDF_RECT_CAPTURE_MAX_EDGE);+ assert.ok(bounds.width * bounds.height <= PDF_RECT_CAPTURE_MAX_PIXELS);+ });++ it("rejects empty and invalid rectangles", () => {+ assert.equal(getLimitedCaptureScale([10, 20, 10, 30]), 0);+ assert.equal(getLimitedCaptureScale([0, 0, Number.NaN, 30]), 0);+ });++ it("expands fractional bounds to complete canvas pixels", () => {+ assert.deepEqual(getCaptureCanvasBounds([20.8, 40.2, 10.1, 30.9]), {+ left: 10,+ top: 30,+ width: 11,+ height: 11,+ });+ });++ it("keeps a stable display width", () => {+ assert.equal(getCaptureDisplayWidth([10, 20, 130.126, 70]), 120.13);+ assert.equal(getCaptureDisplayWidth([10, 20, 10, 70]), 1);+ });+});diff --git a/app/src/asset/pdfRectCapture.ts b/app/src/asset/pdfRectCapture.tsnew file mode 100644index 0000000000..6aebcb4660--- /dev/null+++ b/app/src/asset/pdfRectCapture.ts@@ -0,0 +1,69 @@+const PDF_POINTS_PER_INCH = 72;+export const PDF_RECT_CAPTURE_DPI = 288;+export const PDF_RECT_CAPTURE_SCALE = PDF_RECT_CAPTURE_DPI / PDF_POINTS_PER_INCH;+export const PDF_RECT_DISPLAY_SCALE = 2;+export const PDF_RECT_CAPTURE_MAX_EDGE = 8192;+export const PDF_RECT_CAPTURE_MAX_PIXELS = 16 * 1024 * 1024;+export const PDF_RECT_CAPTURE_PROFILE = "capture-v2";++interface IRectBounds {+ left: number;+ top: number;+ right: number;+ bottom: number;+ width: number;+ height: number;+}++export const normalizePdfRect = (rect: number[]): IRectBounds => {+ const left = Math.min(rect[0], rect[2]);+ const top = Math.min(rect[1], rect[3]);+ const right = Math.max(rect[0], rect[2]);+ const bottom = Math.max(rect[1], rect[3]);+ return {+ left,+ top,+ right,+ bottom,+ width: right - left,+ height: bottom - top,+ };+};++export const getLimitedCaptureScale = (viewportRect: number[], targetScale = PDF_RECT_CAPTURE_SCALE,+ maxEdge = PDF_RECT_CAPTURE_MAX_EDGE,+ maxPixels = PDF_RECT_CAPTURE_MAX_PIXELS) => {+ const bounds = normalizePdfRect(viewportRect);+ if (!Number.isFinite(bounds.width) || !Number.isFinite(bounds.height) || bounds.width <= 0 || bounds.height <= 0) {+ return 0;+ }+ // 为取整产生的边缘像素预留空间,确保最终画布仍在限制内。+ const safeMaxEdge = Math.max(1, maxEdge - 2);+ const safeMaxPixels = Math.max(1, maxPixels - 4 * maxEdge - 4);+ const limitRatio = Math.min(+ 1,+ safeMaxEdge / bounds.width,+ safeMaxEdge / bounds.height,+ Math.sqrt(safeMaxPixels / (bounds.width * bounds.height)),+ );+ return targetScale * limitRatio;+};++export const getCaptureCanvasBounds = (viewportRect: number[]) => {+ const bounds = normalizePdfRect(viewportRect);+ const left = Math.floor(bounds.left);+ const top = Math.floor(bounds.top);+ const right = Math.ceil(bounds.right);+ const bottom = Math.ceil(bounds.bottom);+ return {+ left,+ top,+ width: Math.max(1, right - left),+ height: Math.max(1, bottom - top),+ };+};++export const getCaptureDisplayWidth = (viewportRect: number[]) => {+ const width = normalizePdfRect(viewportRect).width;+ return Math.max(1, Math.round(width * 100) / 100);+};diff --git a/app/src/asset/rectAnnotationResize.test.ts b/app/src/asset/rectAnnotationResize.test.tsindex ecd59897db..d661715a2a 100644--- a/app/src/asset/rectAnnotationResize.test.ts+++ b/app/src/asset/rectAnnotationResize.test.ts@@ -60,12 +60,12 @@ describe("rectangle annotation resizing", () => {it("uses the rectangle position hash in copied image names", () => {const content = "example-P1-20260809120000-abcdefg";- assert.equal(getRectImageName(content, 0, "0123456"),- "example-P1-20260809120000-0123456.png");- assert.equal(getRectImageName(content, 90, "7654321"),- "example-P1-90-20260809120000-7654321.png");- assert.equal(getRectImageName(content, 0, ""),- "example-P1-20260809120000-abcdefg.png");+ assert.equal(getRectImageName(content, 0, "0123456", "capture-v2"),+ "example-P1-capture-v2-20260809120000-0123456.png");+ assert.equal(getRectImageName(content, 90, "7654321", "capture-v2"),+ "example-P1-90-capture-v2-20260809120000-7654321.png");+ assert.equal(getRectImageName(content, 0, "", "capture-v2"),+ "example-P1-capture-v2-20260809120000-abcdefg.png");});it("keeps resized rectangles within the page", () => {diff --git a/app/src/asset/rectAnnotationResize.ts b/app/src/asset/rectAnnotationResize.tsindex 79e0689610..dace5be5e7 100644--- a/app/src/asset/rectAnnotationResize.ts+++ b/app/src/asset/rectAnnotationResize.ts@@ -40,10 +40,11 @@ export const moveRectBounds = (initial: RectBounds, boundary: RectBounds, deltaX};};-export const getRectImageName = (content: string, rotation: number, positionHash: string) => {+export const getRectImageName = (content: string, rotation: number, positionHash: string, captureProfile: string) => {const annotationID = content.substring(content.length - 22);const imageID = positionHash ? annotationID.substring(0, 15) + positionHash.substring(0, 7) : annotationID;- return content.substring(0, content.length - 22) + (rotation ? `${rotation}-` : "") + imageID + ".png";+ return content.substring(0, content.length - 22) + (rotation ? `${rotation}-` : "") ++ `${captureProfile}-${imageID}.png`;};export const hideRectResizeHandles = (element: ParentNode) => {