37 lines
914 B
TypeScript
37 lines
914 B
TypeScript
import { PDFName, PDFArray, PDFString, type PDFPage } from 'pdf-lib'
|
|
|
|
export interface LinkRect {
|
|
x: number
|
|
y: number
|
|
width: number
|
|
height: number
|
|
url: string
|
|
}
|
|
|
|
/** A clickable `/Link` annotation opening `url`, appended to the page's Annots. */
|
|
export function addLinkAnnotation(page: PDFPage, rect: LinkRect): void {
|
|
const context = page.doc.context
|
|
|
|
const actionDict = context.obj({
|
|
Type: 'Action',
|
|
S: 'URI',
|
|
URI: PDFString.of(rect.url),
|
|
})
|
|
|
|
const annotDict = context.obj({
|
|
Type: 'Annot',
|
|
Subtype: 'Link',
|
|
Rect: [rect.x, rect.y, rect.x + rect.width, rect.y + rect.height],
|
|
Border: [0, 0, 0],
|
|
A: actionDict,
|
|
})
|
|
|
|
const annots = page.node.lookup(PDFName.of('Annots'), PDFArray)
|
|
if (annots) {
|
|
annots.push(context.register(annotDict))
|
|
} else {
|
|
const arr = context.obj([context.register(annotDict)])
|
|
page.node.set(PDFName.of('Annots'), arr)
|
|
}
|
|
}
|