diff --git a/src/api/PDFPage.ts b/src/api/PDFPage.ts index 7333440bd..82b3386b4 100644 --- a/src/api/PDFPage.ts +++ b/src/api/PDFPage.ts @@ -568,6 +568,31 @@ export default class PDFPage { this.node.wrapContentStreams(startRef, endRef); } + /** + * translate this page's content and annotations. In some scenarios, the annotations + * is following this text.If only the [translateContent] function is used, + * the position of the annotations relative to the text will change,so you can use [translate] function . + * For example: + * ```js + * // Move the page's content and annotations from the lower-left corner of the page + * // to the top-right corner. + * page.translate(50, 50) + * ``` + * @param x The new position on the x-axis for this page's content. + * @param y The new position on the y-axis for this page's content. + */ + translate(x:number,y:number):void { + assertIs(x, 'x', ['number']); + assertIs(y, 'y', ['number']); + this.translateContent(x, y) + const annots = this.node.Annots() + if (!annots) return + for (let idx = 0; idx < annots.size(); idx++) { + const annot = annots.lookup(idx) + if (annot instanceof PDFDict) this.translateAnnot(annot,x,y) + } + } + /** * Scale the size, content, and annotations of a page. * @@ -1618,4 +1643,25 @@ export default class PDFPage { } } } + /** + * move annotations + * @param annot annot + * @param x The new position on the x-axis for this page's content. + * @param y The new position on the y-axis for this page's content. + */ + private translateAnnot(annot: PDFDict, x: number, y: number) { + const selectors = ['RD', 'CL', 'Vertices', 'QuadPoints', 'L', 'Rect'] + for (let idx = 0, len = selectors.length; idx < len; idx++) { + const list = annot.lookup(PDFName.of(selectors[idx])) + if (list instanceof PDFArray) list.translatePDFNumbers(x,y) + } + + const inkLists = annot.lookup(PDFName.of('InkList')) + if (inkLists instanceof PDFArray) { + for (let idx = 0, len = inkLists.size(); idx < len; idx++) { + const arr = inkLists.lookup(idx) + if (arr instanceof PDFArray) arr.translatePDFNumbers(x,y) + } + } + } } diff --git a/src/core/objects/PDFArray.ts b/src/core/objects/PDFArray.ts index a2124fb5c..cec08b098 100644 --- a/src/core/objects/PDFArray.ts +++ b/src/core/objects/PDFArray.ts @@ -180,6 +180,15 @@ class PDFArray extends PDFObject { } } } + + translatePDFNumbers(x: number, y: number): void { + for (let idx = 0,len = this.size(); idx < len; idx++) { + const el = this.lookup(idx) + if (el instanceof PDFNumber) { + this.set(idx, PDFNumber.of(el.asNumber() + (idx % 2 === 0 ? x : y))) + } + } + } } export default PDFArray;