createPageAnnotation
Adds a new annotation to a specified page and returns its unique ID.
Signature
createPageAnnotation<A extends PdfAnnotationObject>(
doc: PdfDocumentObject,
page: PdfPageObject,
annotation: A,
context?: AnnotationCreateContext<A>
): PdfTask<string>;
Description
This method modifies the PDF in memory by adding a new annotation. You must construct a valid PdfAnnotationObject
with all the required properties for its type (e.g., a PdfHighlightAnnoObject
needs segmentRects
and a color
).
After creating an annotation, you will need to call saveAsCopy
to generate a new PDF file with the changes persisted.
Parameters
Name | Type | Description |
---|---|---|
doc | PdfDocumentObject | The handle of the document to modify. |
page | PdfPageObject | The page to add the annotation to. |
annotation | PdfAnnotationObject | The annotation object to create. The id property should be a unique identifier. If a valid UUID v4 is not provided for the id , one will be automatically generated. See Annotation Models . |
context | AnnotationCreateContext | (Optional) For special cases like Stamp annotations, this provides extra data (e.g., raw image data) that isn’t part of the core annotation object. |
Returns
PdfTask<string>
A Task
that resolves with the unique ID (string
) of the newly created annotation. This will be the ID you provided in the annotation
object, or a newly generated one if the original was missing or invalid.
Example
import {
PdfAnnotationSubtype,
PdfHighlightAnnoObject,
uuidV4
} from '@embedpdf/models';
// Assuming 'engine', 'document', and 'page' are available
async function addHighlight(doc, page) {
// Construct a new highlight annotation object with its type
const newHighlight: PdfHighlightAnnoObject = {
id: uuidV4(),
type: PdfAnnotationSubtype.HIGHLIGHT,
pageIndex: page.index,
rect: { origin: { x: 100, y: 100 }, size: { width: 200, height: 15 } },
segmentRects: [{ origin: { x: 100, y: 100 }, size: { width: 200, height: 15 } }],
color: '#FFD700', // Gold
opacity: 0.5,
};
try {
const newId = await engine.createPageAnnotation(doc, page, newHighlight).toPromise();
console.log(`Successfully created annotation with ID: ${newId}.`);
// Now you could re-render the page or call saveAsCopy()
} catch (error) {
console.error('Failed to create annotation:', error);
}
}
See Also
Last updated on August 14, 2025
Need Help?
Join our community for support, discussions, and to contribute to EmbedPDF's development.