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,SAASL,IAYrB,YAAA3E,uBAAA,W,MACE,GAAI/C,KAAKuD,UAAW,OAAO,EAG3B,IADA,IAAMyE,EAAUhI,KAAKnF,UAAUoN,aACtB5I,EAAM,EAAGC,EAAM0I,EAAQlQ,OAAQuH,EAAMC,EAAKD,IAAO,CAIxD,MADyB,QAAvB,EAFa2I,EAAQ3I,GAEd+I,wBAAgB,eAAEpP,kBAAkB,MACxB,OAAO,EAG9B,OAAO,GAaT,YAAAgK,yBAAA,SAAyB7I,IACvB,QAASA,EAAM,OAAQ,CAAC,CAAC,EAAS,aAClC6F,KAAKsI,kBAAkBnO,IAsBzB,YAAAmO,kBAAA,SACEnO,EACAoO,IAEA,QAASpO,EAAM,OAAQ,CAAC,CAAC,EAAS,cAClC,QAAkBoO,EAAU,WAAY,CAACC,WAGzC,IADA,IAAMR,EAAUhI,KAAKnF,UAAUoN,aACtB5I,EAAM,EAAGC,EAAM0I,EAAQlQ,OAAQuH,EAAMC,EAAKD,IAAO,CACxD,IAAM3E,EAASsN,EAAQ3I,GACvBW,KAAK6H,uBAAuBnN,EAAQP,EAAMoO,KAItC,YAAAV,uBAAR,SACEnN,EACAP,EACAoO,GAEA,IACME,EAAc3P,GADDyP,MAAAA,EAAAA,EAAYzL,GACoBkD,KAAMtF,EAAQP,IACjE6F,KAAKgF,+BAA+BtK,EAAQP,EAAMsO,IA1N7C,EAAAnI,GAAK,SACV2nB,EACAroB,EACAC,GACG,WAAIqoB,EAAUD,EAAgBroB,EAAKC,IAwN1C,EAxOA,CAAuC,G","sources":["webpack://Msdyn365.Commerce.Online/./node_modules/pdf-lib/src/api/colors.ts?8fda","webpack://Msdyn365.Commerce.Online/./node_modules/pdf-lib/src/api/errors.ts?af13","webpack://Msdyn365.Commerce.Online/./node_modules/pdf-lib/src/api/form/appearances.ts?da66","webpack://Msdyn365.Commerce.Online/./node_modules/pdf-lib/src/api/PDFEmbeddedPage.ts?909c","webpack://Msdyn365.Commerce.Online/./node_modules/pdf-lib/src/api/PDFFont.ts?dba5","webpack://Msdyn365.Commerce.Online/./node_modules/pdf-lib/src/api/PDFImage.ts?f4ca","webpack://Msdyn365.Commerce.Online/./node_modules/pdf-lib/src/api/image/alignment.ts?ba51","webpack://Msdyn365.Commerce.Online/./node_modules/pdf-lib/src/api/form/PDFField.ts?f1e3","webpack://Msdyn365.Commerce.Online/./node_modules/pdf-lib/src/api/form/PDFCheckBox.ts?b602","webpack://Msdyn365.Commerce.Online/./node_modules/pdf-lib/src/api/form/PDFDropdown.ts?3e1b","webpack://Msdyn365.Commerce.Online/./node_modules/pdf-lib/src/api/form/PDFOptionList.ts?0fb0","webpack://Msdyn365.Commerce.Online/./node_modules/pdf-lib/src/api/form/PDFRadioGroup.ts?b53d","webpack://Msdyn365.Commerce.Online/./node_modules/pdf-lib/src/api/form/PDFSignature.ts?e451","webpack://Msdyn365.Commerce.Online/./node_modules/pdf-lib/src/api/form/PDFTextField.ts?c936","webpack://Msdyn365.Commerce.Online/./node_modules/pdf-lib/src/api/StandardFonts.ts?2b23","webpack://Msdyn365.Commerce.Online/./node_modules/pdf-lib/src/api/form/PDFForm.ts?4792","webpack://Msdyn365.Commerce.Online/./node_modules/pdf-lib/src/api/PDFDocumentOptions.ts?8ff3","webpack://Msdyn365.Commerce.Online/./node_modules/pdf-lib/src/api/PDFEmbeddedFile.ts?cfac","webpack://Msdyn365.Commerce.Online/./node_modules/pdf-lib/src/api/PDFJavaScript.ts?5268","webpack://Msdyn365.Commerce.Online/./node_modules/pdf-lib/src/api/PDFDocument.ts?0831","webpack://Msdyn365.Commerce.Online/./node_modules/pdf-lib/src/api/PDFPageOptions.ts?96e8","webpack://Msdyn365.Commerce.Online/./node_modules/pdf-lib/src/api/PDFPage.ts?1273","webpack://Msdyn365.Commerce.Online/./node_modules/pdf-lib/src/api/form/PDFButton.ts?d02b"],"sourcesContent":["import {\n setFillingCmykColor,\n setFillingGrayscaleColor,\n setFillingRgbColor,\n setStrokingCmykColor,\n setStrokingGrayscaleColor,\n setStrokingRgbColor,\n} from 'src/api/operators';\nimport { assertRange, error } from 'src/utils';\n\nexport enum ColorTypes {\n Grayscale = 'Grayscale',\n RGB = 'RGB',\n CMYK = 'CMYK',\n}\n\nexport interface Grayscale {\n type: ColorTypes.Grayscale;\n gray: number;\n}\n\nexport interface RGB {\n type: ColorTypes.RGB;\n red: number;\n green: number;\n blue: number;\n}\n\nexport interface CMYK {\n type: ColorTypes.CMYK;\n cyan: number;\n magenta: number;\n yellow: number;\n key: number;\n}\n\nexport type Color = Grayscale | RGB | CMYK;\n\nexport const grayscale = (gray: number): Grayscale => {\n assertRange(gray, 'gray', 0.0, 1.0);\n return { type: ColorTypes.Grayscale, gray };\n};\n\nexport const rgb = (red: number, green: number, blue: number): RGB => {\n assertRange(red, 'red', 0, 1);\n assertRange(green, 'green', 0, 1);\n assertRange(blue, 'blue', 0, 1);\n return { type: ColorTypes.RGB, red, green, blue };\n};\n\nexport const cmyk = (\n cyan: number,\n magenta: number,\n yellow: number,\n key: number,\n): CMYK => {\n assertRange(cyan, 'cyan', 0, 1);\n assertRange(magenta, 'magenta', 0, 1);\n assertRange(yellow, 'yellow', 0, 1);\n assertRange(key, 'key', 0, 1);\n return { type: ColorTypes.CMYK, cyan, magenta, yellow, key };\n};\n\nconst { Grayscale, RGB, CMYK } = ColorTypes;\n\n// prettier-ignore\nexport const setFillingColor = (color: Color) => \n color.type === Grayscale ? setFillingGrayscaleColor(color.gray)\n : color.type === RGB ? setFillingRgbColor(color.red, color.green, color.blue)\n : color.type === CMYK ? setFillingCmykColor(color.cyan, color.magenta, color.yellow, color.key)\n : error(`Invalid color: ${JSON.stringify(color)}`);\n\n// prettier-ignore\nexport const setStrokingColor = (color: Color) => \n color.type === Grayscale ? setStrokingGrayscaleColor(color.gray)\n : color.type === RGB ? setStrokingRgbColor(color.red, color.green, color.blue)\n : color.type === CMYK ? setStrokingCmykColor(color.cyan, color.magenta, color.yellow, color.key)\n : error(`Invalid color: ${JSON.stringify(color)}`);\n\n// prettier-ignore\nexport const componentsToColor = (comps?: number[], scale = 1) => (\n comps?.length === 1 ? grayscale(\n comps[0] * scale,\n )\n : comps?.length === 3 ? rgb(\n comps[0] * scale, \n comps[1] * scale, \n comps[2] * scale,\n )\n : comps?.length === 4 ? cmyk(\n comps[0] * scale, \n comps[1] * scale, \n comps[2] * scale, \n comps[3] * scale,\n )\n : undefined\n);\n\n// prettier-ignore\nexport const colorToComponents = (color: Color) =>\n color.type === Grayscale ? [color.gray]\n : color.type === RGB ? [color.red, color.green, color.blue]\n : color.type === CMYK ? [color.cyan, color.magenta, color.yellow, color.key]\n : error(`Invalid color: ${JSON.stringify(color)}`);\n","// tslint:disable: max-classes-per-file\n\n// TODO: Include link to documentation with example\nexport class EncryptedPDFError extends Error {\n constructor() {\n const msg =\n 'Input document to `PDFDocument.load` is encrypted. You can use `PDFDocument.load(..., { ignoreEncryption: true })` if you wish to load the document anyways.';\n super(msg);\n }\n}\n\n// TODO: Include link to documentation with example\nexport class FontkitNotRegisteredError extends Error {\n constructor() {\n const msg =\n 'Input to `PDFDocument.embedFont` was a custom font, but no `fontkit` instance was found. You must register a `fontkit` instance with `PDFDocument.registerFontkit(...)` before embedding custom fonts.';\n super(msg);\n }\n}\n\n// TODO: Include link to documentation with example\nexport class ForeignPageError extends Error {\n constructor() {\n const msg =\n 'A `page` passed to `PDFDocument.addPage` or `PDFDocument.insertPage` was from a different (foreign) PDF document. If you want to copy pages from one PDFDocument to another, you must use `PDFDocument.copyPages(...)` to copy the pages before adding or inserting them.';\n super(msg);\n }\n}\n\n// TODO: Include link to documentation with example\nexport class RemovePageFromEmptyDocumentError extends Error {\n constructor() {\n const msg =\n 'PDFDocument has no pages so `PDFDocument.removePage` cannot be called';\n super(msg);\n }\n}\n\nexport class NoSuchFieldError extends Error {\n constructor(name: string) {\n const msg = `PDFDocument has no form field with the name \"${name}\"`;\n super(msg);\n }\n}\n\nexport class UnexpectedFieldTypeError extends Error {\n constructor(name: string, expected: any, actual: any) {\n const expectedType = expected?.name;\n const actualType = actual?.constructor?.name ?? actual;\n const msg =\n `Expected field \"${name}\" to be of type ${expectedType}, ` +\n `but it is actually of type ${actualType}`;\n super(msg);\n }\n}\n\nexport class MissingOnValueCheckError extends Error {\n constructor(onValue: any) {\n const msg = `Failed to select check box due to missing onValue: \"${onValue}\"`;\n super(msg);\n }\n}\n\nexport class FieldAlreadyExistsError extends Error {\n constructor(name: string) {\n const msg = `A field already exists with the specified name: \"${name}\"`;\n super(msg);\n }\n}\n\nexport class InvalidFieldNamePartError extends Error {\n constructor(namePart: string) {\n const msg = `Field name contains invalid component: \"${namePart}\"`;\n super(msg);\n }\n}\n\nexport class FieldExistsAsNonTerminalError extends Error {\n constructor(name: string) {\n const msg = `A non-terminal field already exists with the specified name: \"${name}\"`;\n super(msg);\n }\n}\n\nexport class RichTextFieldReadError extends Error {\n constructor(fieldName: string) {\n const msg = `Reading rich text fields is not supported: Attempted to read rich text field: ${fieldName}`;\n super(msg);\n }\n}\n\nexport class CombedTextLayoutError extends Error {\n constructor(lineLength: number, cellCount: number) {\n const msg = `Failed to layout combed text as lineLength=${lineLength} is greater than cellCount=${cellCount}`;\n super(msg);\n }\n}\n\nexport class ExceededMaxLengthError extends Error {\n constructor(textLength: number, maxLength: number, name: string) {\n const msg = `Attempted to set text with length=${textLength} for TextField with maxLength=${maxLength} and name=${name}`;\n super(msg);\n }\n}\n\nexport class InvalidMaxLengthError extends Error {\n constructor(textLength: number, maxLength: number, name: string) {\n const msg = `Attempted to set maxLength=${maxLength}, which is less than ${textLength}, the length of this field's current value (name=${name})`;\n super(msg);\n }\n}\n","import { PDFOperator, PDFWidgetAnnotation } from 'src/core';\nimport PDFFont from 'src/api/PDFFont';\nimport PDFButton from 'src/api/form/PDFButton';\nimport PDFCheckBox from 'src/api/form/PDFCheckBox';\nimport PDFDropdown from 'src/api/form/PDFDropdown';\nimport PDFField from 'src/api/form/PDFField';\nimport PDFOptionList from 'src/api/form/PDFOptionList';\nimport PDFRadioGroup from 'src/api/form/PDFRadioGroup';\nimport PDFSignature from 'src/api/form/PDFSignature';\nimport PDFTextField from 'src/api/form/PDFTextField';\nimport {\n drawCheckBox,\n rotateInPlace,\n drawRadioButton,\n drawButton,\n drawTextField,\n drawOptionList,\n} from 'src/api/operations';\nimport {\n rgb,\n componentsToColor,\n setFillingColor,\n grayscale,\n cmyk,\n Color,\n} from 'src/api/colors';\nimport { reduceRotation, adjustDimsForRotation } from 'src/api/rotations';\nimport {\n layoutMultilineText,\n layoutCombedText,\n TextPosition,\n layoutSinglelineText,\n} from 'src/api/text/layout';\nimport { TextAlignment } from 'src/api/text/alignment';\nimport { setFontAndSize } from 'src/api/operators';\nimport { findLastMatch } from 'src/utils';\n\n/*********************** Appearance Provider Types ****************************/\n\ntype CheckBoxAppearanceProvider = (\n checkBox: PDFCheckBox,\n widget: PDFWidgetAnnotation,\n) => AppearanceOrMapping<{\n on: PDFOperator[];\n off: PDFOperator[];\n}>;\n\ntype RadioGroupAppearanceProvider = (\n radioGroup: PDFRadioGroup,\n widget: PDFWidgetAnnotation,\n) => AppearanceOrMapping<{\n on: PDFOperator[];\n off: PDFOperator[];\n}>;\n\ntype ButtonAppearanceProvider = (\n button: PDFButton,\n widget: PDFWidgetAnnotation,\n font: PDFFont,\n) => AppearanceOrMapping;\n\ntype DropdownAppearanceProvider = (\n dropdown: PDFDropdown,\n widget: PDFWidgetAnnotation,\n font: PDFFont,\n) => AppearanceOrMapping;\n\ntype OptionListAppearanceProvider = (\n optionList: PDFOptionList,\n widget: PDFWidgetAnnotation,\n font: PDFFont,\n) => AppearanceOrMapping;\n\ntype TextFieldAppearanceProvider = (\n textField: PDFTextField,\n widget: PDFWidgetAnnotation,\n font: PDFFont,\n) => AppearanceOrMapping;\n\ntype SignatureAppearanceProvider = (\n signature: PDFSignature,\n widget: PDFWidgetAnnotation,\n font: PDFFont,\n) => AppearanceOrMapping;\n\n/******************* Appearance Provider Utility Types ************************/\n\nexport type AppearanceMapping = { normal: T; rollover?: T; down?: T };\n\ntype AppearanceOrMapping = T | AppearanceMapping;\n\n// prettier-ignore\nexport type AppearanceProviderFor = \n T extends PDFCheckBox ? CheckBoxAppearanceProvider\n: T extends PDFRadioGroup ? RadioGroupAppearanceProvider\n: T extends PDFButton ? ButtonAppearanceProvider\n: T extends PDFDropdown ? DropdownAppearanceProvider\n: T extends PDFOptionList ? OptionListAppearanceProvider\n: T extends PDFTextField ? TextFieldAppearanceProvider\n: T extends PDFSignature ? SignatureAppearanceProvider\n: never;\n\n/********************* Appearance Provider Functions **************************/\n\nexport const normalizeAppearance = (\n appearance: T | AppearanceMapping,\n): AppearanceMapping => {\n if ('normal' in appearance) return appearance;\n return { normal: appearance };\n};\n\n// Examples:\n// `/Helv 12 Tf` -> ['/Helv 12 Tf', 'Helv', '12']\n// `/HeBo 8.00 Tf` -> ['/HeBo 8 Tf', 'HeBo', '8.00']\nconst tfRegex = /\\/([^\\0\\t\\n\\f\\r\\ ]+)[\\0\\t\\n\\f\\r\\ ]+(\\d*\\.\\d+|\\d+)[\\0\\t\\n\\f\\r\\ ]+Tf/;\n\nconst getDefaultFontSize = (field: {\n getDefaultAppearance(): string | undefined;\n}) => {\n const da = field.getDefaultAppearance() ?? '';\n const daMatch = findLastMatch(da, tfRegex).match ?? [];\n const defaultFontSize = Number(daMatch[2]);\n return isFinite(defaultFontSize) ? defaultFontSize : undefined;\n};\n\n// Examples:\n// `0.3 g` -> ['0.3', 'g']\n// `0.3 1 .3 rg` -> ['0.3', '1', '.3', 'rg']\n// `0.3 1 .3 0 k` -> ['0.3', '1', '.3', '0', 'k']\nconst colorRegex = /(\\d*\\.\\d+|\\d+)[\\0\\t\\n\\f\\r\\ ]*(\\d*\\.\\d+|\\d+)?[\\0\\t\\n\\f\\r\\ ]*(\\d*\\.\\d+|\\d+)?[\\0\\t\\n\\f\\r\\ ]*(\\d*\\.\\d+|\\d+)?[\\0\\t\\n\\f\\r\\ ]+(g|rg|k)/;\n\nconst getDefaultColor = (field: {\n getDefaultAppearance(): string | undefined;\n}) => {\n const da = field.getDefaultAppearance() ?? '';\n const daMatch = findLastMatch(da, colorRegex).match;\n\n const [, c1, c2, c3, c4, colorSpace] = daMatch ?? [];\n\n if (colorSpace === 'g' && c1) {\n return grayscale(Number(c1));\n }\n if (colorSpace === 'rg' && c1 && c2 && c3) {\n return rgb(Number(c1), Number(c2), Number(c3));\n }\n if (colorSpace === 'k' && c1 && c2 && c3 && c4) {\n return cmyk(Number(c1), Number(c2), Number(c3), Number(c4));\n }\n\n return undefined;\n};\n\nconst updateDefaultAppearance = (\n field: { setDefaultAppearance(appearance: string): void },\n color: Color,\n font?: PDFFont,\n fontSize: number = 0,\n) => {\n const da = [\n setFillingColor(color).toString(),\n setFontAndSize(font?.name ?? 'dummy__noop', fontSize).toString(),\n ].join('\\n');\n field.setDefaultAppearance(da);\n};\n\nexport const defaultCheckBoxAppearanceProvider: AppearanceProviderFor = (\n checkBox,\n widget,\n) => {\n // The `/DA` entry can be at the widget or field level - so we handle both\n const widgetColor = getDefaultColor(widget);\n const fieldColor = getDefaultColor(checkBox.acroField);\n\n const rectangle = widget.getRectangle();\n const ap = widget.getAppearanceCharacteristics();\n const bs = widget.getBorderStyle();\n\n const borderWidth = bs?.getWidth() ?? 0;\n const rotation = reduceRotation(ap?.getRotation());\n const { width, height } = adjustDimsForRotation(rectangle, rotation);\n\n const rotate = rotateInPlace({ ...rectangle, rotation });\n\n const black = rgb(0, 0, 0);\n const borderColor = componentsToColor(ap?.getBorderColor()) ?? black;\n const normalBackgroundColor = componentsToColor(ap?.getBackgroundColor());\n const downBackgroundColor = componentsToColor(ap?.getBackgroundColor(), 0.8);\n\n // Update color\n const textColor = widgetColor ?? fieldColor ?? black;\n if (widgetColor) {\n updateDefaultAppearance(widget, textColor);\n } else {\n updateDefaultAppearance(checkBox.acroField, textColor);\n }\n\n const options = {\n x: 0 + borderWidth / 2,\n y: 0 + borderWidth / 2,\n width: width - borderWidth,\n height: height - borderWidth,\n thickness: 1.5,\n borderWidth,\n borderColor,\n markColor: textColor,\n };\n\n return {\n normal: {\n on: [\n ...rotate,\n ...drawCheckBox({\n ...options,\n color: normalBackgroundColor,\n filled: true,\n }),\n ],\n off: [\n ...rotate,\n ...drawCheckBox({\n ...options,\n color: normalBackgroundColor,\n filled: false,\n }),\n ],\n },\n down: {\n on: [\n ...rotate,\n ...drawCheckBox({\n ...options,\n color: downBackgroundColor,\n filled: true,\n }),\n ],\n off: [\n ...rotate,\n ...drawCheckBox({\n ...options,\n color: downBackgroundColor,\n filled: false,\n }),\n ],\n },\n };\n};\n\nexport const defaultRadioGroupAppearanceProvider: AppearanceProviderFor = (\n radioGroup,\n widget,\n) => {\n // The `/DA` entry can be at the widget or field level - so we handle both\n const widgetColor = getDefaultColor(widget);\n const fieldColor = getDefaultColor(radioGroup.acroField);\n\n const rectangle = widget.getRectangle();\n const ap = widget.getAppearanceCharacteristics();\n const bs = widget.getBorderStyle();\n\n const borderWidth = bs?.getWidth() ?? 0;\n const rotation = reduceRotation(ap?.getRotation());\n const { width, height } = adjustDimsForRotation(rectangle, rotation);\n\n const rotate = rotateInPlace({ ...rectangle, rotation });\n\n const black = rgb(0, 0, 0);\n const borderColor = componentsToColor(ap?.getBorderColor()) ?? black;\n const normalBackgroundColor = componentsToColor(ap?.getBackgroundColor());\n const downBackgroundColor = componentsToColor(ap?.getBackgroundColor(), 0.8);\n\n // Update color\n const textColor = widgetColor ?? fieldColor ?? black;\n if (widgetColor) {\n updateDefaultAppearance(widget, textColor);\n } else {\n updateDefaultAppearance(radioGroup.acroField, textColor);\n }\n\n const options = {\n x: width / 2,\n y: height / 2,\n width: width - borderWidth,\n height: height - borderWidth,\n borderWidth,\n borderColor,\n dotColor: textColor,\n };\n\n return {\n normal: {\n on: [\n ...rotate,\n ...drawRadioButton({\n ...options,\n color: normalBackgroundColor,\n filled: true,\n }),\n ],\n off: [\n ...rotate,\n ...drawRadioButton({\n ...options,\n color: normalBackgroundColor,\n filled: false,\n }),\n ],\n },\n down: {\n on: [\n ...rotate,\n ...drawRadioButton({\n ...options,\n color: downBackgroundColor,\n filled: true,\n }),\n ],\n off: [\n ...rotate,\n ...drawRadioButton({\n ...options,\n color: downBackgroundColor,\n filled: false,\n }),\n ],\n },\n };\n};\n\nexport const defaultButtonAppearanceProvider: AppearanceProviderFor = (\n button,\n widget,\n font,\n) => {\n // The `/DA` entry can be at the widget or field level - so we handle both\n const widgetColor = getDefaultColor(widget);\n const fieldColor = getDefaultColor(button.acroField);\n const widgetFontSize = getDefaultFontSize(widget);\n const fieldFontSize = getDefaultFontSize(button.acroField);\n\n const rectangle = widget.getRectangle();\n const ap = widget.getAppearanceCharacteristics();\n const bs = widget.getBorderStyle();\n const captions = ap?.getCaptions();\n const normalText = captions?.normal ?? '';\n const downText = captions?.down ?? normalText ?? '';\n\n const borderWidth = bs?.getWidth() ?? 0;\n const rotation = reduceRotation(ap?.getRotation());\n const { width, height } = adjustDimsForRotation(rectangle, rotation);\n\n const rotate = rotateInPlace({ ...rectangle, rotation });\n\n const black = rgb(0, 0, 0);\n\n const borderColor = componentsToColor(ap?.getBorderColor());\n const normalBackgroundColor = componentsToColor(ap?.getBackgroundColor());\n const downBackgroundColor = componentsToColor(ap?.getBackgroundColor(), 0.8);\n\n const bounds = {\n x: borderWidth,\n y: borderWidth,\n width: width - borderWidth * 2,\n height: height - borderWidth * 2,\n };\n const normalLayout = layoutSinglelineText(normalText, {\n alignment: TextAlignment.Center,\n fontSize: widgetFontSize ?? fieldFontSize,\n font,\n bounds,\n });\n const downLayout = layoutSinglelineText(downText, {\n alignment: TextAlignment.Center,\n fontSize: widgetFontSize ?? fieldFontSize,\n font,\n bounds,\n });\n\n // Update font size and color\n const fontSize = Math.min(normalLayout.fontSize, downLayout.fontSize);\n const textColor = widgetColor ?? fieldColor ?? black;\n if (widgetColor || widgetFontSize !== undefined) {\n updateDefaultAppearance(widget, textColor, font, fontSize);\n } else {\n updateDefaultAppearance(button.acroField, textColor, font, fontSize);\n }\n\n const options = {\n x: 0 + borderWidth / 2,\n y: 0 + borderWidth / 2,\n width: width - borderWidth,\n height: height - borderWidth,\n borderWidth,\n borderColor,\n textColor,\n font: font.name,\n fontSize,\n };\n\n return {\n normal: [\n ...rotate,\n ...drawButton({\n ...options,\n color: normalBackgroundColor,\n textLines: [normalLayout.line],\n }),\n ],\n down: [\n ...rotate,\n ...drawButton({\n ...options,\n color: downBackgroundColor,\n textLines: [downLayout.line],\n }),\n ],\n };\n};\n\nexport const defaultTextFieldAppearanceProvider: AppearanceProviderFor = (\n textField,\n widget,\n font,\n) => {\n // The `/DA` entry can be at the widget or field level - so we handle both\n const widgetColor = getDefaultColor(widget);\n const fieldColor = getDefaultColor(textField.acroField);\n const widgetFontSize = getDefaultFontSize(widget);\n const fieldFontSize = getDefaultFontSize(textField.acroField);\n\n const rectangle = widget.getRectangle();\n const ap = widget.getAppearanceCharacteristics();\n const bs = widget.getBorderStyle();\n const text = textField.getText() ?? '';\n\n const borderWidth = bs?.getWidth() ?? 0;\n const rotation = reduceRotation(ap?.getRotation());\n const { width, height } = adjustDimsForRotation(rectangle, rotation);\n\n const rotate = rotateInPlace({ ...rectangle, rotation });\n\n const black = rgb(0, 0, 0);\n\n const borderColor = componentsToColor(ap?.getBorderColor());\n const normalBackgroundColor = componentsToColor(ap?.getBackgroundColor());\n\n let textLines: TextPosition[];\n let fontSize: number;\n\n const padding = textField.isCombed() ? 0 : 1;\n const bounds = {\n x: borderWidth + padding,\n y: borderWidth + padding,\n width: width - (borderWidth + padding) * 2,\n height: height - (borderWidth + padding) * 2,\n };\n if (textField.isMultiline()) {\n const layout = layoutMultilineText(text, {\n alignment: textField.getAlignment(),\n fontSize: widgetFontSize ?? fieldFontSize,\n font,\n bounds,\n });\n textLines = layout.lines;\n fontSize = layout.fontSize;\n } else if (textField.isCombed()) {\n const layout = layoutCombedText(text, {\n fontSize: widgetFontSize ?? fieldFontSize,\n font,\n bounds,\n cellCount: textField.getMaxLength() ?? 0,\n });\n textLines = layout.cells;\n fontSize = layout.fontSize;\n } else {\n const layout = layoutSinglelineText(text, {\n alignment: textField.getAlignment(),\n fontSize: widgetFontSize ?? fieldFontSize,\n font,\n bounds,\n });\n textLines = [layout.line];\n fontSize = layout.fontSize;\n }\n\n // Update font size and color\n const textColor = widgetColor ?? fieldColor ?? black;\n if (widgetColor || widgetFontSize !== undefined) {\n updateDefaultAppearance(widget, textColor, font, fontSize);\n } else {\n updateDefaultAppearance(textField.acroField, textColor, font, fontSize);\n }\n\n const options = {\n x: 0 + borderWidth / 2,\n y: 0 + borderWidth / 2,\n width: width - borderWidth,\n height: height - borderWidth,\n borderWidth: borderWidth ?? 0,\n borderColor,\n textColor,\n font: font.name,\n fontSize,\n color: normalBackgroundColor,\n textLines,\n padding,\n };\n\n return [...rotate, ...drawTextField(options)];\n};\n\nexport const defaultDropdownAppearanceProvider: AppearanceProviderFor = (\n dropdown,\n widget,\n font,\n) => {\n // The `/DA` entry can be at the widget or field level - so we handle both\n const widgetColor = getDefaultColor(widget);\n const fieldColor = getDefaultColor(dropdown.acroField);\n const widgetFontSize = getDefaultFontSize(widget);\n const fieldFontSize = getDefaultFontSize(dropdown.acroField);\n\n const rectangle = widget.getRectangle();\n const ap = widget.getAppearanceCharacteristics();\n const bs = widget.getBorderStyle();\n const text = dropdown.getSelected()[0] ?? '';\n\n const borderWidth = bs?.getWidth() ?? 0;\n const rotation = reduceRotation(ap?.getRotation());\n const { width, height } = adjustDimsForRotation(rectangle, rotation);\n\n const rotate = rotateInPlace({ ...rectangle, rotation });\n\n const black = rgb(0, 0, 0);\n\n const borderColor = componentsToColor(ap?.getBorderColor());\n const normalBackgroundColor = componentsToColor(ap?.getBackgroundColor());\n\n const padding = 1;\n const bounds = {\n x: borderWidth + padding,\n y: borderWidth + padding,\n width: width - (borderWidth + padding) * 2,\n height: height - (borderWidth + padding) * 2,\n };\n const { line, fontSize } = layoutSinglelineText(text, {\n alignment: TextAlignment.Left,\n fontSize: widgetFontSize ?? fieldFontSize,\n font,\n bounds,\n });\n\n // Update font size and color\n const textColor = widgetColor ?? fieldColor ?? black;\n if (widgetColor || widgetFontSize !== undefined) {\n updateDefaultAppearance(widget, textColor, font, fontSize);\n } else {\n updateDefaultAppearance(dropdown.acroField, textColor, font, fontSize);\n }\n\n const options = {\n x: 0 + borderWidth / 2,\n y: 0 + borderWidth / 2,\n width: width - borderWidth,\n height: height - borderWidth,\n borderWidth: borderWidth ?? 0,\n borderColor,\n textColor,\n font: font.name,\n fontSize,\n color: normalBackgroundColor,\n textLines: [line],\n padding,\n };\n\n return [...rotate, ...drawTextField(options)];\n};\n\nexport const defaultOptionListAppearanceProvider: AppearanceProviderFor = (\n optionList,\n widget,\n font,\n) => {\n // The `/DA` entry can be at the widget or field level - so we handle both\n const widgetColor = getDefaultColor(widget);\n const fieldColor = getDefaultColor(optionList.acroField);\n const widgetFontSize = getDefaultFontSize(widget);\n const fieldFontSize = getDefaultFontSize(optionList.acroField);\n\n const rectangle = widget.getRectangle();\n const ap = widget.getAppearanceCharacteristics();\n const bs = widget.getBorderStyle();\n\n const borderWidth = bs?.getWidth() ?? 0;\n const rotation = reduceRotation(ap?.getRotation());\n const { width, height } = adjustDimsForRotation(rectangle, rotation);\n\n const rotate = rotateInPlace({ ...rectangle, rotation });\n\n const black = rgb(0, 0, 0);\n\n const borderColor = componentsToColor(ap?.getBorderColor());\n const normalBackgroundColor = componentsToColor(ap?.getBackgroundColor());\n\n const options = optionList.getOptions();\n const selected = optionList.getSelected();\n\n if (optionList.isSorted()) options.sort();\n\n let text = '';\n for (let idx = 0, len = options.length; idx < len; idx++) {\n text += options[idx];\n if (idx < len - 1) text += '\\n';\n }\n\n const padding = 1;\n const bounds = {\n x: borderWidth + padding,\n y: borderWidth + padding,\n width: width - (borderWidth + padding) * 2,\n height: height - (borderWidth + padding) * 2,\n };\n const { lines, fontSize, lineHeight } = layoutMultilineText(text, {\n alignment: TextAlignment.Left,\n fontSize: widgetFontSize ?? fieldFontSize,\n font,\n bounds,\n });\n\n const selectedLines: number[] = [];\n for (let idx = 0, len = lines.length; idx < len; idx++) {\n const line = lines[idx];\n if (selected.includes(line.text)) selectedLines.push(idx);\n }\n\n const blue = rgb(153 / 255, 193 / 255, 218 / 255);\n\n // Update font size and color\n const textColor = widgetColor ?? fieldColor ?? black;\n if (widgetColor || widgetFontSize !== undefined) {\n updateDefaultAppearance(widget, textColor, font, fontSize);\n } else {\n updateDefaultAppearance(optionList.acroField, textColor, font, fontSize);\n }\n\n return [\n ...rotate,\n ...drawOptionList({\n x: 0 + borderWidth / 2,\n y: 0 + borderWidth / 2,\n width: width - borderWidth,\n height: height - borderWidth,\n borderWidth: borderWidth ?? 0,\n borderColor,\n textColor,\n font: font.name,\n fontSize,\n color: normalBackgroundColor,\n textLines: lines,\n lineHeight,\n selectedColor: blue,\n selectedLines,\n padding,\n }),\n ];\n};\n","import Embeddable from 'src/api/Embeddable';\nimport PDFDocument from 'src/api/PDFDocument';\nimport { PDFPageEmbedder, PDFRef } from 'src/core';\nimport { assertIs } from 'src/utils';\n\n/**\n * Represents a PDF page that has been embedded in a [[PDFDocument]].\n */\nexport default class PDFEmbeddedPage implements Embeddable {\n /**\n * > **NOTE:** You probably don't want to call this method directly. Instead,\n * > consider using the [[PDFDocument.embedPdf]] and\n * > [[PDFDocument.embedPage]] methods, which will create instances of\n * > [[PDFEmbeddedPage]] for you.\n *\n * Create an instance of [[PDFEmbeddedPage]] from an existing ref and embedder\n *\n * @param ref The unique reference for this embedded page.\n * @param doc The document to which the embedded page will belong.\n * @param embedder The embedder that will be used to embed the page.\n */\n static of = (ref: PDFRef, doc: PDFDocument, embedder: PDFPageEmbedder) =>\n new PDFEmbeddedPage(ref, doc, embedder);\n\n /** The unique reference assigned to this embedded page within the document. */\n readonly ref: PDFRef;\n\n /** The document to which this embedded page belongs. */\n readonly doc: PDFDocument;\n\n /** The width of this page in pixels. */\n readonly width: number;\n\n /** The height of this page in pixels. */\n readonly height: number;\n\n private alreadyEmbedded = false;\n private readonly embedder: PDFPageEmbedder;\n\n private constructor(\n ref: PDFRef,\n doc: PDFDocument,\n embedder: PDFPageEmbedder,\n ) {\n assertIs(ref, 'ref', [[PDFRef, 'PDFRef']]);\n assertIs(doc, 'doc', [[PDFDocument, 'PDFDocument']]);\n assertIs(embedder, 'embedder', [[PDFPageEmbedder, 'PDFPageEmbedder']]);\n\n this.ref = ref;\n this.doc = doc;\n this.width = embedder.width;\n this.height = embedder.height;\n\n this.embedder = embedder;\n }\n\n /**\n * Compute the width and height of this page after being scaled by the\n * given `factor`. For example:\n * ```js\n * embeddedPage.width // => 500\n * embeddedPage.height // => 250\n *\n * const scaled = embeddedPage.scale(0.5)\n * scaled.width // => 250\n * scaled.height // => 125\n * ```\n * This operation is often useful before drawing a page with\n * [[PDFPage.drawPage]] to compute the `width` and `height` options.\n * @param factor The factor by which this page should be scaled.\n * @returns The width and height of the page after being scaled.\n */\n scale(factor: number) {\n assertIs(factor, 'factor', ['number']);\n return { width: this.width * factor, height: this.height * factor };\n }\n\n /**\n * Get the width and height of this page. For example:\n * ```js\n * const { width, height } = embeddedPage.size()\n * ```\n * @returns The width and height of the page.\n */\n size() {\n return this.scale(1);\n }\n\n /**\n * > **NOTE:** You probably don't need to call this method directly. The\n * > [[PDFDocument.save]] and [[PDFDocument.saveAsBase64]] methods will\n * > automatically ensure all embeddable pages get embedded.\n *\n * Embed this embeddable page in its document.\n *\n * @returns Resolves when the embedding is complete.\n */\n async embed(): Promise {\n if (!this.alreadyEmbedded) {\n await this.embedder.embedIntoContext(this.doc.context, this.ref);\n this.alreadyEmbedded = true;\n }\n }\n}\n","import Embeddable from 'src/api//Embeddable';\nimport PDFDocument from 'src/api/PDFDocument';\nimport {\n CustomFontEmbedder,\n PDFHexString,\n PDFRef,\n StandardFontEmbedder,\n} from 'src/core';\nimport { assertIs, assertOrUndefined } from 'src/utils';\n\nexport type FontEmbedder = CustomFontEmbedder | StandardFontEmbedder;\n\n/**\n * Represents a font that has been embedded in a [[PDFDocument]].\n */\nexport default class PDFFont implements Embeddable {\n /**\n * > **NOTE:** You probably don't want to call this method directly. Instead,\n * > consider using the [[PDFDocument.embedFont]] and\n * > [[PDFDocument.embedStandardFont]] methods, which will create instances\n * > of [[PDFFont]] for you.\n *\n * Create an instance of [[PDFFont]] from an existing ref and embedder\n *\n * @param ref The unique reference for this font.\n * @param doc The document to which the font will belong.\n * @param embedder The embedder that will be used to embed the font.\n */\n static of = (ref: PDFRef, doc: PDFDocument, embedder: FontEmbedder) =>\n new PDFFont(ref, doc, embedder);\n\n /** The unique reference assigned to this font within the document. */\n readonly ref: PDFRef;\n\n /** The document to which this font belongs. */\n readonly doc: PDFDocument;\n\n /** The name of this font. */\n readonly name: string;\n\n private modified = true;\n private readonly embedder: FontEmbedder;\n\n private constructor(ref: PDFRef, doc: PDFDocument, embedder: FontEmbedder) {\n assertIs(ref, 'ref', [[PDFRef, 'PDFRef']]);\n assertIs(doc, 'doc', [[PDFDocument, 'PDFDocument']]);\n assertIs(embedder, 'embedder', [\n [CustomFontEmbedder, 'CustomFontEmbedder'],\n [StandardFontEmbedder, 'StandardFontEmbedder'],\n ]);\n\n this.ref = ref;\n this.doc = doc;\n this.name = embedder.fontName;\n\n this.embedder = embedder;\n }\n\n /**\n * > **NOTE:** You probably don't need to call this method directly. The\n * > [[PDFPage.drawText]] method will automatically encode the text it is\n * > given.\n *\n * Encodes a string of text in this font.\n *\n * @param text The text to be encoded.\n * @returns The encoded text as a hex string.\n */\n encodeText(text: string): PDFHexString {\n assertIs(text, 'text', ['string']);\n this.modified = true;\n return this.embedder.encodeText(text);\n }\n\n /**\n * Measure the width of a string of text drawn in this font at a given size.\n * For example:\n * ```js\n * const width = font.widthOfTextAtSize('Foo Bar Qux Baz', 36)\n * ```\n * @param text The string of text to be measured.\n * @param size The font size to be used for this measurement.\n * @returns The width of the string of text when drawn in this font at the\n * given size.\n */\n widthOfTextAtSize(text: string, size: number): number {\n assertIs(text, 'text', ['string']);\n assertIs(size, 'size', ['number']);\n return this.embedder.widthOfTextAtSize(text, size);\n }\n\n /**\n * Measure the height of this font at a given size. For example:\n * ```js\n * const height = font.heightAtSize(24)\n * ```\n *\n * The `options.descender` value controls whether or not the font's\n * descender is included in the height calculation.\n *\n * @param size The font size to be used for this measurement.\n * @param options The options to be used when computing this measurement.\n * @returns The height of this font at the given size.\n */\n heightAtSize(size: number, options?: { descender?: boolean }): number {\n assertIs(size, 'size', ['number']);\n assertOrUndefined(options?.descender, 'options.descender', ['boolean']);\n return this.embedder.heightOfFontAtSize(size, {\n descender: options?.descender ?? true,\n });\n }\n\n /**\n * Compute the font size at which this font is a given height. For example:\n * ```js\n * const fontSize = font.sizeAtHeight(12)\n * ```\n * @param height The height to be used for this calculation.\n * @returns The font size at which this font is the given height.\n */\n sizeAtHeight(height: number): number {\n assertIs(height, 'height', ['number']);\n return this.embedder.sizeOfFontAtHeight(height);\n }\n\n /**\n * Get the set of unicode code points that can be represented by this font.\n * @returns The set of unicode code points supported by this font.\n */\n getCharacterSet(): number[] {\n if (this.embedder instanceof StandardFontEmbedder) {\n return this.embedder.encoding.supportedCodePoints;\n } else {\n return this.embedder.font.characterSet;\n }\n }\n\n /**\n * > **NOTE:** You probably don't need to call this method directly. The\n * > [[PDFDocument.save]] and [[PDFDocument.saveAsBase64]] methods will\n * > automatically ensure all fonts get embedded.\n *\n * Embed this font in its document.\n *\n * @returns Resolves when the embedding is complete.\n */\n async embed(): Promise {\n // TODO: Cleanup orphan embedded objects if a font is embedded multiple times...\n if (this.modified) {\n await this.embedder.embedIntoContext(this.doc.context, this.ref);\n this.modified = false;\n }\n }\n}\n","import Embeddable from 'src/api/Embeddable';\nimport PDFDocument from 'src/api/PDFDocument';\nimport { JpegEmbedder, PDFRef, PngEmbedder } from 'src/core';\nimport { assertIs } from 'src/utils';\n\nexport type ImageEmbedder = JpegEmbedder | PngEmbedder;\n\n/**\n * Represents an image that has been embedded in a [[PDFDocument]].\n */\nexport default class PDFImage implements Embeddable {\n /**\n * > **NOTE:** You probably don't want to call this method directly. Instead,\n * > consider using the [[PDFDocument.embedPng]] and [[PDFDocument.embedJpg]]\n * > methods, which will create instances of [[PDFImage]] for you.\n *\n * Create an instance of [[PDFImage]] from an existing ref and embedder\n *\n * @param ref The unique reference for this image.\n * @param doc The document to which the image will belong.\n * @param embedder The embedder that will be used to embed the image.\n */\n static of = (ref: PDFRef, doc: PDFDocument, embedder: ImageEmbedder) =>\n new PDFImage(ref, doc, embedder);\n\n /** The unique reference assigned to this image within the document. */\n readonly ref: PDFRef;\n\n /** The document to which this image belongs. */\n readonly doc: PDFDocument;\n\n /** The width of this image in pixels. */\n readonly width: number;\n\n /** The height of this image in pixels. */\n readonly height: number;\n\n private embedder: ImageEmbedder | undefined;\n private embedTask: Promise | undefined;\n\n private constructor(ref: PDFRef, doc: PDFDocument, embedder: ImageEmbedder) {\n assertIs(ref, 'ref', [[PDFRef, 'PDFRef']]);\n assertIs(doc, 'doc', [[PDFDocument, 'PDFDocument']]);\n assertIs(embedder, 'embedder', [\n [JpegEmbedder, 'JpegEmbedder'],\n [PngEmbedder, 'PngEmbedder'],\n ]);\n\n this.ref = ref;\n this.doc = doc;\n this.width = embedder.width;\n this.height = embedder.height;\n\n this.embedder = embedder;\n }\n\n /**\n * Compute the width and height of this image after being scaled by the\n * given `factor`. For example:\n * ```js\n * image.width // => 500\n * image.height // => 250\n *\n * const scaled = image.scale(0.5)\n * scaled.width // => 250\n * scaled.height // => 125\n * ```\n * This operation is often useful before drawing an image with\n * [[PDFPage.drawImage]] to compute the `width` and `height` options.\n * @param factor The factor by which this image should be scaled.\n * @returns The width and height of the image after being scaled.\n */\n scale(factor: number) {\n assertIs(factor, 'factor', ['number']);\n return { width: this.width * factor, height: this.height * factor };\n }\n\n /**\n * Get the width and height of this image after scaling it as large as\n * possible while maintaining its aspect ratio and not exceeding the\n * specified `width` and `height`. For example:\n * ```\n * image.width // => 500\n * image.height // => 250\n *\n * const scaled = image.scaleToFit(750, 1000)\n * scaled.width // => 750\n * scaled.height // => 375\n * ```\n * The `width` and `height` parameters can also be thought of as the width\n * and height of a box that the scaled image must fit within.\n * @param width The bounding box's width.\n * @param height The bounding box's height.\n * @returns The width and height of the image after being scaled.\n */\n scaleToFit(width: number, height: number) {\n assertIs(width, 'width', ['number']);\n assertIs(height, 'height', ['number']);\n\n const imgWidthScale = width / this.width;\n const imgHeightScale = height / this.height;\n const scale = Math.min(imgWidthScale, imgHeightScale);\n\n return this.scale(scale);\n }\n\n /**\n * Get the width and height of this image. For example:\n * ```js\n * const { width, height } = image.size()\n * ```\n * @returns The width and height of the image.\n */\n size() {\n return this.scale(1);\n }\n\n /**\n * > **NOTE:** You probably don't need to call this method directly. The\n * > [[PDFDocument.save]] and [[PDFDocument.saveAsBase64]] methods will\n * > automatically ensure all images get embedded.\n *\n * Embed this image in its document.\n *\n * @returns Resolves when the embedding is complete.\n */\n async embed(): Promise {\n if (!this.embedder) return;\n\n // The image should only be embedded once. If there's a pending embed\n // operation then wait on it. Otherwise we need to start the embed.\n if (!this.embedTask) {\n const { doc, ref } = this;\n this.embedTask = this.embedder.embedIntoContext(doc.context, ref);\n }\n await this.embedTask;\n\n // We clear `this.embedder` so that the indirectly referenced image data\n // can be garbage collected, thus avoiding a memory leak.\n // See https://github.com/Hopding/pdf-lib/pull/1032/files.\n this.embedder = undefined;\n }\n}\n","export enum ImageAlignment {\n Left = 0,\n Center = 1,\n Right = 2,\n}\n","import PDFDocument from 'src/api/PDFDocument';\nimport PDFFont from 'src/api/PDFFont';\nimport { AppearanceMapping } from 'src/api/form/appearances';\nimport { Color, colorToComponents, setFillingColor } from 'src/api/colors';\nimport {\n Rotation,\n toDegrees,\n rotateRectangle,\n reduceRotation,\n adjustDimsForRotation,\n degrees,\n} from 'src/api/rotations';\n\nimport {\n PDFRef,\n PDFWidgetAnnotation,\n PDFOperator,\n PDFName,\n PDFDict,\n MethodNotImplementedError,\n AcroFieldFlags,\n PDFAcroTerminal,\n AnnotationFlags,\n} from 'src/core';\nimport { assertIs, assertMultiple, assertOrUndefined } from 'src/utils';\nimport { ImageAlignment } from '../image';\nimport PDFImage from '../PDFImage';\nimport { drawImage, rotateInPlace } from '../operations';\n\nexport interface FieldAppearanceOptions {\n x?: number;\n y?: number;\n width?: number;\n height?: number;\n textColor?: Color;\n backgroundColor?: Color;\n borderColor?: Color;\n borderWidth?: number;\n rotate?: Rotation;\n font?: PDFFont;\n hidden?: boolean;\n}\n\nexport const assertFieldAppearanceOptions = (\n options?: FieldAppearanceOptions,\n) => {\n assertOrUndefined(options?.x, 'options.x', ['number']);\n assertOrUndefined(options?.y, 'options.y', ['number']);\n assertOrUndefined(options?.width, 'options.width', ['number']);\n assertOrUndefined(options?.height, 'options.height', ['number']);\n assertOrUndefined(options?.textColor, 'options.textColor', [\n [Object, 'Color'],\n ]);\n assertOrUndefined(options?.backgroundColor, 'options.backgroundColor', [\n [Object, 'Color'],\n ]);\n assertOrUndefined(options?.borderColor, 'options.borderColor', [\n [Object, 'Color'],\n ]);\n assertOrUndefined(options?.borderWidth, 'options.borderWidth', ['number']);\n assertOrUndefined(options?.rotate, 'options.rotate', [[Object, 'Rotation']]);\n};\n\n/**\n * Represents a field of a [[PDFForm]].\n *\n * This class is effectively abstract. All fields in a [[PDFForm]] will\n * actually be an instance of a subclass of this class.\n *\n * Note that each field in a PDF is represented by a single field object.\n * However, a given field object may be rendered at multiple locations within\n * the document (across one or more pages). The rendering of a field is\n * controlled by its widgets. Each widget causes its field to be displayed at a\n * particular location in the document.\n *\n * Most of the time each field in a PDF has only a single widget, and thus is\n * only rendered once. However, if a field is rendered multiple times, it will\n * have multiple widgets - one for each location it is rendered.\n *\n * This abstraction of field objects and widgets is defined in the PDF\n * specification and dictates how PDF files store fields and where they are\n * to be rendered.\n */\nexport default class PDFField {\n /** The low-level PDFAcroTerminal wrapped by this field. */\n readonly acroField: PDFAcroTerminal;\n\n /** The unique reference assigned to this field within the document. */\n readonly ref: PDFRef;\n\n /** The document to which this field belongs. */\n readonly doc: PDFDocument;\n\n protected constructor(\n acroField: PDFAcroTerminal,\n ref: PDFRef,\n doc: PDFDocument,\n ) {\n assertIs(acroField, 'acroField', [[PDFAcroTerminal, 'PDFAcroTerminal']]);\n assertIs(ref, 'ref', [[PDFRef, 'PDFRef']]);\n assertIs(doc, 'doc', [[PDFDocument, 'PDFDocument']]);\n\n this.acroField = acroField;\n this.ref = ref;\n this.doc = doc;\n }\n\n /**\n * Get the fully qualified name of this field. For example:\n * ```js\n * const fields = form.getFields()\n * fields.forEach(field => {\n * const name = field.getName()\n * console.log('Field name:', name)\n * })\n * ```\n * Note that PDF fields are structured as a tree. Each field is the\n * descendent of a series of ancestor nodes all the way up to the form node,\n * which is always the root of the tree. Each node in the tree (except for\n * the form node) has a partial name. Partial names can be composed of any\n * unicode characters except a period (`.`). The fully qualified name of a\n * field is composed of the partial names of all its ancestors joined\n * with periods. This means that splitting the fully qualified name on\n * periods and taking the last element of the resulting array will give you\n * the partial name of a specific field.\n * @returns The fully qualified name of this field.\n */\n getName(): string {\n return this.acroField.getFullyQualifiedName() ?? '';\n }\n\n /**\n * Returns `true` if this field is read only. This means that PDF readers\n * will not allow users to interact with the field or change its value. See\n * [[PDFField.enableReadOnly]] and [[PDFField.disableReadOnly]].\n * For example:\n * ```js\n * const field = form.getField('some.field')\n * if (field.isReadOnly()) console.log('Read only is enabled')\n * ```\n * @returns Whether or not this is a read only field.\n */\n isReadOnly(): boolean {\n return this.acroField.hasFlag(AcroFieldFlags.ReadOnly);\n }\n\n /**\n * Prevent PDF readers from allowing users to interact with this field or\n * change its value. The field will not respond to mouse or keyboard input.\n * For example:\n * ```js\n * const field = form.getField('some.field')\n * field.enableReadOnly()\n * ```\n * Useful for fields whose values are computed, imported from a database, or\n * prefilled by software before being displayed to the user.\n */\n enableReadOnly() {\n this.acroField.setFlagTo(AcroFieldFlags.ReadOnly, true);\n }\n\n /**\n * Allow users to interact with this field and change its value in PDF\n * readers via mouse and keyboard input. For example:\n * ```js\n * const field = form.getField('some.field')\n * field.disableReadOnly()\n * ```\n */\n disableReadOnly() {\n this.acroField.setFlagTo(AcroFieldFlags.ReadOnly, false);\n }\n\n /**\n * Returns `true` if this field must have a value when the form is submitted.\n * See [[PDFField.enableRequired]] and [[PDFField.disableRequired]].\n * For example:\n * ```js\n * const field = form.getField('some.field')\n * if (field.isRequired()) console.log('Field is required')\n * ```\n * @returns Whether or not this field is required.\n */\n isRequired(): boolean {\n return this.acroField.hasFlag(AcroFieldFlags.Required);\n }\n\n /**\n * Require this field to have a value when the form is submitted.\n * For example:\n * ```js\n * const field = form.getField('some.field')\n * field.enableRequired()\n * ```\n */\n enableRequired() {\n this.acroField.setFlagTo(AcroFieldFlags.Required, true);\n }\n\n /**\n * Do not require this field to have a value when the form is submitted.\n * For example:\n * ```js\n * const field = form.getField('some.field')\n * field.disableRequired()\n * ```\n */\n disableRequired() {\n this.acroField.setFlagTo(AcroFieldFlags.Required, false);\n }\n\n /**\n * Returns `true` if this field's value should be exported when the form is\n * submitted. See [[PDFField.enableExporting]] and\n * [[PDFField.disableExporting]].\n * For example:\n * ```js\n * const field = form.getField('some.field')\n * if (field.isExported()) console.log('Exporting is enabled')\n * ```\n * @returns Whether or not this field's value should be exported.\n */\n isExported(): boolean {\n return !this.acroField.hasFlag(AcroFieldFlags.NoExport);\n }\n\n /**\n * Indicate that this field's value should be exported when the form is\n * submitted in a PDF reader. For example:\n * ```js\n * const field = form.getField('some.field')\n * field.enableExporting()\n * ```\n */\n enableExporting() {\n this.acroField.setFlagTo(AcroFieldFlags.NoExport, false);\n }\n\n /**\n * Indicate that this field's value should **not** be exported when the form\n * is submitted in a PDF reader. For example:\n * ```js\n * const field = form.getField('some.field')\n * field.disableExporting()\n * ```\n */\n disableExporting() {\n this.acroField.setFlagTo(AcroFieldFlags.NoExport, true);\n }\n\n /** @ignore */\n needsAppearancesUpdate(): boolean {\n throw new MethodNotImplementedError(\n this.constructor.name,\n 'needsAppearancesUpdate',\n );\n }\n\n /** @ignore */\n defaultUpdateAppearances(_font: PDFFont) {\n throw new MethodNotImplementedError(\n this.constructor.name,\n 'defaultUpdateAppearances',\n );\n }\n\n protected markAsDirty() {\n this.doc.getForm().markFieldAsDirty(this.ref);\n }\n\n protected markAsClean() {\n this.doc.getForm().markFieldAsClean(this.ref);\n }\n\n protected isDirty(): boolean {\n return this.doc.getForm().fieldIsDirty(this.ref);\n }\n\n protected createWidget(options: {\n x: number;\n y: number;\n width: number;\n height: number;\n textColor?: Color;\n backgroundColor?: Color;\n borderColor?: Color;\n borderWidth: number;\n rotate: Rotation;\n caption?: string;\n hidden?: boolean;\n page?: PDFRef;\n }): PDFWidgetAnnotation {\n const textColor = options.textColor;\n const backgroundColor = options.backgroundColor;\n const borderColor = options.borderColor;\n const borderWidth = options.borderWidth;\n const degreesAngle = toDegrees(options.rotate);\n const caption = options.caption;\n const x = options.x;\n const y = options.y;\n const width = options.width + borderWidth;\n const height = options.height + borderWidth;\n const hidden = Boolean(options.hidden);\n const pageRef = options.page;\n\n assertMultiple(degreesAngle, 'degreesAngle', 90);\n\n // Create a widget for this field\n const widget = PDFWidgetAnnotation.create(this.doc.context, this.ref);\n\n // Set widget properties\n const rect = rotateRectangle(\n { x, y, width, height },\n borderWidth,\n degreesAngle,\n );\n widget.setRectangle(rect);\n\n if (pageRef) widget.setP(pageRef);\n\n const ac = widget.getOrCreateAppearanceCharacteristics();\n if (backgroundColor) {\n ac.setBackgroundColor(colorToComponents(backgroundColor));\n }\n ac.setRotation(degreesAngle);\n if (caption) ac.setCaptions({ normal: caption });\n if (borderColor) ac.setBorderColor(colorToComponents(borderColor));\n\n const bs = widget.getOrCreateBorderStyle();\n if (borderWidth !== undefined) bs.setWidth(borderWidth);\n\n widget.setFlagTo(AnnotationFlags.Print, true);\n widget.setFlagTo(AnnotationFlags.Hidden, hidden);\n widget.setFlagTo(AnnotationFlags.Invisible, false);\n\n // Set acrofield properties\n if (textColor) {\n const da = this.acroField.getDefaultAppearance() ?? '';\n const newDa = da + '\\n' + setFillingColor(textColor).toString();\n this.acroField.setDefaultAppearance(newDa);\n }\n\n return widget;\n }\n\n protected updateWidgetAppearanceWithFont(\n widget: PDFWidgetAnnotation,\n font: PDFFont,\n { normal, rollover, down }: AppearanceMapping,\n ) {\n this.updateWidgetAppearances(widget, {\n normal: this.createAppearanceStream(widget, normal, font),\n rollover: rollover && this.createAppearanceStream(widget, rollover, font),\n down: down && this.createAppearanceStream(widget, down, font),\n });\n }\n\n protected updateOnOffWidgetAppearance(\n widget: PDFWidgetAnnotation,\n onValue: PDFName,\n {\n normal,\n rollover,\n down,\n }: AppearanceMapping<{ on: PDFOperator[]; off: PDFOperator[] }>,\n ) {\n this.updateWidgetAppearances(widget, {\n normal: this.createAppearanceDict(widget, normal, onValue),\n rollover:\n rollover && this.createAppearanceDict(widget, rollover, onValue),\n down: down && this.createAppearanceDict(widget, down, onValue),\n });\n }\n\n protected updateWidgetAppearances(\n widget: PDFWidgetAnnotation,\n { normal, rollover, down }: AppearanceMapping,\n ) {\n widget.setNormalAppearance(normal);\n\n if (rollover) {\n widget.setRolloverAppearance(rollover);\n } else {\n widget.removeRolloverAppearance();\n }\n\n if (down) {\n widget.setDownAppearance(down);\n } else {\n widget.removeDownAppearance();\n }\n }\n\n // // TODO: Do we need to do this...?\n // private foo(font: PDFFont, dict: PDFDict) {\n // if (!dict.lookup(PDFName.of('DR'))) {\n // dict.set(PDFName.of('DR'), dict.context.obj({}));\n // }\n // const DR = dict.lookup(PDFName.of('DR'), PDFDict);\n\n // if (!DR.lookup(PDFName.of('Font'))) {\n // DR.set(PDFName.of('Font'), dict.context.obj({}));\n // }\n // const Font = DR.lookup(PDFName.of('Font'), PDFDict);\n\n // Font.set(PDFName.of(font.name), font.ref);\n // }\n\n private createAppearanceStream(\n widget: PDFWidgetAnnotation,\n appearance: PDFOperator[],\n font?: PDFFont,\n ): PDFRef {\n const { context } = this.acroField.dict;\n const { width, height } = widget.getRectangle();\n\n // TODO: Do we need to do this...?\n // if (font) {\n // this.foo(font, widget.dict);\n // this.foo(font, this.doc.getForm().acroForm.dict);\n // }\n // END TODO\n\n const Resources = font && { Font: { [font.name]: font.ref } };\n const stream = context.formXObject(appearance, {\n Resources,\n BBox: context.obj([0, 0, width, height]),\n Matrix: context.obj([1, 0, 0, 1, 0, 0]),\n });\n const streamRef = context.register(stream);\n\n return streamRef;\n }\n\n /**\n * Create a FormXObject of the supplied image and add it to context.\n * The FormXObject size is calculated based on the widget (including\n * the alignment).\n * @param widget The widget that should display the image.\n * @param alignment The alignment of the image.\n * @param image The image that should be displayed.\n * @returns The ref for the FormXObject that was added to the context.\n */\n protected createImageAppearanceStream(\n widget: PDFWidgetAnnotation,\n image: PDFImage,\n alignment: ImageAlignment,\n ): PDFRef {\n // NOTE: This implementation doesn't handle image borders.\n // NOTE: Acrobat seems to resize the image (maybe even skewing its aspect\n // ratio) to fit perfectly within the widget's rectangle. This method\n // does not currently do that. Should there be an option for that?\n\n const { context } = this.acroField.dict;\n\n const rectangle = widget.getRectangle();\n const ap = widget.getAppearanceCharacteristics();\n const bs = widget.getBorderStyle();\n\n const borderWidth = bs?.getWidth() ?? 0;\n const rotation = reduceRotation(ap?.getRotation());\n\n const rotate = rotateInPlace({ ...rectangle, rotation });\n\n const adj = adjustDimsForRotation(rectangle, rotation);\n const imageDims = image.scaleToFit(\n adj.width - borderWidth * 2,\n adj.height - borderWidth * 2,\n );\n\n // Support borders on images and maybe other properties\n const options = {\n x: borderWidth,\n y: borderWidth,\n width: imageDims.width,\n height: imageDims.height,\n //\n rotate: degrees(0),\n xSkew: degrees(0),\n ySkew: degrees(0),\n };\n\n if (alignment === ImageAlignment.Center) {\n options.x += (adj.width - borderWidth * 2) / 2 - imageDims.width / 2;\n options.y += (adj.height - borderWidth * 2) / 2 - imageDims.height / 2;\n } else if (alignment === ImageAlignment.Right) {\n options.x = adj.width - borderWidth - imageDims.width;\n options.y = adj.height - borderWidth - imageDims.height;\n }\n\n const imageName = this.doc.context.addRandomSuffix('Image', 10);\n const appearance = [...rotate, ...drawImage(imageName, options)];\n ////////////\n\n const Resources = { XObject: { [imageName]: image.ref } };\n const stream = context.formXObject(appearance, {\n Resources,\n BBox: context.obj([0, 0, rectangle.width, rectangle.height]),\n Matrix: context.obj([1, 0, 0, 1, 0, 0]),\n });\n\n return context.register(stream);\n }\n\n private createAppearanceDict(\n widget: PDFWidgetAnnotation,\n appearance: { on: PDFOperator[]; off: PDFOperator[] },\n onValue: PDFName,\n ): PDFDict {\n const { context } = this.acroField.dict;\n\n const onStreamRef = this.createAppearanceStream(widget, appearance.on);\n const offStreamRef = this.createAppearanceStream(widget, appearance.off);\n\n const appearanceDict = context.obj({});\n appearanceDict.set(onValue, onStreamRef);\n appearanceDict.set(PDFName.of('Off'), offStreamRef);\n\n return appearanceDict;\n }\n}\n","import PDFDocument from 'src/api/PDFDocument';\nimport PDFPage from 'src/api/PDFPage';\nimport {\n AppearanceProviderFor,\n normalizeAppearance,\n defaultCheckBoxAppearanceProvider,\n} from 'src/api/form/appearances';\nimport { rgb } from 'src/api/colors';\nimport { degrees } from 'src/api/rotations';\nimport PDFField, {\n FieldAppearanceOptions,\n assertFieldAppearanceOptions,\n} from 'src/api/form/PDFField';\n\nimport {\n PDFName,\n PDFRef,\n PDFDict,\n PDFAcroCheckBox,\n PDFWidgetAnnotation,\n} from 'src/core';\nimport { assertIs, assertOrUndefined } from 'src/utils';\n\n/**\n * Represents a check box field of a [[PDFForm]].\n *\n * [[PDFCheckBox]] fields are interactive boxes that users can click with their\n * mouse. This type of [[PDFField]] has two states: `on` and `off`. The purpose\n * of a check box is to enable users to select from one or more options, where\n * each option is represented by a single check box. Check boxes are typically\n * square in shape and display a check mark when they are in the `on` state.\n */\nexport default class PDFCheckBox extends PDFField {\n /**\n * > **NOTE:** You probably don't want to call this method directly. Instead,\n * > consider using the [[PDFForm.getCheckBox]] method, which will create an\n * > instance of [[PDFCheckBox]] for you.\n *\n * Create an instance of [[PDFCheckBox]] from an existing acroCheckBox and ref\n *\n * @param acroCheckBox The underlying `PDFAcroCheckBox` for this check box.\n * @param ref The unique reference for this check box.\n * @param doc The document to which this check box will belong.\n */\n static of = (acroCheckBox: PDFAcroCheckBox, ref: PDFRef, doc: PDFDocument) =>\n new PDFCheckBox(acroCheckBox, ref, doc);\n\n /** The low-level PDFAcroCheckBox wrapped by this check box. */\n readonly acroField: PDFAcroCheckBox;\n\n private constructor(\n acroCheckBox: PDFAcroCheckBox,\n ref: PDFRef,\n doc: PDFDocument,\n ) {\n super(acroCheckBox, ref, doc);\n\n assertIs(acroCheckBox, 'acroCheckBox', [\n [PDFAcroCheckBox, 'PDFAcroCheckBox'],\n ]);\n\n this.acroField = acroCheckBox;\n }\n\n /**\n * Mark this check box. This operation is analogous to a human user clicking\n * a check box to fill it in a PDF reader. This method will update the\n * underlying state of the check box field to indicate it has been selected.\n * PDF libraries and readers will be able to extract this value from the\n * saved document and determine that it was selected.\n *\n * For example:\n * ```js\n * const checkBox = form.getCheckBox('some.checkBox.field')\n * checkBox.check()\n * ```\n *\n * This method will mark this check box as dirty, causing its appearance\n * streams to be updated when either [[PDFDocument.save]] or\n * [[PDFForm.updateFieldAppearances]] is called. The updated appearance\n * streams will display a check mark inside the widgets of this check box\n * field.\n */\n check() {\n const onValue = this.acroField.getOnValue() ?? PDFName.of('Yes');\n this.markAsDirty();\n this.acroField.setValue(onValue);\n }\n\n /**\n * Clears this check box. This operation is analogous to a human user clicking\n * a check box to unmark it in a PDF reader. This method will update the\n * underlying state of the check box field to indicate it has been deselected.\n * PDF libraries and readers will be able to extract this value from the\n * saved document and determine that it was not selected.\n *\n * For example:\n * ```js\n * const checkBox = form.getCheckBox('some.checkBox.field')\n * checkBox.uncheck()\n * ```\n *\n * This method will mark this check box as dirty. See [[PDFCheckBox.check]]\n * for more details about what this means.\n */\n uncheck() {\n this.markAsDirty();\n this.acroField.setValue(PDFName.of('Off'));\n }\n\n /**\n * Returns `true` if this check box is selected (either by a human user via\n * a PDF reader, or else programmatically via software). For example:\n * ```js\n * const checkBox = form.getCheckBox('some.checkBox.field')\n * if (checkBox.isChecked()) console.log('check box is selected')\n * ```\n * @returns Whether or not this check box is selected.\n */\n isChecked(): boolean {\n const onValue = this.acroField.getOnValue();\n return !!onValue && onValue === this.acroField.getValue();\n }\n\n /**\n * Show this check box on the specified page. For example:\n * ```js\n * const helvetica = await pdfDoc.embedFont(StandardFonts.Helvetica)\n * const page = pdfDoc.addPage()\n *\n * const form = pdfDoc.getForm()\n * const checkBox = form.createCheckBox('some.checkBox.field')\n *\n * checkBox.addToPage(page, {\n * x: 50,\n * y: 75,\n * width: 25,\n * height: 25,\n * textColor: rgb(1, 0, 0),\n * backgroundColor: rgb(0, 1, 0),\n * borderColor: rgb(0, 0, 1),\n * borderWidth: 2,\n * rotate: degrees(90),\n * })\n * ```\n * This will create a new widget for this check box field.\n * @param page The page to which this check box widget should be added.\n * @param options The options to be used when adding this check box widget.\n */\n addToPage(page: PDFPage, options?: FieldAppearanceOptions) {\n assertIs(page, 'page', [[PDFPage, 'PDFPage']]);\n assertFieldAppearanceOptions(options);\n\n if (!options) options = {};\n\n if (!('textColor' in options)) options.textColor = rgb(0, 0, 0);\n if (!('backgroundColor' in options)) options.backgroundColor = rgb(1, 1, 1);\n if (!('borderColor' in options)) options.borderColor = rgb(0, 0, 0);\n if (!('borderWidth' in options)) options.borderWidth = 1;\n\n // Create a widget for this check box\n const widget = this.createWidget({\n x: options.x ?? 0,\n y: options.y ?? 0,\n width: options.width ?? 50,\n height: options.height ?? 50,\n textColor: options.textColor,\n backgroundColor: options.backgroundColor,\n borderColor: options.borderColor,\n borderWidth: options.borderWidth ?? 0,\n rotate: options.rotate ?? degrees(0),\n hidden: options.hidden,\n page: page.ref,\n });\n const widgetRef = this.doc.context.register(widget.dict);\n\n // Add widget to this field\n this.acroField.addWidget(widgetRef);\n\n // Set appearance streams for widget\n widget.setAppearanceState(PDFName.of('Off'));\n this.updateWidgetAppearance(widget, PDFName.of('Yes'));\n\n // Add widget to the given page\n page.node.addAnnot(widgetRef);\n }\n\n /**\n * Returns `true` if any of this check box's widgets do not have an\n * appearance stream for its current state. For example:\n * ```js\n * const checkBox = form.getCheckBox('some.checkBox.field')\n * if (checkBox.needsAppearancesUpdate()) console.log('Needs update')\n * ```\n * @returns Whether or not this check box needs an appearance update.\n */\n needsAppearancesUpdate(): boolean {\n const widgets = this.acroField.getWidgets();\n for (let idx = 0, len = widgets.length; idx < len; idx++) {\n const widget = widgets[idx];\n const state = widget.getAppearanceState();\n const normal = widget.getAppearances()?.normal;\n\n if (!(normal instanceof PDFDict)) return true;\n if (state && !normal.has(state)) return true;\n }\n\n return false;\n }\n\n /**\n * Update the appearance streams for each of this check box's widgets using\n * the default appearance provider for check boxes. For example:\n * ```js\n * const checkBox = form.getCheckBox('some.checkBox.field')\n * checkBox.defaultUpdateAppearances()\n * ```\n */\n defaultUpdateAppearances() {\n this.updateAppearances();\n }\n\n /**\n * Update the appearance streams for each of this check box's widgets using\n * the given appearance provider. If no `provider` is passed, the default\n * appearance provider for check boxs will be used. For example:\n * ```js\n * const checkBox = form.getCheckBox('some.checkBox.field')\n * checkBox.updateAppearances((field, widget) => {\n * ...\n * return {\n * normal: { on: drawCheckBox(...), off: drawCheckBox(...) },\n * down: { on: drawCheckBox(...), off: drawCheckBox(...) },\n * }\n * })\n * ```\n * @param provider Optionally, the appearance provider to be used for\n * generating the contents of the appearance streams.\n */\n updateAppearances(provider?: AppearanceProviderFor) {\n assertOrUndefined(provider, 'provider', [Function]);\n\n const widgets = this.acroField.getWidgets();\n for (let idx = 0, len = widgets.length; idx < len; idx++) {\n const widget = widgets[idx];\n const onValue = widget.getOnValue() ?? PDFName.of('Yes');\n if (!onValue) continue;\n this.updateWidgetAppearance(widget, onValue, provider);\n }\n this.markAsClean();\n }\n\n private updateWidgetAppearance(\n widget: PDFWidgetAnnotation,\n onValue: PDFName,\n provider?: AppearanceProviderFor,\n ) {\n const apProvider = provider ?? defaultCheckBoxAppearanceProvider;\n const appearances = normalizeAppearance(apProvider(this, widget));\n this.updateOnOffWidgetAppearance(widget, onValue, appearances);\n }\n}\n","import PDFDocument from 'src/api/PDFDocument';\nimport PDFPage from 'src/api/PDFPage';\nimport PDFFont from 'src/api/PDFFont';\nimport PDFField, {\n FieldAppearanceOptions,\n assertFieldAppearanceOptions,\n} from 'src/api/form/PDFField';\nimport {\n AppearanceProviderFor,\n normalizeAppearance,\n defaultDropdownAppearanceProvider,\n} from 'src/api/form/appearances';\nimport { rgb } from 'src/api/colors';\nimport { degrees } from 'src/api/rotations';\n\nimport {\n PDFHexString,\n PDFRef,\n PDFString,\n PDFStream,\n PDFWidgetAnnotation,\n PDFAcroComboBox,\n AcroChoiceFlags,\n} from 'src/core';\nimport { assertIs, assertOrUndefined, assertPositive } from 'src/utils';\n\n/**\n * Represents a dropdown field of a [[PDFForm]].\n *\n * [[PDFDropdown]] fields are interactive text boxes that display a single\n * element (the currently selected value). The purpose of a dropdown is to\n * enable users to select a single option from a set of possible options. Users\n * can click on a dropdown to view the full list of options it provides.\n * Clicking on an option in the list will cause it to be selected and displayed\n * in the dropdown's text box. Some dropdowns allow users to enter text\n * directly into the box from their keyboard, rather than only being allowed to\n * choose an option from the list (see [[PDFDropdown.isEditable]]).\n */\nexport default class PDFDropdown extends PDFField {\n /**\n * > **NOTE:** You probably don't want to call this method directly. Instead,\n * > consider using the [[PDFForm.getDropdown]] method, which will create an\n * > instance of [[PDFDropdown]] for you.\n *\n * Create an instance of [[PDFDropdown]] from an existing acroComboBox and ref\n *\n * @param acroComboBox The underlying `PDFAcroComboBox` for this dropdown.\n * @param ref The unique reference for this dropdown.\n * @param doc The document to which this dropdown will belong.\n */\n static of = (acroComboBox: PDFAcroComboBox, ref: PDFRef, doc: PDFDocument) =>\n new PDFDropdown(acroComboBox, ref, doc);\n\n /** The low-level PDFAcroComboBox wrapped by this dropdown. */\n readonly acroField: PDFAcroComboBox;\n\n private constructor(\n acroComboBox: PDFAcroComboBox,\n ref: PDFRef,\n doc: PDFDocument,\n ) {\n super(acroComboBox, ref, doc);\n\n assertIs(acroComboBox, 'acroComboBox', [\n [PDFAcroComboBox, 'PDFAcroComboBox'],\n ]);\n\n this.acroField = acroComboBox;\n }\n\n /**\n * Get the list of available options for this dropdown. These options will be\n * displayed to users who click on this dropdown in a PDF reader.\n * For example:\n * ```js\n * const dropdown = form.getDropdown('some.dropdown.field')\n * const options = dropdown.getOptions()\n * console.log('Dropdown options:', options)\n * ```\n * @returns The options for this dropdown.\n */\n getOptions(): string[] {\n const rawOptions = this.acroField.getOptions();\n\n const options = new Array(rawOptions.length);\n for (let idx = 0, len = options.length; idx < len; idx++) {\n const { display, value } = rawOptions[idx];\n options[idx] = (display ?? value).decodeText();\n }\n\n return options;\n }\n\n /**\n * Get the selected options for this dropdown. These are the values that were\n * selected by a human user via a PDF reader, or programatically via\n * software.\n * For example:\n * ```js\n * const dropdown = form.getDropdown('some.dropdown.field')\n * const selections = dropdown.getSelected()\n * console.log('Dropdown selections:', selections)\n * ```\n * > **NOTE:** Note that PDF readers only display one selected option when\n * > rendering dropdowns. However, the PDF specification does allow for\n * > multiple values to be selected in a dropdown. As such, the `pdf-lib`\n * > API supports this. However, in most cases the array returned by this\n * > method will contain only a single element (or no elements).\n * @returns The selected options in this dropdown.\n */\n getSelected(): string[] {\n const values = this.acroField.getValues();\n\n const selected = new Array(values.length);\n for (let idx = 0, len = values.length; idx < len; idx++) {\n selected[idx] = values[idx].decodeText();\n }\n\n return selected;\n }\n\n /**\n * Set the list of options that are available for this dropdown. These are\n * the values that will be available for users to select when they view this\n * dropdown in a PDF reader. Note that preexisting options for this dropdown\n * will be removed. Only the values passed as `options` will be available to\n * select.\n * For example:\n * ```js\n * const dropdown = form.getDropdown('planets.dropdown')\n * dropdown.setOptions(['Earth', 'Mars', 'Pluto', 'Venus'])\n * ```\n * @param options The options that should be available in this dropdown.\n */\n setOptions(options: string[]) {\n assertIs(options, 'options', [Array]);\n\n const optionObjects = new Array<{ value: PDFHexString }>(options.length);\n for (let idx = 0, len = options.length; idx < len; idx++) {\n optionObjects[idx] = { value: PDFHexString.fromText(options[idx]) };\n }\n this.acroField.setOptions(optionObjects);\n }\n\n /**\n * Add to the list of options that are available for this dropdown. Users\n * will be able to select these values in a PDF reader. In addition to the\n * values passed as `options`, any preexisting options for this dropdown will\n * still be available for users to select.\n * For example:\n * ```js\n * const dropdown = form.getDropdown('rockets.dropdown')\n * dropdown.addOptions(['Saturn IV', 'Falcon Heavy'])\n * ```\n * @param options New options that should be available in this dropdown.\n */\n addOptions(options: string | string[]) {\n assertIs(options, 'options', ['string', Array]);\n\n const optionsArr = Array.isArray(options) ? options : [options];\n\n const existingOptions: {\n value: PDFString | PDFHexString;\n display?: PDFString | PDFHexString;\n }[] = this.acroField.getOptions();\n\n const newOptions = new Array<{ value: PDFHexString }>(optionsArr.length);\n for (let idx = 0, len = optionsArr.length; idx < len; idx++) {\n newOptions[idx] = { value: PDFHexString.fromText(optionsArr[idx]) };\n }\n\n this.acroField.setOptions(existingOptions.concat(newOptions));\n }\n\n /**\n * Select one or more values for this dropdown. This operation is analogous\n * to a human user opening the dropdown in a PDF reader and clicking on a\n * value to select it. This method will update the underlying state of the\n * dropdown to indicate which values have been selected. PDF libraries and\n * readers will be able to extract these values from the saved document and\n * determine which values were selected.\n *\n * For example:\n * ```js\n * const dropdown = form.getDropdown('best.superhero.dropdown')\n * dropdown.select('One Punch Man')\n * ```\n *\n * This method will mark this dropdown as dirty, causing its appearance\n * streams to be updated when either [[PDFDocument.save]] or\n * [[PDFForm.updateFieldAppearances]] is called. The updated streams will\n * display the selected option inside the widgets of this dropdown.\n *\n * **IMPORTANT:** The default font used to update appearance streams is\n * [[StandardFonts.Helvetica]]. Note that this is a WinAnsi font. This means\n * that encoding errors will be thrown if the selected option for this field\n * contains characters outside the WinAnsi character set (the latin alphabet).\n *\n * Embedding a custom font and passing it to\n * [[PDFForm.updateFieldAppearances]] or [[PDFDropdown.updateAppearances]]\n * allows you to generate appearance streams with characters outside the\n * latin alphabet (assuming the custom font supports them).\n *\n * Selecting an option that does not exist in this dropdown's option list\n * (see [[PDFDropdown.getOptions]]) will enable editing on this dropdown\n * (see [[PDFDropdown.enableEditing]]).\n *\n * > **NOTE:** PDF readers only display one selected option when rendering\n * > dropdowns. However, the PDF specification does allow for multiple values\n * > to be selected in a dropdown. As such, the `pdf-lib` API supports this.\n * > However, it is not recommended to select more than one value with this\n * > method, as only one will be visible. [[PDFOptionList]] fields are better\n * > suited for displaying multiple selected values.\n *\n * @param options The options to be selected.\n * @param merge Whether or not existing selections should be preserved.\n */\n select(options: string | string[], merge = false) {\n assertIs(options, 'options', ['string', Array]);\n assertIs(merge, 'merge', ['boolean']);\n\n const optionsArr = Array.isArray(options) ? options : [options];\n\n const validOptions = this.getOptions();\n const hasCustomOption = optionsArr.find(\n (option) => !validOptions.includes(option),\n );\n if (hasCustomOption) this.enableEditing();\n\n this.markAsDirty();\n\n if (optionsArr.length > 1 || (optionsArr.length === 1 && merge)) {\n this.enableMultiselect();\n }\n\n const values = new Array(optionsArr.length);\n for (let idx = 0, len = optionsArr.length; idx < len; idx++) {\n values[idx] = PDFHexString.fromText(optionsArr[idx]);\n }\n\n if (merge) {\n const existingValues = this.acroField.getValues();\n this.acroField.setValues(existingValues.concat(values));\n } else {\n this.acroField.setValues(values);\n }\n }\n\n /**\n * Clear all selected values for this dropdown. This operation is equivalent\n * to selecting an empty list. This method will update the underlying state\n * of the dropdown to indicate that no values have been selected.\n * For example:\n * ```js\n * const dropdown = form.getDropdown('some.dropdown.field')\n * dropdown.clear()\n * ```\n * This method will mark this text field as dirty. See [[PDFDropdown.select]]\n * for more details about what this means.\n */\n clear() {\n this.markAsDirty();\n this.acroField.setValues([]);\n }\n\n /**\n * Set the font size for this field. Larger font sizes will result in larger\n * text being displayed when PDF readers render this dropdown. Font sizes may\n * be integer or floating point numbers. Supplying a negative font size will\n * cause this method to throw an error.\n *\n * For example:\n * ```js\n * const dropdown = form.getDropdown('some.dropdown.field')\n * dropdown.setFontSize(4)\n * dropdown.setFontSize(15.7)\n * ```\n *\n * > This method depends upon the existence of a default appearance\n * > (`/DA`) string. If this field does not have a default appearance string,\n * > or that string does not contain a font size (via the `Tf` operator),\n * > then this method will throw an error.\n *\n * @param fontSize The font size to be used when rendering text in this field.\n */\n setFontSize(fontSize: number) {\n assertPositive(fontSize, 'fontSize');\n this.acroField.setFontSize(fontSize);\n this.markAsDirty();\n }\n\n /**\n * Returns `true` if users are allowed to edit the selected value of this\n * dropdown directly and are not constrained by the list of available\n * options. See [[PDFDropdown.enableEditing]] and\n * [[PDFDropdown.disableEditing]]. For example:\n * ```js\n * const dropdown = form.getDropdown('some.dropdown.field')\n * if (dropdown.isEditable()) console.log('Editing is enabled')\n * ```\n * @returns Whether or not this dropdown is editable.\n */\n isEditable(): boolean {\n return this.acroField.hasFlag(AcroChoiceFlags.Edit);\n }\n\n /**\n * Allow users to edit the selected value of this dropdown in PDF readers\n * with their keyboard. This means that the selected value of this dropdown\n * will not be constrained by the list of available options. However, if this\n * dropdown has any available options, users will still be allowed to select\n * from that list.\n * For example:\n * ```js\n * const dropdown = form.getDropdown('some.dropdown.field')\n * dropdown.enableEditing()\n * ```\n */\n enableEditing() {\n this.acroField.setFlagTo(AcroChoiceFlags.Edit, true);\n }\n\n /**\n * Do not allow users to edit the selected value of this dropdown in PDF\n * readers with their keyboard. This will constrain the selected value of\n * this dropdown to the list of available options. Users will only be able\n * to select an option from that list.\n * For example:\n * ```js\n * const dropdown = form.getDropdown('some.dropdown.field')\n * dropdown.disableEditing()\n * ```\n */\n disableEditing() {\n this.acroField.setFlagTo(AcroChoiceFlags.Edit, false);\n }\n\n /**\n * Returns `true` if the option list of this dropdown is always displayed\n * in alphabetical order, irrespective of the order in which the options\n * were added to the dropdown. See [[PDFDropdown.enableSorting]] and\n * [[PDFDropdown.disableSorting]]. For example:\n * ```js\n * const dropdown = form.getDropdown('some.dropdown.field')\n * if (dropdown.isSorted()) console.log('Sorting is enabled')\n * ```\n * @returns Whether or not this dropdown's options are sorted.\n */\n isSorted(): boolean {\n return this.acroField.hasFlag(AcroChoiceFlags.Sort);\n }\n\n /**\n * Always display the option list of this dropdown in alphabetical order,\n * irrespective of the order in which the options were added to this dropdown.\n * For example:\n * ```js\n * const dropdown = form.getDropdown('some.dropdown.field')\n * dropdown.enableSorting()\n * ```\n */\n enableSorting() {\n this.acroField.setFlagTo(AcroChoiceFlags.Sort, true);\n }\n\n /**\n * Do not always display the option list of this dropdown in alphabetical\n * order. Instead, display the options in whichever order they were added\n * to the list. For example:\n * ```js\n * const dropdown = form.getDropdown('some.dropdown.field')\n * dropdown.disableSorting()\n * ```\n */\n disableSorting() {\n this.acroField.setFlagTo(AcroChoiceFlags.Sort, false);\n }\n\n /**\n * Returns `true` if multiple options can be selected from this dropdown's\n * option list. See [[PDFDropdown.enableMultiselect]] and\n * [[PDFDropdown.disableMultiselect]]. For example:\n * ```js\n * const dropdown = form.getDropdown('some.dropdown.field')\n * if (dropdown.isMultiselect()) console.log('Multiselect is enabled')\n * ```\n * @returns Whether or not multiple options can be selected.\n */\n isMultiselect(): boolean {\n return this.acroField.hasFlag(AcroChoiceFlags.MultiSelect);\n }\n\n /**\n * Allow users to select more than one option from this dropdown's option\n * list. For example:\n * ```js\n * const dropdown = form.getDropdown('some.dropdown.field')\n * dropdown.enableMultiselect()\n * ```\n */\n enableMultiselect() {\n this.acroField.setFlagTo(AcroChoiceFlags.MultiSelect, true);\n }\n\n /**\n * Do not allow users to select more than one option from this dropdown's\n * option list. For example:\n * ```js\n * const dropdown = form.getDropdown('some.dropdown.field')\n * dropdown.disableMultiselect()\n * ```\n */\n disableMultiselect() {\n this.acroField.setFlagTo(AcroChoiceFlags.MultiSelect, false);\n }\n\n /**\n * Returns `true` if the selected option should be spell checked by PDF\n * readers. Spell checking will only be performed if this dropdown allows\n * editing (see [[PDFDropdown.isEditable]]). See\n * [[PDFDropdown.enableSpellChecking]] and\n * [[PDFDropdown.disableSpellChecking]]. For example:\n * ```js\n * const dropdown = form.getDropdown('some.dropdown.field')\n * if (dropdown.isSpellChecked()) console.log('Spell checking is enabled')\n * ```\n * @returns Whether or not this dropdown can be spell checked.\n */\n isSpellChecked(): boolean {\n return !this.acroField.hasFlag(AcroChoiceFlags.DoNotSpellCheck);\n }\n\n /**\n * Allow PDF readers to spell check the selected option of this dropdown.\n * For example:\n * ```js\n * const dropdown = form.getDropdown('some.dropdown.field')\n * dropdown.enableSpellChecking()\n * ```\n */\n enableSpellChecking() {\n this.acroField.setFlagTo(AcroChoiceFlags.DoNotSpellCheck, false);\n }\n\n /**\n * Do not allow PDF readers to spell check the selected option of this\n * dropdown. For example:\n * ```js\n * const dropdown = form.getDropdown('some.dropdown.field')\n * dropdown.disableSpellChecking()\n * ```\n */\n disableSpellChecking() {\n this.acroField.setFlagTo(AcroChoiceFlags.DoNotSpellCheck, true);\n }\n\n /**\n * Returns `true` if the option selected by a user is stored, or \"committed\",\n * when the user clicks the option. The alternative is that the user's\n * selection is stored when the user leaves this dropdown field (by clicking\n * outside of it - on another field, for example). See\n * [[PDFDropdown.enableSelectOnClick]] and\n * [[PDFDropdown.disableSelectOnClick]]. For example:\n * ```js\n * const dropdown = form.getDropdown('some.dropdown.field')\n * if (dropdown.isSelectOnClick()) console.log('Select on click is enabled')\n * ```\n * @returns Whether or not options are selected immediately after they are\n * clicked.\n */\n isSelectOnClick(): boolean {\n return this.acroField.hasFlag(AcroChoiceFlags.CommitOnSelChange);\n }\n\n /**\n * Store the option selected by a user immediately after the user clicks the\n * option. Do not wait for the user to leave this dropdown field (by clicking\n * outside of it - on another field, for example). For example:\n * ```js\n * const dropdown = form.getDropdown('some.dropdown.field')\n * dropdown.enableSelectOnClick()\n * ```\n */\n enableSelectOnClick() {\n this.acroField.setFlagTo(AcroChoiceFlags.CommitOnSelChange, true);\n }\n\n /**\n * Wait to store the option selected by a user until they leave this dropdown\n * field (by clicking outside of it - on another field, for example).\n * For example:\n * ```js\n * const dropdown = form.getDropdown('some.dropdown.field')\n * dropdown.disableSelectOnClick()\n * ```\n */\n disableSelectOnClick() {\n this.acroField.setFlagTo(AcroChoiceFlags.CommitOnSelChange, false);\n }\n\n /**\n * Show this dropdown on the specified page. For example:\n * ```js\n * const ubuntuFont = await pdfDoc.embedFont(ubuntuFontBytes)\n * const page = pdfDoc.addPage()\n *\n * const form = pdfDoc.getForm()\n * const dropdown = form.createDropdown('best.gundam')\n * dropdown.setOptions(['Exia', 'Dynames'])\n * dropdown.select('Exia')\n *\n * dropdown.addToPage(page, {\n * x: 50,\n * y: 75,\n * width: 200,\n * height: 100,\n * textColor: rgb(1, 0, 0),\n * backgroundColor: rgb(0, 1, 0),\n * borderColor: rgb(0, 0, 1),\n * borderWidth: 2,\n * rotate: degrees(90),\n * font: ubuntuFont,\n * })\n * ```\n * This will create a new widget for this dropdown field.\n * @param page The page to which this dropdown widget should be added.\n * @param options The options to be used when adding this dropdown widget.\n */\n addToPage(page: PDFPage, options?: FieldAppearanceOptions) {\n assertIs(page, 'page', [[PDFPage, 'PDFPage']]);\n assertFieldAppearanceOptions(options);\n\n if (!options) options = {};\n\n if (!('textColor' in options)) options.textColor = rgb(0, 0, 0);\n if (!('backgroundColor' in options)) options.backgroundColor = rgb(1, 1, 1);\n if (!('borderColor' in options)) options.borderColor = rgb(0, 0, 0);\n if (!('borderWidth' in options)) options.borderWidth = 1;\n\n // Create a widget for this dropdown\n const widget = this.createWidget({\n x: options.x ?? 0,\n y: options.y ?? 0,\n width: options.width ?? 200,\n height: options.height ?? 50,\n textColor: options.textColor,\n backgroundColor: options.backgroundColor,\n borderColor: options.borderColor,\n borderWidth: options.borderWidth ?? 0,\n rotate: options.rotate ?? degrees(0),\n hidden: options.hidden,\n page: page.ref,\n });\n const widgetRef = this.doc.context.register(widget.dict);\n\n // Add widget to this field\n this.acroField.addWidget(widgetRef);\n\n // Set appearance streams for widget\n const font = options.font ?? this.doc.getForm().getDefaultFont();\n this.updateWidgetAppearance(widget, font);\n\n // Add widget to the given page\n page.node.addAnnot(widgetRef);\n }\n\n /**\n * Returns `true` if this dropdown has been marked as dirty, or if any of\n * this dropdown's widgets do not have an appearance stream. For example:\n * ```js\n * const dropdown = form.getDropdown('some.dropdown.field')\n * if (dropdown.needsAppearancesUpdate()) console.log('Needs update')\n * ```\n * @returns Whether or not this dropdown needs an appearance update.\n */\n needsAppearancesUpdate(): boolean {\n if (this.isDirty()) return true;\n\n const widgets = this.acroField.getWidgets();\n for (let idx = 0, len = widgets.length; idx < len; idx++) {\n const widget = widgets[idx];\n const hasAppearances =\n widget.getAppearances()?.normal instanceof PDFStream;\n if (!hasAppearances) return true;\n }\n\n return false;\n }\n\n /**\n * Update the appearance streams for each of this dropdown's widgets using\n * the default appearance provider for dropdowns. For example:\n * ```js\n * const helvetica = await pdfDoc.embedFont(StandardFonts.Helvetica)\n * const dropdown = form.getDropdown('some.dropdown.field')\n * dropdown.defaultUpdateAppearances(helvetica)\n * ```\n * @param font The font to be used for creating the appearance streams.\n */\n defaultUpdateAppearances(font: PDFFont) {\n assertIs(font, 'font', [[PDFFont, 'PDFFont']]);\n this.updateAppearances(font);\n }\n\n /**\n * Update the appearance streams for each of this dropdown's widgets using\n * the given appearance provider. If no `provider` is passed, the default\n * appearance provider for dropdowns will be used. For example:\n * ```js\n * const helvetica = await pdfDoc.embedFont(StandardFonts.Helvetica)\n * const dropdown = form.getDropdown('some.dropdown.field')\n * dropdown.updateAppearances(helvetica, (field, widget, font) => {\n * ...\n * return drawTextField(...)\n * })\n * ```\n * @param font The font to be used for creating the appearance streams.\n * @param provider Optionally, the appearance provider to be used for\n * generating the contents of the appearance streams.\n */\n updateAppearances(\n font: PDFFont,\n provider?: AppearanceProviderFor,\n ) {\n assertIs(font, 'font', [[PDFFont, 'PDFFont']]);\n assertOrUndefined(provider, 'provider', [Function]);\n\n const widgets = this.acroField.getWidgets();\n for (let idx = 0, len = widgets.length; idx < len; idx++) {\n const widget = widgets[idx];\n this.updateWidgetAppearance(widget, font, provider);\n }\n this.markAsClean();\n }\n\n // getOption(index: number): string {}\n // getSelectedIndices(): number[] {}\n // removeOptions(option: string | string[]) {}\n // removeIndices(option: number[]) {}\n // deselect(options: string | string[]) {}\n // deselectIndices(optionIndices: number[]) {}\n\n private updateWidgetAppearance(\n widget: PDFWidgetAnnotation,\n font: PDFFont,\n provider?: AppearanceProviderFor,\n ) {\n const apProvider = provider ?? defaultDropdownAppearanceProvider;\n const appearances = normalizeAppearance(apProvider(this, widget, font));\n this.updateWidgetAppearanceWithFont(widget, font, appearances);\n }\n}\n","import PDFDocument from 'src/api/PDFDocument';\nimport PDFPage from 'src/api/PDFPage';\nimport PDFFont from 'src/api/PDFFont';\nimport PDFField, {\n FieldAppearanceOptions,\n assertFieldAppearanceOptions,\n} from 'src/api/form/PDFField';\nimport {\n AppearanceProviderFor,\n normalizeAppearance,\n defaultOptionListAppearanceProvider,\n} from 'src/api/form/appearances';\nimport { rgb } from 'src/api/colors';\nimport { degrees } from 'src/api/rotations';\n\nimport {\n PDFRef,\n PDFHexString,\n PDFString,\n PDFStream,\n PDFAcroListBox,\n AcroChoiceFlags,\n PDFWidgetAnnotation,\n} from 'src/core';\nimport {\n assertIs,\n assertIsSubset,\n assertOrUndefined,\n assertPositive,\n} from 'src/utils';\n\n/**\n * Represents an option list field of a [[PDFForm]].\n *\n * [[PDFOptionList]] fields are interactive lists of options. The purpose of an\n * option list is to enable users to select one or more options from a set of\n * possible options. Users are able to see the full set of options without\n * first having to click on the field (though scrolling may be necessary).\n * Clicking an option in the list will cause it to be selected and displayed\n * with a highlighted background. Some option lists allow users to select\n * more than one option (see [[PDFOptionList.isMultiselect]]).\n */\nexport default class PDFOptionList extends PDFField {\n /**\n * > **NOTE:** You probably don't want to call this method directly. Instead,\n * > consider using the [[PDFForm.getOptionList]] method, which will create\n * > an instance of [[PDFOptionList]] for you.\n *\n * Create an instance of [[PDFOptionList]] from an existing acroListBox and\n * ref\n *\n * @param acroComboBox The underlying `PDFAcroListBox` for this option list.\n * @param ref The unique reference for this option list.\n * @param doc The document to which this option list will belong.\n */\n static of = (acroListBox: PDFAcroListBox, ref: PDFRef, doc: PDFDocument) =>\n new PDFOptionList(acroListBox, ref, doc);\n\n /** The low-level PDFAcroListBox wrapped by this option list. */\n readonly acroField: PDFAcroListBox;\n\n private constructor(\n acroListBox: PDFAcroListBox,\n ref: PDFRef,\n doc: PDFDocument,\n ) {\n super(acroListBox, ref, doc);\n\n assertIs(acroListBox, 'acroListBox', [[PDFAcroListBox, 'PDFAcroListBox']]);\n\n this.acroField = acroListBox;\n }\n\n /**\n * Get the list of available options for this option list. These options will\n * be displayed to users who view this option list in a PDF reader.\n * For example:\n * ```js\n * const optionList = form.getOptionList('some.optionList.field')\n * const options = optionList.getOptions()\n * console.log('Option List options:', options)\n * ```\n * @returns The options for this option list.\n */\n getOptions(): string[] {\n const rawOptions = this.acroField.getOptions();\n\n const options = new Array(rawOptions.length);\n for (let idx = 0, len = options.length; idx < len; idx++) {\n const { display, value } = rawOptions[idx];\n options[idx] = (display ?? value).decodeText();\n }\n\n return options;\n }\n\n /**\n * Get the selected options for this option list. These are the values that\n * were selected by a human user via a PDF reader, or programatically via\n * software.\n * For example:\n * ```js\n * const optionList = form.getOptionList('some.optionList.field')\n * const selections = optionList.getSelected()\n * console.log('Option List selections:', selections)\n * ```\n * @returns The selected options for this option list.\n */\n getSelected(): string[] {\n const values = this.acroField.getValues();\n\n const selected = new Array(values.length);\n for (let idx = 0, len = values.length; idx < len; idx++) {\n selected[idx] = values[idx].decodeText();\n }\n\n return selected;\n }\n\n /**\n * Set the list of options that are available for this option list. These are\n * the values that will be available for users to select when they view this\n * option list in a PDF reader. Note that preexisting options for this\n * option list will be removed. Only the values passed as `options` will be\n * available to select.\n *\n * For example:\n * ```js\n * const optionList = form.getOptionList('planets.optionList')\n * optionList.setOptions(['Earth', 'Mars', 'Pluto', 'Venus'])\n * ```\n *\n * This method will mark this option list as dirty, causing its appearance\n * streams to be updated when either [[PDFDocument.save]] or\n * [[PDFForm.updateFieldAppearances]] is called. The updated streams will\n * display the options this field contains inside the widgets of this text\n * field (with selected options highlighted).\n *\n * **IMPORTANT:** The default font used to update appearance streams is\n * [[StandardFonts.Helvetica]]. Note that this is a WinAnsi font. This means\n * that encoding errors will be thrown if this field contains any options\n * with characters outside the WinAnsi character set (the latin alphabet).\n *\n * Embedding a custom font and passing it to\n * [[PDFForm.updateFieldAppearances]] or [[PDFOptionList.updateAppearances]]\n * allows you to generate appearance streams with characters outside the\n * latin alphabet (assuming the custom font supports them).\n *\n * @param options The options that should be available in this option list.\n */\n setOptions(options: string[]) {\n assertIs(options, 'options', [Array]);\n\n this.markAsDirty();\n const optionObjects = new Array<{ value: PDFHexString }>(options.length);\n for (let idx = 0, len = options.length; idx < len; idx++) {\n optionObjects[idx] = { value: PDFHexString.fromText(options[idx]) };\n }\n this.acroField.setOptions(optionObjects);\n }\n\n /**\n * Add to the list of options that are available for this option list. Users\n * will be able to select these values in a PDF reader. In addition to the\n * values passed as `options`, any preexisting options for this option list\n * will still be available for users to select.\n * For example:\n * ```js\n * const optionList = form.getOptionList('rockets.optionList')\n * optionList.addOptions(['Saturn IV', 'Falcon Heavy'])\n * ```\n * This method will mark this option list as dirty. See\n * [[PDFOptionList.setOptions]] for more details about what this means.\n * @param options New options that should be available in this option list.\n */\n addOptions(options: string | string[]) {\n assertIs(options, 'options', ['string', Array]);\n\n this.markAsDirty();\n\n const optionsArr = Array.isArray(options) ? options : [options];\n\n const existingOptions: {\n value: PDFString | PDFHexString;\n display?: PDFString | PDFHexString;\n }[] = this.acroField.getOptions();\n\n const newOptions = new Array<{ value: PDFHexString }>(optionsArr.length);\n for (let idx = 0, len = optionsArr.length; idx < len; idx++) {\n newOptions[idx] = { value: PDFHexString.fromText(optionsArr[idx]) };\n }\n\n this.acroField.setOptions(existingOptions.concat(newOptions));\n }\n\n /**\n * Select one or more values for this option list. This operation is analogous\n * to a human user opening the option list in a PDF reader and clicking on one\n * or more values to select them. This method will update the underlying state\n * of the option list to indicate which values have been selected. PDF\n * libraries and readers will be able to extract these values from the saved\n * document and determine which values were selected.\n * For example:\n * ```js\n * const optionList = form.getOptionList('best.superheroes.optionList')\n * optionList.select(['One Punch Man', 'Iron Man'])\n * ```\n * This method will mark this option list as dirty. See\n * [[PDFOptionList.setOptions]] for more details about what this means.\n * @param options The options to be selected.\n * @param merge Whether or not existing selections should be preserved.\n */\n select(options: string | string[], merge = false) {\n assertIs(options, 'options', ['string', Array]);\n assertIs(merge, 'merge', ['boolean']);\n\n const optionsArr = Array.isArray(options) ? options : [options];\n\n const validOptions = this.getOptions();\n assertIsSubset(optionsArr, 'option', validOptions);\n\n this.markAsDirty();\n\n if (optionsArr.length > 1 || (optionsArr.length === 1 && merge)) {\n this.enableMultiselect();\n }\n\n const values = new Array(optionsArr.length);\n for (let idx = 0, len = optionsArr.length; idx < len; idx++) {\n values[idx] = PDFHexString.fromText(optionsArr[idx]);\n }\n\n if (merge) {\n const existingValues = this.acroField.getValues();\n this.acroField.setValues(existingValues.concat(values));\n } else {\n this.acroField.setValues(values);\n }\n }\n\n /**\n * Clear all selected values for this option list. This operation is\n * equivalent to selecting an empty list. This method will update the\n * underlying state of the option list to indicate that no values have been\n * selected.\n * For example:\n * ```js\n * const optionList = form.getOptionList('some.optionList.field')\n * optionList.clear()\n * ```\n * This method will mark this option list as dirty. See\n * [[PDFOptionList.setOptions]] for more details about what this means.\n */\n clear() {\n this.markAsDirty();\n this.acroField.setValues([]);\n }\n\n /**\n * Set the font size for the text in this field. There needs to be a\n * default appearance string (DA) set with a font value specified\n * for this to work. For example:\n * ```js\n * const optionList = form.getOptionList('some.optionList.field')\n * optionList.setFontSize(4);\n * ```\n * @param fontSize The font size to set the font to.\n */\n\n /**\n * Set the font size for this field. Larger font sizes will result in larger\n * text being displayed when PDF readers render this option list. Font sizes\n * may be integer or floating point numbers. Supplying a negative font size\n * will cause this method to throw an error.\n *\n * For example:\n * ```js\n * const optionList = form.getOptionList('some.optionList.field')\n * optionList.setFontSize(4)\n * optionList.setFontSize(15.7)\n * ```\n *\n * > This method depends upon the existence of a default appearance\n * > (`/DA`) string. If this field does not have a default appearance string,\n * > or that string does not contain a font size (via the `Tf` operator),\n * > then this method will throw an error.\n *\n * @param fontSize The font size to be used when rendering text in this field.\n */\n setFontSize(fontSize: number) {\n assertPositive(fontSize, 'fontSize');\n this.acroField.setFontSize(fontSize);\n this.markAsDirty();\n }\n\n /**\n * Returns `true` if the options of this option list are always displayed\n * in alphabetical order, irrespective of the order in which the options\n * were added to the option list. See [[PDFOptionList.enableSorting]] and\n * [[PDFOptionList.disableSorting]]. For example:\n * ```js\n * const optionList = form.getOptionList('some.optionList.field')\n * if (optionList.isSorted()) console.log('Sorting is enabled')\n * ```\n * @returns Whether or not this option list is sorted.\n */\n isSorted(): boolean {\n return this.acroField.hasFlag(AcroChoiceFlags.Sort);\n }\n\n /**\n * Always display the options of this option list in alphabetical order,\n * irrespective of the order in which the options were added to this option\n * list.\n * For example:\n * ```js\n * const optionList = form.getOptionList('some.optionList.field')\n * optionList.enableSorting()\n * ```\n */\n enableSorting() {\n this.acroField.setFlagTo(AcroChoiceFlags.Sort, true);\n }\n\n /**\n * Do not always display the options of this option list in alphabetical\n * order. Instead, display the options in whichever order they were added\n * to this option list. For example:\n * ```js\n * const optionList = form.getOptionList('some.optionList.field')\n * optionList.disableSorting()\n * ```\n */\n disableSorting() {\n this.acroField.setFlagTo(AcroChoiceFlags.Sort, false);\n }\n\n /**\n * Returns `true` if multiple options can be selected from this option list.\n * See [[PDFOptionList.enableMultiselect]] and\n * [[PDFOptionList.disableMultiselect]]. For example:\n * ```js\n * const optionList = form.getOptionList('some.optionList.field')\n * if (optionList.isMultiselect()) console.log('Multiselect is enabled')\n * ```\n * @returns Whether or not multiple options can be selected.\n */\n isMultiselect(): boolean {\n return this.acroField.hasFlag(AcroChoiceFlags.MultiSelect);\n }\n\n /**\n * Allow users to select more than one option from this option list.\n * For example:\n * ```js\n * const optionList = form.getOptionList('some.optionList.field')\n * optionList.enableMultiselect()\n * ```\n */\n enableMultiselect() {\n this.acroField.setFlagTo(AcroChoiceFlags.MultiSelect, true);\n }\n\n /**\n * Do not allow users to select more than one option from this option list.\n * For example:\n * ```js\n * const optionList = form.getOptionList('some.optionList.field')\n * optionList.disableMultiselect()\n * ```\n */\n disableMultiselect() {\n this.acroField.setFlagTo(AcroChoiceFlags.MultiSelect, false);\n }\n\n /**\n * Returns `true` if the option selected by a user is stored, or \"committed\",\n * when the user clicks the option. The alternative is that the user's\n * selection is stored when the user leaves this option list field (by\n * clicking outside of it - on another field, for example). See\n * [[PDFOptionList.enableSelectOnClick]] and\n * [[PDFOptionList.disableSelectOnClick]]. For example:\n * ```js\n * const optionList = form.getOptionList('some.optionList.field')\n * if (optionList.isSelectOnClick()) console.log('Select on click is enabled')\n * ```\n * @returns Whether or not options are selected immediately after they are\n * clicked.\n */\n isSelectOnClick(): boolean {\n return this.acroField.hasFlag(AcroChoiceFlags.CommitOnSelChange);\n }\n\n /**\n * Store the option selected by a user immediately after the user clicks the\n * option. Do not wait for the user to leave this option list field (by\n * clicking outside of it - on another field, for example). For example:\n * ```js\n * const optionList = form.getOptionList('some.optionList.field')\n * optionList.enableSelectOnClick()\n * ```\n */\n enableSelectOnClick() {\n this.acroField.setFlagTo(AcroChoiceFlags.CommitOnSelChange, true);\n }\n\n /**\n * Wait to store the option selected by a user until they leave this option\n * list field (by clicking outside of it - on another field, for example).\n * For example:\n * ```js\n * const optionList = form.getOptionList('some.optionList.field')\n * optionList.disableSelectOnClick()\n * ```\n */\n disableSelectOnClick() {\n this.acroField.setFlagTo(AcroChoiceFlags.CommitOnSelChange, false);\n }\n\n /**\n * Show this option list on the specified page. For example:\n * ```js\n * const ubuntuFont = await pdfDoc.embedFont(ubuntuFontBytes)\n * const page = pdfDoc.addPage()\n *\n * const form = pdfDoc.getForm()\n * const optionList = form.createOptionList('best.gundams')\n * optionList.setOptions(['Exia', 'Dynames', 'Kyrios', 'Virtue'])\n * optionList.select(['Exia', 'Virtue'])\n *\n * optionList.addToPage(page, {\n * x: 50,\n * y: 75,\n * width: 200,\n * height: 100,\n * textColor: rgb(1, 0, 0),\n * backgroundColor: rgb(0, 1, 0),\n * borderColor: rgb(0, 0, 1),\n * borderWidth: 2,\n * rotate: degrees(90),\n * font: ubuntuFont,\n * })\n * ```\n * This will create a new widget for this option list field.\n * @param page The page to which this option list widget should be added.\n * @param options The options to be used when adding this option list widget.\n */\n addToPage(page: PDFPage, options?: FieldAppearanceOptions) {\n assertIs(page, 'page', [[PDFPage, 'PDFPage']]);\n assertFieldAppearanceOptions(options);\n\n if (!options) options = {};\n\n if (!('textColor' in options)) options.textColor = rgb(0, 0, 0);\n if (!('backgroundColor' in options)) options.backgroundColor = rgb(1, 1, 1);\n if (!('borderColor' in options)) options.borderColor = rgb(0, 0, 0);\n if (!('borderWidth' in options)) options.borderWidth = 1;\n\n // Create a widget for this option list\n const widget = this.createWidget({\n x: options.x ?? 0,\n y: options.y ?? 0,\n width: options.width ?? 200,\n height: options.height ?? 100,\n textColor: options.textColor,\n backgroundColor: options.backgroundColor,\n borderColor: options.borderColor,\n borderWidth: options.borderWidth ?? 0,\n rotate: options.rotate ?? degrees(0),\n hidden: options.hidden,\n page: page.ref,\n });\n const widgetRef = this.doc.context.register(widget.dict);\n\n // Add widget to this field\n this.acroField.addWidget(widgetRef);\n\n // Set appearance streams for widget\n const font = options.font ?? this.doc.getForm().getDefaultFont();\n this.updateWidgetAppearance(widget, font);\n\n // Add widget to the given page\n page.node.addAnnot(widgetRef);\n }\n\n /**\n * Returns `true` if this option list has been marked as dirty, or if any of\n * this option list's widgets do not have an appearance stream. For example:\n * ```js\n * const optionList = form.getOptionList('some.optionList.field')\n * if (optionList.needsAppearancesUpdate()) console.log('Needs update')\n * ```\n * @returns Whether or not this option list needs an appearance update.\n */\n needsAppearancesUpdate(): boolean {\n if (this.isDirty()) return true;\n\n const widgets = this.acroField.getWidgets();\n for (let idx = 0, len = widgets.length; idx < len; idx++) {\n const widget = widgets[idx];\n const hasAppearances =\n widget.getAppearances()?.normal instanceof PDFStream;\n if (!hasAppearances) return true;\n }\n\n return false;\n }\n\n /**\n * Update the appearance streams for each of this option list's widgets using\n * the default appearance provider for option lists. For example:\n * ```js\n * const helvetica = await pdfDoc.embedFont(StandardFonts.Helvetica)\n * const optionList = form.getOptionList('some.optionList.field')\n * optionList.defaultUpdateAppearances(helvetica)\n * ```\n * @param font The font to be used for creating the appearance streams.\n */\n defaultUpdateAppearances(font: PDFFont) {\n assertIs(font, 'font', [[PDFFont, 'PDFFont']]);\n this.updateAppearances(font);\n }\n\n /**\n * Update the appearance streams for each of this option list's widgets using\n * the given appearance provider. If no `provider` is passed, the default\n * appearance provider for option lists will be used. For example:\n * ```js\n * const helvetica = await pdfDoc.embedFont(StandardFonts.Helvetica)\n * const optionList = form.getOptionList('some.optionList.field')\n * optionList.updateAppearances(helvetica, (field, widget, font) => {\n * ...\n * return drawOptionList(...)\n * })\n * ```\n * @param font The font to be used for creating the appearance streams.\n * @param provider Optionally, the appearance provider to be used for\n * generating the contents of the appearance streams.\n */\n updateAppearances(\n font: PDFFont,\n provider?: AppearanceProviderFor,\n ) {\n assertIs(font, 'font', [[PDFFont, 'PDFFont']]);\n assertOrUndefined(provider, 'provider', [Function]);\n\n const widgets = this.acroField.getWidgets();\n for (let idx = 0, len = widgets.length; idx < len; idx++) {\n const widget = widgets[idx];\n this.updateWidgetAppearance(widget, font, provider);\n }\n this.markAsClean();\n }\n\n // getOption(index: number): string {}\n // getSelectedIndices(): number[] {}\n // removeOptions(option: string | string[]) {}\n // removeIndices(option: number[]) {}\n // deselect(options: string | string[]) {}\n // deselectIndices(optionIndices: number[]) {}\n\n private updateWidgetAppearance(\n widget: PDFWidgetAnnotation,\n font: PDFFont,\n provider?: AppearanceProviderFor,\n ) {\n const apProvider = provider ?? defaultOptionListAppearanceProvider;\n const appearances = normalizeAppearance(apProvider(this, widget, font));\n this.updateWidgetAppearanceWithFont(widget, font, appearances);\n }\n}\n","import PDFDocument from 'src/api/PDFDocument';\nimport PDFPage from 'src/api/PDFPage';\nimport PDFField, {\n FieldAppearanceOptions,\n assertFieldAppearanceOptions,\n} from 'src/api/form/PDFField';\nimport {\n AppearanceProviderFor,\n normalizeAppearance,\n defaultRadioGroupAppearanceProvider,\n} from 'src/api/form/appearances';\nimport { rgb } from 'src/api/colors';\nimport { degrees } from 'src/api/rotations';\n\nimport {\n PDFName,\n PDFRef,\n PDFHexString,\n PDFDict,\n PDFWidgetAnnotation,\n PDFAcroRadioButton,\n AcroButtonFlags,\n} from 'src/core';\nimport { assertIs, assertOrUndefined, assertIsOneOf } from 'src/utils';\n\n/**\n * Represents a radio group field of a [[PDFForm]].\n *\n * [[PDFRadioGroup]] fields are collections of radio buttons. The purpose of a\n * radio group is to enable users to select one option from a set of mutually\n * exclusive choices. Each choice in a radio group is represented by a radio\n * button. Radio buttons each have two states: `on` and `off`. At most one\n * radio button in a group may be in the `on` state at any time. Users can\n * click on a radio button to select it (and thereby automatically deselect any\n * other radio button that might have already been selected). Some radio\n * groups allow users to toggle a selected radio button `off` by clicking on\n * it (see [[PDFRadioGroup.isOffToggleable]]).\n *\n * Note that some radio groups allow multiple radio buttons to be in the `on`\n * state at the same type **if** they represent the same underlying value (see\n * [[PDFRadioGroup.isMutuallyExclusive]]).\n */\nexport default class PDFRadioGroup extends PDFField {\n /**\n * > **NOTE:** You probably don't want to call this method directly. Instead,\n * > consider using the [[PDFForm.getOptionList]] method, which will create an\n * > instance of [[PDFOptionList]] for you.\n *\n * Create an instance of [[PDFOptionList]] from an existing acroRadioButton\n * and ref\n *\n * @param acroRadioButton The underlying `PDFAcroRadioButton` for this\n * radio group.\n * @param ref The unique reference for this radio group.\n * @param doc The document to which this radio group will belong.\n */\n static of = (\n acroRadioButton: PDFAcroRadioButton,\n ref: PDFRef,\n doc: PDFDocument,\n ) => new PDFRadioGroup(acroRadioButton, ref, doc);\n\n /** The low-level PDFAcroRadioButton wrapped by this radio group. */\n readonly acroField: PDFAcroRadioButton;\n\n private constructor(\n acroRadioButton: PDFAcroRadioButton,\n ref: PDFRef,\n doc: PDFDocument,\n ) {\n super(acroRadioButton, ref, doc);\n\n assertIs(acroRadioButton, 'acroRadioButton', [\n [PDFAcroRadioButton, 'PDFAcroRadioButton'],\n ]);\n\n this.acroField = acroRadioButton;\n }\n\n /**\n * Get the list of available options for this radio group. Each option is\n * represented by a radio button. These radio buttons are displayed at\n * various locations in the document, potentially on different pages (though\n * typically they are stacked horizontally or vertically on the same page).\n * For example:\n * ```js\n * const radioGroup = form.getRadioGroup('some.radioGroup.field')\n * const options = radioGroup.getOptions()\n * console.log('Radio Group options:', options)\n * ```\n * @returns The options for this radio group.\n */\n getOptions(): string[] {\n const exportValues = this.acroField.getExportValues();\n if (exportValues) {\n const exportOptions = new Array(exportValues.length);\n for (let idx = 0, len = exportValues.length; idx < len; idx++) {\n exportOptions[idx] = exportValues[idx].decodeText();\n }\n return exportOptions;\n }\n\n const onValues = this.acroField.getOnValues();\n const onOptions = new Array(onValues.length);\n for (let idx = 0, len = onOptions.length; idx < len; idx++) {\n onOptions[idx] = onValues[idx].decodeText();\n }\n return onOptions;\n }\n\n /**\n * Get the selected option for this radio group. The selected option is\n * represented by the radio button in this group that is turned on. At most\n * one radio button in a group can be selected. If no buttons in this group\n * are selected, `undefined` is returned.\n * For example:\n * ```js\n * const radioGroup = form.getRadioGroup('some.radioGroup.field')\n * const selected = radioGroup.getSelected()\n * console.log('Selected radio button:', selected)\n * ```\n * @returns The selected option for this radio group.\n */\n getSelected(): string | undefined {\n const value = this.acroField.getValue();\n if (value === PDFName.of('Off')) return undefined;\n const exportValues = this.acroField.getExportValues();\n if (exportValues) {\n const onValues = this.acroField.getOnValues();\n for (let idx = 0, len = onValues.length; idx < len; idx++) {\n if (onValues[idx] === value) return exportValues[idx].decodeText();\n }\n }\n return value.decodeText();\n }\n\n // // TODO: Figure out why this seems to crash Acrobat. Maybe it's because we\n // // aren't removing the widget reference from the page's Annots?\n // removeOption(option: string) {\n // assertIs(option, 'option', ['string']);\n // // TODO: Assert is valid `option`!\n\n // const onValues = this.acroField.getOnValues();\n // const exportValues = this.acroField.getExportValues();\n // if (exportValues) {\n // for (let idx = 0, len = exportValues.length; idx < len; idx++) {\n // if (exportValues[idx].decodeText() === option) {\n // this.acroField.removeWidget(idx);\n // this.acroField.removeExportValue(idx);\n // }\n // }\n // } else {\n // for (let idx = 0, len = onValues.length; idx < len; idx++) {\n // const value = onValues[idx];\n // if (value.decodeText() === option) {\n // this.acroField.removeWidget(idx);\n // this.acroField.removeExportValue(idx);\n // }\n // }\n // }\n // }\n\n /**\n * Select an option for this radio group. This operation is analogous to a\n * human user clicking one of the radio buttons in this group via a PDF\n * reader to toggle it on. This method will update the underlying state of\n * the radio group to indicate which option has been selected. PDF libraries\n * and readers will be able to extract this value from the saved document and\n * determine which option was selected.\n *\n * For example:\n * ```js\n * const radioGroup = form.getRadioGroup('best.superhero.radioGroup')\n * radioGroup.select('One Punch Man')\n * ```\n *\n * This method will mark this radio group as dirty, causing its appearance\n * streams to be updated when either [[PDFDocument.save]] or\n * [[PDFForm.updateFieldAppearances]] is called. The updated appearance\n * streams will display a dot inside the widget of this check box field\n * that represents the selected option.\n *\n * @param option The option to be selected.\n */\n select(option: string) {\n assertIs(option, 'option', ['string']);\n\n const validOptions = this.getOptions();\n assertIsOneOf(option, 'option', validOptions);\n\n this.markAsDirty();\n\n const onValues = this.acroField.getOnValues();\n const exportValues = this.acroField.getExportValues();\n if (exportValues) {\n for (let idx = 0, len = exportValues.length; idx < len; idx++) {\n if (exportValues[idx].decodeText() === option) {\n this.acroField.setValue(onValues[idx]);\n }\n }\n } else {\n for (let idx = 0, len = onValues.length; idx < len; idx++) {\n const value = onValues[idx];\n if (value.decodeText() === option) this.acroField.setValue(value);\n }\n }\n }\n\n /**\n * Clear any selected option for this dropdown. This will result in all\n * radio buttons in this group being toggled off. This method will update\n * the underlying state of the dropdown to indicate that no radio buttons\n * have been selected.\n * For example:\n * ```js\n * const radioGroup = form.getRadioGroup('some.radioGroup.field')\n * radioGroup.clear()\n * ```\n * This method will mark this radio group as dirty. See\n * [[PDFRadioGroup.select]] for more details about what this means.\n */\n clear() {\n this.markAsDirty();\n this.acroField.setValue(PDFName.of('Off'));\n }\n\n /**\n * Returns `true` if users can click on radio buttons in this group to toggle\n * them off. The alternative is that once a user clicks on a radio button\n * to select it, the only way to deselect it is by selecting on another radio\n * button in the group. See [[PDFRadioGroup.enableOffToggling]] and\n * [[PDFRadioGroup.disableOffToggling]]. For example:\n * ```js\n * const radioGroup = form.getRadioGroup('some.radioGroup.field')\n * if (radioGroup.isOffToggleable()) console.log('Off toggling is enabled')\n * ```\n */\n isOffToggleable() {\n return !this.acroField.hasFlag(AcroButtonFlags.NoToggleToOff);\n }\n\n /**\n * Allow users to click on selected radio buttons in this group to toggle\n * them off. For example:\n * ```js\n * const radioGroup = form.getRadioGroup('some.radioGroup.field')\n * radioGroup.enableOffToggling()\n * ```\n * > **NOTE:** This feature is documented in the PDF specification\n * > (Table 226). However, most PDF readers do not respect this option and\n * > prevent users from toggling radio buttons off even when it is enabled.\n * > At the time of this writing (9/6/2020) Mac's Preview software did\n * > respect the option. Adobe Acrobat, Foxit Reader, and Google Chrome did\n * > not.\n */\n enableOffToggling() {\n this.acroField.setFlagTo(AcroButtonFlags.NoToggleToOff, false);\n }\n\n /**\n * Prevent users from clicking on selected radio buttons in this group to\n * toggle them off. Clicking on a selected radio button will have no effect.\n * The only way to deselect a selected radio button is to click on a\n * different radio button in the group. For example:\n * ```js\n * const radioGroup = form.getRadioGroup('some.radioGroup.field')\n * radioGroup.disableOffToggling()\n * ```\n */\n disableOffToggling() {\n this.acroField.setFlagTo(AcroButtonFlags.NoToggleToOff, true);\n }\n\n /**\n * Returns `true` if the radio buttons in this group are mutually exclusive.\n * This means that when the user selects a radio button, only that specific\n * button will be turned on. Even if other radio buttons in the group\n * represent the same value, they will not be enabled. The alternative to\n * this is that clicking a radio button will select that button along with\n * any other radio buttons in the group that share the same value. See\n * [[PDFRadioGroup.enableMutualExclusion]] and\n * [[PDFRadioGroup.disableMutualExclusion]].\n * For example:\n * ```js\n * const radioGroup = form.getRadioGroup('some.radioGroup.field')\n * if (radioGroup.isMutuallyExclusive()) console.log('Mutual exclusion is enabled')\n * ```\n */\n isMutuallyExclusive() {\n return !this.acroField.hasFlag(AcroButtonFlags.RadiosInUnison);\n }\n\n /**\n * When the user clicks a radio button in this group it will be selected. In\n * addition, any other radio buttons in this group that share the same\n * underlying value will also be selected. For example:\n * ```js\n * const radioGroup = form.getRadioGroup('some.radioGroup.field')\n * radioGroup.enableMutualExclusion()\n * ```\n * Note that this option must be enabled prior to adding options to the\n * radio group. It does not currently apply retroactively to existing\n * radio buttons in the group.\n */\n enableMutualExclusion() {\n this.acroField.setFlagTo(AcroButtonFlags.RadiosInUnison, false);\n }\n\n /**\n * When the user clicks a radio button in this group only it will be selected.\n * No other radio buttons in the group will be selected, even if they share\n * the same underlying value. For example:\n * ```js\n * const radioGroup = form.getRadioGroup('some.radioGroup.field')\n * radioGroup.disableMutualExclusion()\n * ```\n * Note that this option must be disabled prior to adding options to the\n * radio group. It does not currently apply retroactively to existing\n * radio buttons in the group.\n */\n disableMutualExclusion() {\n this.acroField.setFlagTo(AcroButtonFlags.RadiosInUnison, true);\n }\n\n /**\n * Add a new radio button to this group on the specified page. For example:\n * ```js\n * const page = pdfDoc.addPage()\n *\n * const form = pdfDoc.getForm()\n * const radioGroup = form.createRadioGroup('best.gundam')\n *\n * const options = {\n * x: 50,\n * width: 25,\n * height: 25,\n * textColor: rgb(1, 0, 0),\n * backgroundColor: rgb(0, 1, 0),\n * borderColor: rgb(0, 0, 1),\n * borderWidth: 2,\n * rotate: degrees(90),\n * }\n *\n * radioGroup.addOptionToPage('Exia', page, { ...options, y: 50 })\n * radioGroup.addOptionToPage('Dynames', page, { ...options, y: 110 })\n * ```\n * This will create a new radio button widget for this radio group field.\n * @param option The option that the radio button widget represents.\n * @param page The page to which the radio button widget should be added.\n * @param options The options to be used when adding the radio button widget.\n */\n addOptionToPage(\n option: string,\n page: PDFPage,\n options?: FieldAppearanceOptions,\n ) {\n assertIs(option, 'option', ['string']);\n assertIs(page, 'page', [[PDFPage, 'PDFPage']]);\n assertFieldAppearanceOptions(options);\n\n // Create a widget for this radio button\n const widget = this.createWidget({\n x: options?.x ?? 0,\n y: options?.y ?? 0,\n width: options?.width ?? 50,\n height: options?.height ?? 50,\n textColor: options?.textColor ?? rgb(0, 0, 0),\n backgroundColor: options?.backgroundColor ?? rgb(1, 1, 1),\n borderColor: options?.borderColor ?? rgb(0, 0, 0),\n borderWidth: options?.borderWidth ?? 1,\n rotate: options?.rotate ?? degrees(0),\n hidden: options?.hidden,\n page: page.ref,\n });\n const widgetRef = this.doc.context.register(widget.dict);\n\n // Add widget to this field\n const apStateValue = this.acroField.addWidgetWithOpt(\n widgetRef,\n PDFHexString.fromText(option),\n !this.isMutuallyExclusive(),\n );\n\n // Set appearance streams for widget\n widget.setAppearanceState(PDFName.of('Off'));\n this.updateWidgetAppearance(widget, apStateValue);\n\n // Add widget to the given page\n page.node.addAnnot(widgetRef);\n }\n\n /**\n * Returns `true` if any of this group's radio button widgets do not have an\n * appearance stream for their current state. For example:\n * ```js\n * const radioGroup = form.getRadioGroup('some.radioGroup.field')\n * if (radioGroup.needsAppearancesUpdate()) console.log('Needs update')\n * ```\n * @returns Whether or not this radio group needs an appearance update.\n */\n needsAppearancesUpdate(): boolean {\n const widgets = this.acroField.getWidgets();\n for (let idx = 0, len = widgets.length; idx < len; idx++) {\n const widget = widgets[idx];\n const state = widget.getAppearanceState();\n const normal = widget.getAppearances()?.normal;\n\n if (!(normal instanceof PDFDict)) return true;\n if (state && !normal.has(state)) return true;\n }\n\n return false;\n }\n\n /**\n * Update the appearance streams for each of this group's radio button widgets\n * using the default appearance provider for radio groups. For example:\n * ```js\n * const radioGroup = form.getRadioGroup('some.radioGroup.field')\n * radioGroup.defaultUpdateAppearances()\n * ```\n */\n defaultUpdateAppearances() {\n this.updateAppearances();\n }\n\n // rg.updateAppearances((field: any, widget: any) => {\n // assert(field === rg);\n // assert(widget instanceof PDFWidgetAnnotation);\n // return { on: [...rectangle, ...circle], off: [...rectangle, ...circle] };\n // });\n\n /**\n * Update the appearance streams for each of this group's radio button widgets\n * using the given appearance provider. If no `provider` is passed, the\n * default appearance provider for radio groups will be used. For example:\n * ```js\n * const radioGroup = form.getRadioGroup('some.radioGroup.field')\n * radioGroup.updateAppearances((field, widget) => {\n * ...\n * return {\n * normal: { on: drawRadioButton(...), off: drawRadioButton(...) },\n * down: { on: drawRadioButton(...), off: drawRadioButton(...) },\n * }\n * })\n * ```\n * @param provider Optionally, the appearance provider to be used for\n * generating the contents of the appearance streams.\n */\n updateAppearances(provider?: AppearanceProviderFor) {\n assertOrUndefined(provider, 'provider', [Function]);\n\n const widgets = this.acroField.getWidgets();\n for (let idx = 0, len = widgets.length; idx < len; idx++) {\n const widget = widgets[idx];\n const onValue = widget.getOnValue();\n if (!onValue) continue;\n this.updateWidgetAppearance(widget, onValue, provider);\n }\n }\n\n private updateWidgetAppearance(\n widget: PDFWidgetAnnotation,\n onValue: PDFName,\n provider?: AppearanceProviderFor,\n ) {\n const apProvider = provider ?? defaultRadioGroupAppearanceProvider;\n const appearances = normalizeAppearance(apProvider(this, widget));\n this.updateOnOffWidgetAppearance(widget, onValue, appearances);\n }\n}\n","import PDFDocument from 'src/api/PDFDocument';\nimport PDFField from 'src/api/form/PDFField';\n\nimport { PDFRef, PDFAcroSignature } from 'src/core';\nimport { assertIs } from 'src/utils';\n\n/**\n * Represents a signature field of a [[PDFForm]].\n *\n * [[PDFSignature]] fields are digital signatures. `pdf-lib` does not\n * currently provide any specialized APIs for creating digital signatures or\n * reading the contents of existing digital signatures.\n */\nexport default class PDFSignature extends PDFField {\n /**\n * > **NOTE:** You probably don't want to call this method directly. Instead,\n * > consider using the [[PDFForm.getSignature]] method, which will create an\n * > instance of [[PDFSignature]] for you.\n *\n * Create an instance of [[PDFSignature]] from an existing acroSignature and\n * ref\n *\n * @param acroSignature The underlying `PDFAcroSignature` for this signature.\n * @param ref The unique reference for this signature.\n * @param doc The document to which this signature will belong.\n */\n static of = (\n acroSignature: PDFAcroSignature,\n ref: PDFRef,\n doc: PDFDocument,\n ) => new PDFSignature(acroSignature, ref, doc);\n\n /** The low-level PDFAcroSignature wrapped by this signature. */\n readonly acroField: PDFAcroSignature;\n\n private constructor(\n acroSignature: PDFAcroSignature,\n ref: PDFRef,\n doc: PDFDocument,\n ) {\n super(acroSignature, ref, doc);\n\n assertIs(acroSignature, 'acroSignature', [\n [PDFAcroSignature, 'PDFAcroSignature'],\n ]);\n\n this.acroField = acroSignature;\n }\n\n needsAppearancesUpdate() {\n return false;\n }\n}\n","import PDFDocument from 'src/api/PDFDocument';\nimport PDFPage from 'src/api/PDFPage';\nimport PDFFont from 'src/api/PDFFont';\nimport PDFImage from 'src/api/PDFImage';\nimport PDFField, {\n FieldAppearanceOptions,\n assertFieldAppearanceOptions,\n} from 'src/api/form/PDFField';\nimport {\n AppearanceProviderFor,\n normalizeAppearance,\n defaultTextFieldAppearanceProvider,\n} from 'src/api/form/appearances';\nimport { rgb } from 'src/api/colors';\nimport { degrees } from 'src/api/rotations';\nimport {\n RichTextFieldReadError,\n ExceededMaxLengthError,\n InvalidMaxLengthError,\n} from 'src/api/errors';\nimport { ImageAlignment } from 'src/api/image/alignment';\nimport { TextAlignment } from 'src/api/text/alignment';\n\nimport {\n PDFHexString,\n PDFRef,\n PDFStream,\n PDFAcroText,\n AcroTextFlags,\n PDFWidgetAnnotation,\n} from 'src/core';\nimport {\n assertIs,\n assertIsOneOf,\n assertOrUndefined,\n assertPositive,\n assertRangeOrUndefined,\n} from 'src/utils';\n\n/**\n * Represents a text field of a [[PDFForm]].\n *\n * [[PDFTextField]] fields are boxes that display text entered by the user. The\n * purpose of a text field is to enable users to enter text or view text values\n * in the document prefilled by software. Users can click on a text field and\n * input text via their keyboard. Some text fields allow multiple lines of text\n * to be entered (see [[PDFTextField.isMultiline]]).\n */\nexport default class PDFTextField extends PDFField {\n /**\n * > **NOTE:** You probably don't want to call this method directly. Instead,\n * > consider using the [[PDFForm.getTextField]] method, which will create an\n * > instance of [[PDFTextField]] for you.\n *\n * Create an instance of [[PDFTextField]] from an existing acroText and ref\n *\n * @param acroText The underlying `PDFAcroText` for this text field.\n * @param ref The unique reference for this text field.\n * @param doc The document to which this text field will belong.\n */\n static of = (acroText: PDFAcroText, ref: PDFRef, doc: PDFDocument) =>\n new PDFTextField(acroText, ref, doc);\n\n /** The low-level PDFAcroText wrapped by this text field. */\n readonly acroField: PDFAcroText;\n\n private constructor(acroText: PDFAcroText, ref: PDFRef, doc: PDFDocument) {\n super(acroText, ref, doc);\n\n assertIs(acroText, 'acroText', [[PDFAcroText, 'PDFAcroText']]);\n\n this.acroField = acroText;\n }\n\n /**\n * Get the text that this field contains. This text is visible to users who\n * view this field in a PDF reader.\n *\n * For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * const text = textField.getText()\n * console.log('Text field contents:', text)\n * ```\n *\n * Note that if this text field contains no underlying value, `undefined`\n * will be returned. Text fields may also contain an underlying value that\n * is simply an empty string (`''`). This detail is largely irrelevant for\n * most applications. In general, you'll want to treat both cases the same\n * way and simply consider the text field to be empty. In either case, the\n * text field will appear empty to users when viewed in a PDF reader.\n *\n * An error will be thrown if this is a rich text field. `pdf-lib` does not\n * support reading rich text fields. Nor do most PDF readers and writers.\n * Rich text fields are based on XFA (XML Forms Architecture). Relatively few\n * PDFs use rich text fields or XFA. Unlike PDF itself, XFA is not an ISO\n * standard. XFA has been deprecated in PDF 2.0:\n * * https://en.wikipedia.org/wiki/XFA\n * * http://blog.pdfshareforms.com/pdf-2-0-release-bid-farewell-xfa-forms/\n *\n * @returns The text contained in this text field.\n */\n getText(): string | undefined {\n const value = this.acroField.getValue();\n if (!value && this.isRichFormatted()) {\n throw new RichTextFieldReadError(this.getName());\n }\n return value?.decodeText();\n }\n\n /**\n * Set the text for this field. This operation is analogous to a human user\n * clicking on the text field in a PDF reader and typing in text via their\n * keyboard. This method will update the underlying state of the text field\n * to indicate what text has been set. PDF libraries and readers will be able\n * to extract these values from the saved document and determine what text\n * was set.\n *\n * For example:\n * ```js\n * const textField = form.getTextField('best.superhero.text.field')\n * textField.setText('One Punch Man')\n * ```\n *\n * This method will mark this text field as dirty, causing its appearance\n * streams to be updated when either [[PDFDocument.save]] or\n * [[PDFForm.updateFieldAppearances]] is called. The updated streams will\n * display the text this field contains inside the widgets of this text\n * field.\n *\n * **IMPORTANT:** The default font used to update appearance streams is\n * [[StandardFonts.Helvetica]]. Note that this is a WinAnsi font. This means\n * that encoding errors will be thrown if this field contains text outside\n * the WinAnsi character set (the latin alphabet).\n *\n * Embedding a custom font and passing it to\n * [[PDFForm.updateFieldAppearances]] or [[PDFTextField.updateAppearances]]\n * allows you to generate appearance streams with characters outside the\n * latin alphabet (assuming the custom font supports them).\n *\n * If this is a rich text field, it will be converted to a standard text\n * field in order to set the text. `pdf-lib` does not support writing rich\n * text strings. Nor do most PDF readers and writers. See\n * [[PDFTextField.getText]] for more information about rich text fields and\n * their deprecation in PDF 2.0.\n *\n * @param text The text this field should contain.\n */\n setText(text: string | undefined) {\n assertOrUndefined(text, 'text', ['string']);\n\n const maxLength = this.getMaxLength();\n if (maxLength !== undefined && text && text.length > maxLength) {\n throw new ExceededMaxLengthError(text.length, maxLength, this.getName());\n }\n\n this.markAsDirty();\n this.disableRichFormatting();\n\n if (text) {\n this.acroField.setValue(PDFHexString.fromText(text));\n } else {\n this.acroField.removeValue();\n }\n }\n\n /**\n * Get the alignment for this text field. This value represents the\n * justification of the text when it is displayed to the user in PDF readers.\n * There are three possible alignments: left, center, and right. For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * const alignment = textField.getAlignment()\n * if (alignment === TextAlignment.Left) console.log('Text is left justified')\n * if (alignment === TextAlignment.Center) console.log('Text is centered')\n * if (alignment === TextAlignment.Right) console.log('Text is right justified')\n * ```\n * @returns The alignment of this text field.\n */\n getAlignment(): TextAlignment {\n const quadding = this.acroField.getQuadding();\n\n // prettier-ignore\n return (\n quadding === 0 ? TextAlignment.Left\n : quadding === 1 ? TextAlignment.Center\n : quadding === 2 ? TextAlignment.Right\n : TextAlignment.Left\n );\n }\n\n /**\n * Set the alignment for this text field. This will determine the\n * justification of the text when it is displayed to the user in PDF readers.\n * There are three possible alignments: left, center, and right. For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n *\n * // Text will be left justified when displayed\n * textField.setAlignment(TextAlignment.Left)\n *\n * // Text will be centered when displayed\n * textField.setAlignment(TextAlignment.Center)\n *\n * // Text will be right justified when displayed\n * textField.setAlignment(TextAlignment.Right)\n * ```\n * This method will mark this text field as dirty. See\n * [[PDFTextField.setText]] for more details about what this means.\n * @param alignment The alignment for this text field.\n */\n setAlignment(alignment: TextAlignment) {\n assertIsOneOf(alignment, 'alignment', TextAlignment);\n this.markAsDirty();\n this.acroField.setQuadding(alignment);\n }\n\n /**\n * Get the maximum length of this field. This value represents the maximum\n * number of characters that can be typed into this field by the user. If\n * this field does not have a maximum length, `undefined` is returned.\n * For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * const maxLength = textField.getMaxLength()\n * if (maxLength === undefined) console.log('No max length')\n * else console.log(`Max length is ${maxLength}`)\n * ```\n * @returns The maximum number of characters allowed in this field, or\n * `undefined` if no limit exists.\n */\n getMaxLength(): number | undefined {\n return this.acroField.getMaxLength();\n }\n\n /**\n * Set the maximum length of this field. This limits the number of characters\n * that can be typed into this field by the user. This also limits the length\n * of the string that can be passed to [[PDFTextField.setText]]. This limit\n * can be removed by passing `undefined` as `maxLength`. For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n *\n * // Allow between 0 and 5 characters to be entered\n * textField.setMaxLength(5)\n *\n * // Allow any number of characters to be entered\n * textField.setMaxLength(undefined)\n * ```\n * This method will mark this text field as dirty. See\n * [[PDFTextField.setText]] for more details about what this means.\n * @param maxLength The maximum number of characters allowed in this field, or\n * `undefined` to remove the limit.\n */\n setMaxLength(maxLength?: number) {\n assertRangeOrUndefined(maxLength, 'maxLength', 0, Number.MAX_SAFE_INTEGER);\n\n this.markAsDirty();\n\n if (maxLength === undefined) {\n this.acroField.removeMaxLength();\n } else {\n const text = this.getText();\n if (text && text.length > maxLength) {\n throw new InvalidMaxLengthError(text.length, maxLength, this.getName());\n }\n this.acroField.setMaxLength(maxLength);\n }\n }\n\n /**\n * Remove the maximum length for this text field. This allows any number of\n * characters to be typed into this field by the user. For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * textField.removeMaxLength()\n * ```\n * Calling this method is equivalent to passing `undefined` to\n * [[PDFTextField.setMaxLength]].\n */\n removeMaxLength() {\n this.markAsDirty();\n this.acroField.removeMaxLength();\n }\n\n /**\n * Display an image inside the bounds of this text field's widgets. For example:\n * ```js\n * const pngImage = await pdfDoc.embedPng(...)\n * const textField = form.getTextField('some.text.field')\n * textField.setImage(pngImage)\n * ```\n * This will update the appearances streams for each of this text field's widgets.\n * @param image The image that should be displayed.\n */\n setImage(image: PDFImage) {\n const fieldAlignment = this.getAlignment();\n\n // prettier-ignore\n const alignment = \n fieldAlignment === TextAlignment.Center ? ImageAlignment.Center\n : fieldAlignment === TextAlignment.Right ? ImageAlignment.Right\n : ImageAlignment.Left;\n\n const widgets = this.acroField.getWidgets();\n for (let idx = 0, len = widgets.length; idx < len; idx++) {\n const widget = widgets[idx];\n const streamRef = this.createImageAppearanceStream(\n widget,\n image,\n alignment,\n );\n this.updateWidgetAppearances(widget, { normal: streamRef });\n }\n\n this.markAsClean();\n }\n\n /**\n * Set the font size for this field. Larger font sizes will result in larger\n * text being displayed when PDF readers render this text field. Font sizes\n * may be integer or floating point numbers. Supplying a negative font size\n * will cause this method to throw an error.\n *\n * For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * textField.setFontSize(4)\n * textField.setFontSize(15.7)\n * ```\n *\n * > This method depends upon the existence of a default appearance\n * > (`/DA`) string. If this field does not have a default appearance string,\n * > or that string does not contain a font size (via the `Tf` operator),\n * > then this method will throw an error.\n *\n * @param fontSize The font size to be used when rendering text in this field.\n */\n setFontSize(fontSize: number) {\n assertPositive(fontSize, 'fontSize');\n this.acroField.setFontSize(fontSize);\n this.markAsDirty();\n }\n\n /**\n * Returns `true` if each line of text is shown on a new line when this\n * field is displayed in a PDF reader. The alternative is that all lines of\n * text are merged onto a single line when displayed. See\n * [[PDFTextField.enableMultiline]] and [[PDFTextField.disableMultiline]].\n * For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * if (textField.isMultiline()) console.log('Multiline is enabled')\n * ```\n * @returns Whether or not this is a multiline text field.\n */\n isMultiline(): boolean {\n return this.acroField.hasFlag(AcroTextFlags.Multiline);\n }\n\n /**\n * Display each line of text on a new line when this field is displayed in a\n * PDF reader. For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * textField.enableMultiline()\n * ```\n * This method will mark this text field as dirty. See\n * [[PDFTextField.setText]] for more details about what this means.\n */\n enableMultiline() {\n this.markAsDirty();\n this.acroField.setFlagTo(AcroTextFlags.Multiline, true);\n }\n\n /**\n * Display each line of text on the same line when this field is displayed\n * in a PDF reader. For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * textField.disableMultiline()\n * ```\n * This method will mark this text field as dirty. See\n * [[PDFTextField.setText]] for more details about what this means.\n */\n disableMultiline() {\n this.markAsDirty();\n this.acroField.setFlagTo(AcroTextFlags.Multiline, false);\n }\n\n /**\n * Returns `true` if this is a password text field. This means that the field\n * is intended for storing a secure password. See\n * [[PDFTextField.enablePassword]] and [[PDFTextField.disablePassword]].\n * For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * if (textField.isPassword()) console.log('Password is enabled')\n * ```\n * @returns Whether or not this is a password text field.\n */\n isPassword(): boolean {\n return this.acroField.hasFlag(AcroTextFlags.Password);\n }\n\n /**\n * Indicate that this text field is intended for storing a secure password.\n * For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * textField.enablePassword()\n * ```\n * Values entered into password text fields should not be displayed on the\n * screen by PDF readers. Most PDF readers will display the value as\n * asterisks or bullets. PDF readers should never store values entered by the\n * user into password text fields. Similarly, applications should not\n * write data to a password text field.\n *\n * **Please note that this method does not cause entered values to be\n * encrypted or secured in any way! It simply sets a flag that PDF software\n * and readers can access to determine the _purpose_ of this field.**\n */\n enablePassword() {\n this.acroField.setFlagTo(AcroTextFlags.Password, true);\n }\n\n /**\n * Indicate that this text field is **not** intended for storing a secure\n * password. For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * textField.disablePassword()\n * ```\n */\n disablePassword() {\n this.acroField.setFlagTo(AcroTextFlags.Password, false);\n }\n\n /**\n * Returns `true` if the contents of this text field represent a file path.\n * See [[PDFTextField.enableFileSelection]] and\n * [[PDFTextField.disableFileSelection]]. For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * if (textField.isFileSelector()) console.log('Is a file selector')\n * ```\n * @returns Whether or not this field should contain file paths.\n */\n isFileSelector(): boolean {\n return this.acroField.hasFlag(AcroTextFlags.FileSelect);\n }\n\n /**\n * Indicate that this text field is intended to store a file path. The\n * contents of the file stored at that path should be submitted as the value\n * of the field. For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * textField.enableFileSelection()\n * ```\n */\n enableFileSelection() {\n this.acroField.setFlagTo(AcroTextFlags.FileSelect, true);\n }\n\n /**\n * Indicate that this text field is **not** intended to store a file path.\n * For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * textField.disableFileSelection()\n * ```\n */\n disableFileSelection() {\n this.acroField.setFlagTo(AcroTextFlags.FileSelect, false);\n }\n\n /**\n * Returns `true` if the text entered in this field should be spell checked\n * by PDF readers. See [[PDFTextField.enableSpellChecking]] and\n * [[PDFTextField.disableSpellChecking]]. For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * if (textField.isSpellChecked()) console.log('Spell checking is enabled')\n * ```\n * @returns Whether or not this field should be spell checked.\n */\n isSpellChecked(): boolean {\n return !this.acroField.hasFlag(AcroTextFlags.DoNotSpellCheck);\n }\n\n /**\n * Allow PDF readers to spell check the text entered in this field.\n * For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * textField.enableSpellChecking()\n * ```\n */\n enableSpellChecking() {\n this.acroField.setFlagTo(AcroTextFlags.DoNotSpellCheck, false);\n }\n\n /**\n * Do not allow PDF readers to spell check the text entered in this field.\n * For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * textField.disableSpellChecking()\n * ```\n */\n disableSpellChecking() {\n this.acroField.setFlagTo(AcroTextFlags.DoNotSpellCheck, true);\n }\n\n /**\n * Returns `true` if PDF readers should allow the user to scroll the text\n * field when its contents do not fit within the field's view bounds. See\n * [[PDFTextField.enableScrolling]] and [[PDFTextField.disableScrolling]].\n * For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * if (textField.isScrollable()) console.log('Scrolling is enabled')\n * ```\n * @returns Whether or not the field is scrollable in PDF readers.\n */\n isScrollable(): boolean {\n return !this.acroField.hasFlag(AcroTextFlags.DoNotScroll);\n }\n\n /**\n * Allow PDF readers to present a scroll bar to the user when the contents\n * of this text field do not fit within its view bounds. For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * textField.enableScrolling()\n * ```\n * A horizontal scroll bar should be shown for singleline fields. A vertical\n * scroll bar should be shown for multiline fields.\n */\n enableScrolling() {\n this.acroField.setFlagTo(AcroTextFlags.DoNotScroll, false);\n }\n\n /**\n * Do not allow PDF readers to present a scroll bar to the user when the\n * contents of this text field do not fit within its view bounds. For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * textField.disableScrolling()\n * ```\n */\n disableScrolling() {\n this.acroField.setFlagTo(AcroTextFlags.DoNotScroll, true);\n }\n\n /**\n * Returns `true` if this is a combed text field. This means that the field\n * is split into `n` equal size cells with one character in each (where `n`\n * is equal to the max length of the text field). The result is that all\n * characters in this field are displayed an equal distance apart from one\n * another. See [[PDFTextField.enableCombing]] and\n * [[PDFTextField.disableCombing]]. For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * if (textField.isCombed()) console.log('Combing is enabled')\n * ```\n * Note that in order for a text field to be combed, the following must be\n * true (in addition to enabling combing):\n * * It must not be a multiline field (see [[PDFTextField.isMultiline]])\n * * It must not be a password field (see [[PDFTextField.isPassword]])\n * * It must not be a file selector field (see [[PDFTextField.isFileSelector]])\n * * It must have a max length defined (see [[PDFTextField.setMaxLength]])\n * @returns Whether or not this field is combed.\n */\n isCombed(): boolean {\n return (\n this.acroField.hasFlag(AcroTextFlags.Comb) &&\n !this.isMultiline() &&\n !this.isPassword() &&\n !this.isFileSelector() &&\n this.getMaxLength() !== undefined\n );\n }\n\n /**\n * Split this field into `n` equal size cells with one character in each\n * (where `n` is equal to the max length of the text field). This will cause\n * all characters in the field to be displayed an equal distance apart from\n * one another. For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * textField.enableCombing()\n * ```\n *\n * In addition to calling this method, text fields must have a max length\n * defined in order to be combed (see [[PDFTextField.setMaxLength]]).\n *\n * This method will also call the following three methods internally:\n * * [[PDFTextField.disableMultiline]]\n * * [[PDFTextField.disablePassword]]\n * * [[PDFTextField.disableFileSelection]]\n *\n * This method will mark this text field as dirty. See\n * [[PDFTextField.setText]] for more details about what this means.\n */\n enableCombing() {\n if (this.getMaxLength() === undefined) {\n const msg = `PDFTextFields must have a max length in order to be combed`;\n console.warn(msg);\n }\n\n this.markAsDirty();\n\n this.disableMultiline();\n this.disablePassword();\n this.disableFileSelection();\n\n this.acroField.setFlagTo(AcroTextFlags.Comb, true);\n }\n\n /**\n * Turn off combing for this text field. For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * textField.disableCombing()\n * ```\n * See [[PDFTextField.isCombed]] and [[PDFTextField.enableCombing]] for more\n * information about what combing is.\n *\n * This method will mark this text field as dirty. See\n * [[PDFTextField.setText]] for more details about what this means.\n */\n disableCombing() {\n this.markAsDirty();\n this.acroField.setFlagTo(AcroTextFlags.Comb, false);\n }\n\n /**\n * Returns `true` if this text field contains rich text. See\n * [[PDFTextField.enableRichFormatting]] and\n * [[PDFTextField.disableRichFormatting]]. For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * if (textField.isRichFormatted()) console.log('Rich formatting enabled')\n * ```\n * @returns Whether or not this field contains rich text.\n */\n isRichFormatted(): boolean {\n return this.acroField.hasFlag(AcroTextFlags.RichText);\n }\n\n /**\n * Indicate that this field contains XFA data - or rich text. For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * textField.enableRichFormatting()\n * ```\n * Note that `pdf-lib` does not support reading or writing rich text fields.\n * Nor do most PDF readers and writers. Rich text fields are based on XFA\n * (XML Forms Architecture). Relatively few PDFs use rich text fields or XFA.\n * Unlike PDF itself, XFA is not an ISO standard. XFA has been deprecated in\n * PDF 2.0:\n * * https://en.wikipedia.org/wiki/XFA\n * * http://blog.pdfshareforms.com/pdf-2-0-release-bid-farewell-xfa-forms/\n */\n enableRichFormatting() {\n this.acroField.setFlagTo(AcroTextFlags.RichText, true);\n }\n\n /**\n * Indicate that this is a standard text field that does not XFA data (rich\n * text). For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * textField.disableRichFormatting()\n * ```\n */\n disableRichFormatting() {\n this.acroField.setFlagTo(AcroTextFlags.RichText, false);\n }\n\n /**\n * Show this text field on the specified page. For example:\n * ```js\n * const ubuntuFont = await pdfDoc.embedFont(ubuntuFontBytes)\n * const page = pdfDoc.addPage()\n *\n * const form = pdfDoc.getForm()\n * const textField = form.createTextField('best.gundam')\n * textField.setText('Exia')\n *\n * textField.addToPage(page, {\n * x: 50,\n * y: 75,\n * width: 200,\n * height: 100,\n * textColor: rgb(1, 0, 0),\n * backgroundColor: rgb(0, 1, 0),\n * borderColor: rgb(0, 0, 1),\n * borderWidth: 2,\n * rotate: degrees(90),\n * font: ubuntuFont,\n * })\n * ```\n * This will create a new widget for this text field.\n * @param page The page to which this text field widget should be added.\n * @param options The options to be used when adding this text field widget.\n */\n addToPage(page: PDFPage, options?: FieldAppearanceOptions) {\n assertIs(page, 'page', [[PDFPage, 'PDFPage']]);\n assertFieldAppearanceOptions(options);\n\n if (!options) options = {};\n\n if (!('textColor' in options)) options.textColor = rgb(0, 0, 0);\n if (!('backgroundColor' in options)) options.backgroundColor = rgb(1, 1, 1);\n if (!('borderColor' in options)) options.borderColor = rgb(0, 0, 0);\n if (!('borderWidth' in options)) options.borderWidth = 1;\n\n // Create a widget for this text field\n const widget = this.createWidget({\n x: options.x ?? 0,\n y: options.y ?? 0,\n width: options.width ?? 200,\n height: options.height ?? 50,\n textColor: options.textColor,\n backgroundColor: options.backgroundColor,\n borderColor: options.borderColor,\n borderWidth: options.borderWidth ?? 0,\n rotate: options.rotate ?? degrees(0),\n hidden: options.hidden,\n page: page.ref,\n });\n const widgetRef = this.doc.context.register(widget.dict);\n\n // Add widget to this field\n this.acroField.addWidget(widgetRef);\n\n // Set appearance streams for widget\n const font = options.font ?? this.doc.getForm().getDefaultFont();\n this.updateWidgetAppearance(widget, font);\n\n // Add widget to the given page\n page.node.addAnnot(widgetRef);\n }\n\n /**\n * Returns `true` if this text field has been marked as dirty, or if any of\n * this text field's widgets do not have an appearance stream. For example:\n * ```js\n * const textField = form.getTextField('some.text.field')\n * if (textField.needsAppearancesUpdate()) console.log('Needs update')\n * ```\n * @returns Whether or not this text field needs an appearance update.\n */\n needsAppearancesUpdate(): boolean {\n if (this.isDirty()) return true;\n\n const widgets = this.acroField.getWidgets();\n for (let idx = 0, len = widgets.length; idx < len; idx++) {\n const widget = widgets[idx];\n const hasAppearances =\n widget.getAppearances()?.normal instanceof PDFStream;\n if (!hasAppearances) return true;\n }\n\n return false;\n }\n\n /**\n * Update the appearance streams for each of this text field's widgets using\n * the default appearance provider for text fields. For example:\n * ```js\n * const helvetica = await pdfDoc.embedFont(StandardFonts.Helvetica)\n * const textField = form.getTextField('some.text.field')\n * textField.defaultUpdateAppearances(helvetica)\n * ```\n * @param font The font to be used for creating the appearance streams.\n */\n defaultUpdateAppearances(font: PDFFont) {\n assertIs(font, 'font', [[PDFFont, 'PDFFont']]);\n this.updateAppearances(font);\n }\n\n /**\n * Update the appearance streams for each of this text field's widgets using\n * the given appearance provider. If no `provider` is passed, the default\n * appearance provider for text fields will be used. For example:\n * ```js\n * const helvetica = await pdfDoc.embedFont(StandardFonts.Helvetica)\n * const textField = form.getTextField('some.text.field')\n * textField.updateAppearances(helvetica, (field, widget, font) => {\n * ...\n * return drawTextField(...)\n * })\n * ```\n * @param font The font to be used for creating the appearance streams.\n * @param provider Optionally, the appearance provider to be used for\n * generating the contents of the appearance streams.\n */\n updateAppearances(\n font: PDFFont,\n provider?: AppearanceProviderFor,\n ) {\n assertIs(font, 'font', [[PDFFont, 'PDFFont']]);\n assertOrUndefined(provider, 'provider', [Function]);\n\n const widgets = this.acroField.getWidgets();\n for (let idx = 0, len = widgets.length; idx < len; idx++) {\n const widget = widgets[idx];\n this.updateWidgetAppearance(widget, font, provider);\n }\n this.markAsClean();\n }\n\n private updateWidgetAppearance(\n widget: PDFWidgetAnnotation,\n font: PDFFont,\n provider?: AppearanceProviderFor,\n ) {\n const apProvider = provider ?? defaultTextFieldAppearanceProvider;\n const appearances = normalizeAppearance(apProvider(this, widget, font));\n this.updateWidgetAppearanceWithFont(widget, font, appearances);\n }\n}\n","export enum StandardFonts {\n Courier = 'Courier',\n CourierBold = 'Courier-Bold',\n CourierOblique = 'Courier-Oblique',\n CourierBoldOblique = 'Courier-BoldOblique',\n Helvetica = 'Helvetica',\n HelveticaBold = 'Helvetica-Bold',\n HelveticaOblique = 'Helvetica-Oblique',\n HelveticaBoldOblique = 'Helvetica-BoldOblique',\n TimesRoman = 'Times-Roman',\n TimesRomanBold = 'Times-Bold',\n TimesRomanItalic = 'Times-Italic',\n TimesRomanBoldItalic = 'Times-BoldItalic',\n Symbol = 'Symbol',\n ZapfDingbats = 'ZapfDingbats',\n}\n","import PDFDocument from 'src/api/PDFDocument';\nimport PDFPage from 'src/api/PDFPage';\nimport PDFField from 'src/api/form/PDFField';\nimport PDFButton from 'src/api/form/PDFButton';\nimport PDFCheckBox from 'src/api/form/PDFCheckBox';\nimport PDFDropdown from 'src/api/form/PDFDropdown';\nimport PDFOptionList from 'src/api/form/PDFOptionList';\nimport PDFRadioGroup from 'src/api/form/PDFRadioGroup';\nimport PDFSignature from 'src/api/form/PDFSignature';\nimport PDFTextField from 'src/api/form/PDFTextField';\nimport {\n NoSuchFieldError,\n UnexpectedFieldTypeError,\n FieldAlreadyExistsError,\n InvalidFieldNamePartError,\n} from 'src/api/errors';\nimport PDFFont from 'src/api/PDFFont';\nimport { StandardFonts } from 'src/api/StandardFonts';\nimport { rotateInPlace } from 'src/api/operations';\nimport {\n drawObject,\n popGraphicsState,\n pushGraphicsState,\n translate,\n} from 'src/api/operators';\nimport {\n PDFAcroForm,\n PDFAcroField,\n PDFAcroCheckBox,\n PDFAcroComboBox,\n PDFAcroListBox,\n PDFAcroRadioButton,\n PDFAcroSignature,\n PDFAcroText,\n PDFAcroPushButton,\n PDFAcroNonTerminal,\n PDFDict,\n PDFOperator,\n PDFRef,\n createPDFAcroFields,\n PDFName,\n PDFWidgetAnnotation,\n} from 'src/core';\nimport { assertIs, Cache, assertOrUndefined } from 'src/utils';\n\nexport interface FlattenOptions {\n updateFieldAppearances: boolean;\n}\n\n/**\n * Represents the interactive form of a [[PDFDocument]].\n *\n * Interactive forms (sometimes called _AcroForms_) are collections of fields\n * designed to gather information from a user. A PDF document may contains any\n * number of fields that appear on various pages, all of which make up a single,\n * global interactive form spanning the entire document. This means that\n * instances of [[PDFDocument]] shall contain at most one [[PDFForm]].\n *\n * The fields of an interactive form are represented by [[PDFField]] instances.\n */\nexport default class PDFForm {\n /**\n * > **NOTE:** You probably don't want to call this method directly. Instead,\n * > consider using the [[PDFDocument.getForm]] method, which will create an\n * > instance of [[PDFForm]] for you.\n *\n * Create an instance of [[PDFForm]] from an existing acroForm and embedder\n *\n * @param acroForm The underlying `PDFAcroForm` for this form.\n * @param doc The document to which the form will belong.\n */\n static of = (acroForm: PDFAcroForm, doc: PDFDocument) =>\n new PDFForm(acroForm, doc);\n\n /** The low-level PDFAcroForm wrapped by this form. */\n readonly acroForm: PDFAcroForm;\n\n /** The document to which this form belongs. */\n readonly doc: PDFDocument;\n\n private readonly dirtyFields: Set;\n private readonly defaultFontCache: Cache;\n\n private constructor(acroForm: PDFAcroForm, doc: PDFDocument) {\n assertIs(acroForm, 'acroForm', [[PDFAcroForm, 'PDFAcroForm']]);\n assertIs(doc, 'doc', [[PDFDocument, 'PDFDocument']]);\n\n this.acroForm = acroForm;\n this.doc = doc;\n\n this.dirtyFields = new Set();\n this.defaultFontCache = Cache.populatedBy(this.embedDefaultFont);\n }\n\n /**\n * Returns `true` if this [[PDFForm]] has XFA data. Most PDFs with form\n * fields do not use XFA as it is not widely supported by PDF readers.\n *\n * > `pdf-lib` does not support creation, modification, or reading of XFA\n * > fields.\n *\n * For example:\n * ```js\n * const form = pdfDoc.getForm()\n * if (form.hasXFA()) console.log('PDF has XFA data')\n * ```\n * @returns Whether or not this form has XFA data.\n */\n hasXFA(): boolean {\n return this.acroForm.dict.has(PDFName.of('XFA'));\n }\n\n /**\n * Disconnect the XFA data from this [[PDFForm]] (if any exists). This will\n * force readers to fallback to standard fields if the [[PDFDocument]]\n * contains any. For example:\n *\n * For example:\n * ```js\n * const form = pdfDoc.getForm()\n * form.deleteXFA()\n * ```\n */\n deleteXFA(): void {\n this.acroForm.dict.delete(PDFName.of('XFA'));\n }\n\n /**\n * Get all fields contained in this [[PDFForm]]. For example:\n * ```js\n * const form = pdfDoc.getForm()\n * const fields = form.getFields()\n * fields.forEach(field => {\n * const type = field.constructor.name\n * const name = field.getName()\n * console.log(`${type}: ${name}`)\n * })\n * ```\n * @returns An array of all fields in this form.\n */\n getFields(): PDFField[] {\n const allFields = this.acroForm.getAllFields();\n\n const fields: PDFField[] = [];\n for (let idx = 0, len = allFields.length; idx < len; idx++) {\n const [acroField, ref] = allFields[idx];\n const field = convertToPDFField(acroField, ref, this.doc);\n if (field) fields.push(field);\n }\n\n return fields;\n }\n\n /**\n * Get the field in this [[PDFForm]] with the given name. For example:\n * ```js\n * const form = pdfDoc.getForm()\n * const field = form.getFieldMaybe('Page1.Foo.Bar[0]')\n * if (field) console.log('Field exists!')\n * ```\n * @param name A fully qualified field name.\n * @returns The field with the specified name, if one exists.\n */\n getFieldMaybe(name: string): PDFField | undefined {\n assertIs(name, 'name', ['string']);\n const fields = this.getFields();\n for (let idx = 0, len = fields.length; idx < len; idx++) {\n const field = fields[idx];\n if (field.getName() === name) return field;\n }\n return undefined;\n }\n\n /**\n * Get the field in this [[PDFForm]] with the given name. For example:\n * ```js\n * const form = pdfDoc.getForm()\n * const field = form.getField('Page1.Foo.Bar[0]')\n * ```\n * If no field exists with the provided name, an error will be thrown.\n * @param name A fully qualified field name.\n * @returns The field with the specified name.\n */\n getField(name: string): PDFField {\n assertIs(name, 'name', ['string']);\n const field = this.getFieldMaybe(name);\n if (field) return field;\n throw new NoSuchFieldError(name);\n }\n\n /**\n * Get the button field in this [[PDFForm]] with the given name. For example:\n * ```js\n * const form = pdfDoc.getForm()\n * const button = form.getButton('Page1.Foo.Button[0]')\n * ```\n * An error will be thrown if no field exists with the provided name, or if\n * the field exists but is not a button.\n * @param name A fully qualified button name.\n * @returns The button with the specified name.\n */\n getButton(name: string): PDFButton {\n assertIs(name, 'name', ['string']);\n const field = this.getField(name);\n if (field instanceof PDFButton) return field;\n throw new UnexpectedFieldTypeError(name, PDFButton, field);\n }\n\n /**\n * Get the check box field in this [[PDFForm]] with the given name.\n * For example:\n * ```js\n * const form = pdfDoc.getForm()\n * const checkBox = form.getCheckBox('Page1.Foo.CheckBox[0]')\n * checkBox.check()\n * ```\n * An error will be thrown if no field exists with the provided name, or if\n * the field exists but is not a check box.\n * @param name A fully qualified check box name.\n * @returns The check box with the specified name.\n */\n getCheckBox(name: string): PDFCheckBox {\n assertIs(name, 'name', ['string']);\n const field = this.getField(name);\n if (field instanceof PDFCheckBox) return field;\n throw new UnexpectedFieldTypeError(name, PDFCheckBox, field);\n }\n\n /**\n * Get the dropdown field in this [[PDFForm]] with the given name.\n * For example:\n * ```js\n * const form = pdfDoc.getForm()\n * const dropdown = form.getDropdown('Page1.Foo.Dropdown[0]')\n * const options = dropdown.getOptions()\n * dropdown.select(options[0])\n * ```\n * An error will be thrown if no field exists with the provided name, or if\n * the field exists but is not a dropdown.\n * @param name A fully qualified dropdown name.\n * @returns The dropdown with the specified name.\n */\n getDropdown(name: string): PDFDropdown {\n assertIs(name, 'name', ['string']);\n const field = this.getField(name);\n if (field instanceof PDFDropdown) return field;\n throw new UnexpectedFieldTypeError(name, PDFDropdown, field);\n }\n\n /**\n * Get the option list field in this [[PDFForm]] with the given name.\n * For example:\n * ```js\n * const form = pdfDoc.getForm()\n * const optionList = form.getOptionList('Page1.Foo.OptionList[0]')\n * const options = optionList.getOptions()\n * optionList.select(options[0])\n * ```\n * An error will be thrown if no field exists with the provided name, or if\n * the field exists but is not an option list.\n * @param name A fully qualified option list name.\n * @returns The option list with the specified name.\n */\n getOptionList(name: string): PDFOptionList {\n assertIs(name, 'name', ['string']);\n const field = this.getField(name);\n if (field instanceof PDFOptionList) return field;\n throw new UnexpectedFieldTypeError(name, PDFOptionList, field);\n }\n\n /**\n * Get the radio group field in this [[PDFForm]] with the given name.\n * For example:\n * ```js\n * const form = pdfDoc.getForm()\n * const radioGroup = form.getRadioGroup('Page1.Foo.RadioGroup[0]')\n * const options = radioGroup.getOptions()\n * radioGroup.select(options[0])\n * ```\n * An error will be thrown if no field exists with the provided name, or if\n * the field exists but is not a radio group.\n * @param name A fully qualified radio group name.\n * @returns The radio group with the specified name.\n */\n getRadioGroup(name: string): PDFRadioGroup {\n assertIs(name, 'name', ['string']);\n const field = this.getField(name);\n if (field instanceof PDFRadioGroup) return field;\n throw new UnexpectedFieldTypeError(name, PDFRadioGroup, field);\n }\n\n /**\n * Get the signature field in this [[PDFForm]] with the given name.\n * For example:\n * ```js\n * const form = pdfDoc.getForm()\n * const signature = form.getSignature('Page1.Foo.Signature[0]')\n * ```\n * An error will be thrown if no field exists with the provided name, or if\n * the field exists but is not a signature.\n * @param name A fully qualified signature name.\n * @returns The signature with the specified name.\n */\n getSignature(name: string): PDFSignature {\n assertIs(name, 'name', ['string']);\n const field = this.getField(name);\n if (field instanceof PDFSignature) return field;\n throw new UnexpectedFieldTypeError(name, PDFSignature, field);\n }\n\n /**\n * Get the text field in this [[PDFForm]] with the given name.\n * For example:\n * ```js\n * const form = pdfDoc.getForm()\n * const textField = form.getTextField('Page1.Foo.TextField[0]')\n * textField.setText('Are you designed to act or to be acted upon?')\n * ```\n * An error will be thrown if no field exists with the provided name, or if\n * the field exists but is not a text field.\n * @param name A fully qualified text field name.\n * @returns The text field with the specified name.\n */\n getTextField(name: string): PDFTextField {\n assertIs(name, 'name', ['string']);\n const field = this.getField(name);\n if (field instanceof PDFTextField) return field;\n throw new UnexpectedFieldTypeError(name, PDFTextField, field);\n }\n\n /**\n * Create a new button field in this [[PDFForm]] with the given name.\n * For example:\n * ```js\n * const font = await pdfDoc.embedFont(StandardFonts.Helvetica)\n * const page = pdfDoc.addPage()\n *\n * const form = pdfDoc.getForm()\n * const button = form.createButton('cool.new.button')\n *\n * button.addToPage('Do Stuff', font, page)\n * ```\n * An error will be thrown if a field already exists with the provided name.\n * @param name The fully qualified name for the new button.\n * @returns The new button field.\n */\n createButton(name: string): PDFButton {\n assertIs(name, 'name', ['string']);\n\n const nameParts = splitFieldName(name);\n const parent = this.findOrCreateNonTerminals(nameParts.nonTerminal);\n\n const button = PDFAcroPushButton.create(this.doc.context);\n button.setPartialName(nameParts.terminal);\n\n addFieldToParent(parent, [button, button.ref], nameParts.terminal);\n\n return PDFButton.of(button, button.ref, this.doc);\n }\n\n /**\n * Create a new check box field in this [[PDFForm]] with the given name.\n * For example:\n * ```js\n * const font = await pdfDoc.embedFont(StandardFonts.Helvetica)\n * const page = pdfDoc.addPage()\n *\n * const form = pdfDoc.getForm()\n * const checkBox = form.createCheckBox('cool.new.checkBox')\n *\n * checkBox.addToPage(page)\n * ```\n * An error will be thrown if a field already exists with the provided name.\n * @param name The fully qualified name for the new check box.\n * @returns The new check box field.\n */\n createCheckBox(name: string): PDFCheckBox {\n assertIs(name, 'name', ['string']);\n\n const nameParts = splitFieldName(name);\n const parent = this.findOrCreateNonTerminals(nameParts.nonTerminal);\n\n const checkBox = PDFAcroCheckBox.create(this.doc.context);\n checkBox.setPartialName(nameParts.terminal);\n\n addFieldToParent(parent, [checkBox, checkBox.ref], nameParts.terminal);\n\n return PDFCheckBox.of(checkBox, checkBox.ref, this.doc);\n }\n\n /**\n * Create a new dropdown field in this [[PDFForm]] with the given name.\n * For example:\n * ```js\n * const font = await pdfDoc.embedFont(StandardFonts.Helvetica)\n * const page = pdfDoc.addPage()\n *\n * const form = pdfDoc.getForm()\n * const dropdown = form.createDropdown('cool.new.dropdown')\n *\n * dropdown.addToPage(font, page)\n * ```\n * An error will be thrown if a field already exists with the provided name.\n * @param name The fully qualified name for the new dropdown.\n * @returns The new dropdown field.\n */\n createDropdown(name: string): PDFDropdown {\n assertIs(name, 'name', ['string']);\n\n const nameParts = splitFieldName(name);\n const parent = this.findOrCreateNonTerminals(nameParts.nonTerminal);\n\n const comboBox = PDFAcroComboBox.create(this.doc.context);\n comboBox.setPartialName(nameParts.terminal);\n\n addFieldToParent(parent, [comboBox, comboBox.ref], nameParts.terminal);\n\n return PDFDropdown.of(comboBox, comboBox.ref, this.doc);\n }\n\n /**\n * Create a new option list field in this [[PDFForm]] with the given name.\n * For example:\n * ```js\n * const font = await pdfDoc.embedFont(StandardFonts.Helvetica)\n * const page = pdfDoc.addPage()\n *\n * const form = pdfDoc.getForm()\n * const optionList = form.createOptionList('cool.new.optionList')\n *\n * optionList.addToPage(font, page)\n * ```\n * An error will be thrown if a field already exists with the provided name.\n * @param name The fully qualified name for the new option list.\n * @returns The new option list field.\n */\n createOptionList(name: string): PDFOptionList {\n assertIs(name, 'name', ['string']);\n\n const nameParts = splitFieldName(name);\n const parent = this.findOrCreateNonTerminals(nameParts.nonTerminal);\n\n const listBox = PDFAcroListBox.create(this.doc.context);\n listBox.setPartialName(nameParts.terminal);\n\n addFieldToParent(parent, [listBox, listBox.ref], nameParts.terminal);\n\n return PDFOptionList.of(listBox, listBox.ref, this.doc);\n }\n\n /**\n * Create a new radio group field in this [[PDFForm]] with the given name.\n * For example:\n * ```js\n * const font = await pdfDoc.embedFont(StandardFonts.Helvetica)\n * const page = pdfDoc.addPage()\n *\n * const form = pdfDoc.getForm()\n * const radioGroup = form.createRadioGroup('cool.new.radioGroup')\n *\n * radioGroup.addOptionToPage('is-dog', page, { y: 0 })\n * radioGroup.addOptionToPage('is-cat', page, { y: 75 })\n * ```\n * An error will be thrown if a field already exists with the provided name.\n * @param name The fully qualified name for the new radio group.\n * @returns The new radio group field.\n */\n createRadioGroup(name: string): PDFRadioGroup {\n assertIs(name, 'name', ['string']);\n const nameParts = splitFieldName(name);\n\n const parent = this.findOrCreateNonTerminals(nameParts.nonTerminal);\n\n const radioButton = PDFAcroRadioButton.create(this.doc.context);\n radioButton.setPartialName(nameParts.terminal);\n\n addFieldToParent(\n parent,\n [radioButton, radioButton.ref],\n nameParts.terminal,\n );\n\n return PDFRadioGroup.of(radioButton, radioButton.ref, this.doc);\n }\n\n /**\n * Create a new text field in this [[PDFForm]] with the given name.\n * For example:\n * ```js\n * const font = await pdfDoc.embedFont(StandardFonts.Helvetica)\n * const page = pdfDoc.addPage()\n *\n * const form = pdfDoc.getForm()\n * const textField = form.createTextField('cool.new.textField')\n *\n * textField.addToPage(font, page)\n * ```\n * An error will be thrown if a field already exists with the provided name.\n * @param name The fully qualified name for the new radio group.\n * @returns The new radio group field.\n */\n createTextField(name: string): PDFTextField {\n assertIs(name, 'name', ['string']);\n const nameParts = splitFieldName(name);\n\n const parent = this.findOrCreateNonTerminals(nameParts.nonTerminal);\n\n const text = PDFAcroText.create(this.doc.context);\n text.setPartialName(nameParts.terminal);\n\n addFieldToParent(parent, [text, text.ref], nameParts.terminal);\n\n return PDFTextField.of(text, text.ref, this.doc);\n }\n\n /**\n * Flatten all fields in this [[PDFForm]].\n *\n * Flattening a form field will take the current appearance for each of that\n * field's widgets and make them part of their page's content stream. All form\n * fields and annotations associated are then removed. Note that once a form\n * has been flattened its fields can no longer be accessed or edited.\n *\n * This operation is often used after filling form fields to ensure a\n * consistent appearance across different PDF readers and/or printers.\n * Another common use case is to copy a template document with form fields\n * into another document. In this scenario you would load the template\n * document, fill its fields, flatten it, and then copy its pages into the\n * recipient document - the filled fields will be copied over.\n *\n * For example:\n * ```js\n * const form = pdfDoc.getForm();\n * form.flatten();\n * ```\n */\n flatten(options: FlattenOptions = { updateFieldAppearances: true }) {\n if (options.updateFieldAppearances) {\n this.updateFieldAppearances();\n }\n\n const fields = this.getFields();\n\n for (let i = 0, lenFields = fields.length; i < lenFields; i++) {\n const field = fields[i];\n const widgets = field.acroField.getWidgets();\n\n for (let j = 0, lenWidgets = widgets.length; j < lenWidgets; j++) {\n const widget = widgets[j];\n const page = this.findWidgetPage(widget);\n const widgetRef = this.findWidgetAppearanceRef(field, widget);\n\n const xObjectKey = page.node.newXObject('FlatWidget', widgetRef);\n\n const rectangle = widget.getRectangle();\n const operators = [\n pushGraphicsState(),\n translate(rectangle.x, rectangle.y),\n ...rotateInPlace({ ...rectangle, rotation: 0 }),\n drawObject(xObjectKey),\n popGraphicsState(),\n ].filter(Boolean) as PDFOperator[];\n\n page.pushOperators(...operators);\n }\n\n this.removeField(field);\n }\n }\n\n /**\n * Remove a field from this [[PDFForm]].\n *\n * For example:\n * ```js\n * const form = pdfDoc.getForm();\n * const ageField = form.getFields().find(x => x.getName() === 'Age');\n * form.removeField(ageField);\n * ```\n */\n removeField(field: PDFField) {\n const widgets = field.acroField.getWidgets();\n const pages: Set = new Set();\n\n for (let i = 0, len = widgets.length; i < len; i++) {\n const widget = widgets[i];\n const widgetRef = this.findWidgetAppearanceRef(field, widget);\n\n const page = this.findWidgetPage(widget);\n pages.add(page);\n\n page.node.removeAnnot(widgetRef);\n }\n\n pages.forEach((page) => page.node.removeAnnot(field.ref));\n this.acroForm.removeField(field.acroField);\n const fieldKids = field.acroField.normalizedEntries().Kids;\n const kidsCount = fieldKids.size();\n for (let childIndex = 0; childIndex < kidsCount; childIndex++) {\n const child = fieldKids.get(childIndex);\n if (child instanceof PDFRef) {\n this.doc.context.delete(child);\n }\n }\n this.doc.context.delete(field.ref);\n }\n\n /**\n * Update the appearance streams for all widgets of all fields in this\n * [[PDFForm]]. Appearance streams will only be created for a widget if it\n * does not have any existing appearance streams, or the field's value has\n * changed (e.g. by calling [[PDFTextField.setText]] or\n * [[PDFDropdown.select]]).\n *\n * For example:\n * ```js\n * const courier = await pdfDoc.embedFont(StandardFonts.Courier)\n * const form = pdfDoc.getForm()\n * form.updateFieldAppearances(courier)\n * ```\n *\n * **IMPORTANT:** The default value for the `font` parameter is\n * [[StandardFonts.Helvetica]]. Note that this is a WinAnsi font. This means\n * that encoding errors will be thrown if any fields contain text with\n * characters outside the WinAnsi character set (the latin alphabet).\n *\n * Embedding a custom font and passing that as the `font`\n * parameter allows you to generate appearance streams with non WinAnsi\n * characters (assuming your custom font supports them).\n *\n * > **NOTE:** The [[PDFDocument.save]] method will call this method to\n * > update appearances automatically if a form was accessed via the\n * > [[PDFDocument.getForm]] method prior to saving.\n *\n * @param font Optionally, the font to use when creating new appearances.\n */\n updateFieldAppearances(font?: PDFFont) {\n assertOrUndefined(font, 'font', [[PDFFont, 'PDFFont']]);\n\n font = font ?? this.getDefaultFont();\n\n const fields = this.getFields();\n\n for (let idx = 0, len = fields.length; idx < len; idx++) {\n const field = fields[idx];\n if (field.needsAppearancesUpdate()) {\n field.defaultUpdateAppearances(font);\n }\n }\n }\n\n /**\n * Mark a field as dirty. This will cause its appearance streams to be\n * updated by [[PDFForm.updateFieldAppearances]].\n * ```js\n * const form = pdfDoc.getForm()\n * const field = form.getField('foo.bar')\n * form.markFieldAsDirty(field.ref)\n * ```\n * @param fieldRef The reference to the field that should be marked.\n */\n markFieldAsDirty(fieldRef: PDFRef) {\n assertOrUndefined(fieldRef, 'fieldRef', [[PDFRef, 'PDFRef']]);\n this.dirtyFields.add(fieldRef);\n }\n\n /**\n * Mark a field as dirty. This will cause its appearance streams to not be\n * updated by [[PDFForm.updateFieldAppearances]].\n * ```js\n * const form = pdfDoc.getForm()\n * const field = form.getField('foo.bar')\n * form.markFieldAsClean(field.ref)\n * ```\n * @param fieldRef The reference to the field that should be marked.\n */\n markFieldAsClean(fieldRef: PDFRef) {\n assertOrUndefined(fieldRef, 'fieldRef', [[PDFRef, 'PDFRef']]);\n this.dirtyFields.delete(fieldRef);\n }\n\n /**\n * Returns `true` is the specified field has been marked as dirty.\n * ```js\n * const form = pdfDoc.getForm()\n * const field = form.getField('foo.bar')\n * if (form.fieldIsDirty(field.ref)) console.log('Field is dirty')\n * ```\n * @param fieldRef The reference to the field that should be checked.\n * @returns Whether or not the specified field is dirty.\n */\n fieldIsDirty(fieldRef: PDFRef): boolean {\n assertOrUndefined(fieldRef, 'fieldRef', [[PDFRef, 'PDFRef']]);\n return this.dirtyFields.has(fieldRef);\n }\n\n getDefaultFont() {\n return this.defaultFontCache.access();\n }\n\n private findWidgetPage(widget: PDFWidgetAnnotation): PDFPage {\n const pageRef = widget.P();\n let page = this.doc.getPages().find((x) => x.ref === pageRef);\n if (page === undefined) {\n const widgetRef = this.doc.context.getObjectRef(widget.dict);\n if (widgetRef === undefined) {\n throw new Error('Could not find PDFRef for PDFObject');\n }\n\n page = this.doc.findPageForAnnotationRef(widgetRef);\n\n if (page === undefined) {\n throw new Error(`Could not find page for PDFRef ${widgetRef}`);\n }\n }\n\n return page;\n }\n\n private findWidgetAppearanceRef(\n field: PDFField,\n widget: PDFWidgetAnnotation,\n ): PDFRef {\n let refOrDict = widget.getNormalAppearance();\n\n if (\n refOrDict instanceof PDFDict &&\n (field instanceof PDFCheckBox || field instanceof PDFRadioGroup)\n ) {\n const value = field.acroField.getValue();\n const ref = refOrDict.get(value) ?? refOrDict.get(PDFName.of('Off'));\n\n if (ref instanceof PDFRef) {\n refOrDict = ref;\n }\n }\n\n if (!(refOrDict instanceof PDFRef)) {\n const name = field.getName();\n throw new Error(`Failed to extract appearance ref for: ${name}`);\n }\n\n return refOrDict;\n }\n\n private findOrCreateNonTerminals(partialNames: string[]) {\n let nonTerminal: [PDFAcroForm] | [PDFAcroNonTerminal, PDFRef] = [\n this.acroForm,\n ];\n for (let idx = 0, len = partialNames.length; idx < len; idx++) {\n const namePart = partialNames[idx];\n if (!namePart) throw new InvalidFieldNamePartError(namePart);\n const [parent, parentRef] = nonTerminal;\n const res = this.findNonTerminal(namePart, parent);\n\n if (res) {\n nonTerminal = res;\n } else {\n const node = PDFAcroNonTerminal.create(this.doc.context);\n node.setPartialName(namePart);\n node.setParent(parentRef);\n const nodeRef = this.doc.context.register(node.dict);\n parent.addField(nodeRef);\n nonTerminal = [node, nodeRef];\n }\n }\n return nonTerminal;\n }\n\n private findNonTerminal(\n partialName: string,\n parent: PDFAcroForm | PDFAcroNonTerminal,\n ): [PDFAcroNonTerminal, PDFRef] | undefined {\n const fields =\n parent instanceof PDFAcroForm\n ? this.acroForm.getFields()\n : createPDFAcroFields(parent.Kids());\n\n for (let idx = 0, len = fields.length; idx < len; idx++) {\n const [field, ref] = fields[idx];\n if (field.getPartialName() === partialName) {\n if (field instanceof PDFAcroNonTerminal) return [field, ref];\n throw new FieldAlreadyExistsError(partialName);\n }\n }\n\n return undefined;\n }\n\n private embedDefaultFont = (): PDFFont =>\n this.doc.embedStandardFont(StandardFonts.Helvetica);\n}\n\nconst convertToPDFField = (\n field: PDFAcroField,\n ref: PDFRef,\n doc: PDFDocument,\n): PDFField | undefined => {\n if (field instanceof PDFAcroPushButton) return PDFButton.of(field, ref, doc);\n if (field instanceof PDFAcroCheckBox) return PDFCheckBox.of(field, ref, doc);\n if (field instanceof PDFAcroComboBox) return PDFDropdown.of(field, ref, doc);\n if (field instanceof PDFAcroListBox) return PDFOptionList.of(field, ref, doc);\n if (field instanceof PDFAcroText) return PDFTextField.of(field, ref, doc);\n if (field instanceof PDFAcroRadioButton) {\n return PDFRadioGroup.of(field, ref, doc);\n }\n if (field instanceof PDFAcroSignature) {\n return PDFSignature.of(field, ref, doc);\n }\n return undefined;\n};\n\nconst splitFieldName = (fullyQualifiedName: string) => {\n if (fullyQualifiedName.length === 0) {\n throw new Error('PDF field names must not be empty strings');\n }\n\n const parts = fullyQualifiedName.split('.');\n\n for (let idx = 0, len = parts.length; idx < len; idx++) {\n if (parts[idx] === '') {\n throw new Error(\n `Periods in PDF field names must be separated by at least one character: \"${fullyQualifiedName}\"`,\n );\n }\n }\n\n if (parts.length === 1) return { nonTerminal: [], terminal: parts[0] };\n\n return {\n nonTerminal: parts.slice(0, parts.length - 1),\n terminal: parts[parts.length - 1],\n };\n};\n\nconst addFieldToParent = (\n [parent, parentRef]: [PDFAcroForm] | [PDFAcroNonTerminal, PDFRef],\n [field, fieldRef]: [PDFAcroField, PDFRef],\n partialName: string,\n) => {\n const entries = parent.normalizedEntries();\n const fields = createPDFAcroFields(\n 'Kids' in entries ? entries.Kids : entries.Fields,\n );\n for (let idx = 0, len = fields.length; idx < len; idx++) {\n if (fields[idx][0].getPartialName() === partialName) {\n throw new FieldAlreadyExistsError(partialName);\n }\n }\n parent.addField(fieldRef);\n field.setParent(parentRef);\n};\n","import { EmbeddedFileOptions } from 'src/core/embedders/FileEmbedder';\nimport { TypeFeatures } from 'src/types/fontkit';\n\nexport enum ParseSpeeds {\n Fastest = Infinity,\n Fast = 1500,\n Medium = 500,\n Slow = 100,\n}\n\nexport interface AttachmentOptions extends EmbeddedFileOptions {}\n\nexport interface SaveOptions {\n useObjectStreams?: boolean;\n addDefaultPage?: boolean;\n objectsPerTick?: number;\n updateFieldAppearances?: boolean;\n}\n\nexport interface Base64SaveOptions extends SaveOptions {\n dataUri?: boolean;\n}\n\nexport interface LoadOptions {\n ignoreEncryption?: boolean;\n parseSpeed?: ParseSpeeds | number;\n throwOnInvalidObject?: boolean;\n updateMetadata?: boolean;\n capNumbers?: boolean;\n}\n\nexport interface CreateOptions {\n updateMetadata?: boolean;\n}\n\nexport interface EmbedFontOptions {\n subset?: boolean;\n customName?: string;\n features?: TypeFeatures;\n}\n\nexport interface SetTitleOptions {\n showInWindowTitleBar: boolean;\n}\n","import Embeddable from 'src/api/Embeddable';\nimport PDFDocument from 'src/api/PDFDocument';\nimport FileEmbedder from 'src/core/embedders/FileEmbedder';\nimport { PDFName, PDFArray, PDFDict, PDFHexString, PDFRef } from 'src/core';\n\n/**\n * Represents a file that has been embedded in a [[PDFDocument]].\n */\nexport default class PDFEmbeddedFile implements Embeddable {\n /**\n * > **NOTE:** You probably don't want to call this method directly. Instead,\n * > consider using the [[PDFDocument.attach]] method, which will create\n * instances of [[PDFEmbeddedFile]] for you.\n *\n * Create an instance of [[PDFEmbeddedFile]] from an existing ref and embedder\n *\n * @param ref The unique reference for this file.\n * @param doc The document to which the file will belong.\n * @param embedder The embedder that will be used to embed the file.\n */\n static of = (ref: PDFRef, doc: PDFDocument, embedder: FileEmbedder) =>\n new PDFEmbeddedFile(ref, doc, embedder);\n\n /** The unique reference assigned to this embedded file within the document. */\n readonly ref: PDFRef;\n\n /** The document to which this embedded file belongs. */\n readonly doc: PDFDocument;\n\n private alreadyEmbedded = false;\n private readonly embedder: FileEmbedder;\n\n private constructor(ref: PDFRef, doc: PDFDocument, embedder: FileEmbedder) {\n this.ref = ref;\n this.doc = doc;\n this.embedder = embedder;\n }\n\n /**\n * > **NOTE:** You probably don't need to call this method directly. The\n * > [[PDFDocument.save]] and [[PDFDocument.saveAsBase64]] methods will\n * > automatically ensure all embeddable files get embedded.\n *\n * Embed this embeddable file in its document.\n *\n * @returns Resolves when the embedding is complete.\n */\n async embed(): Promise {\n if (!this.alreadyEmbedded) {\n const ref = await this.embedder.embedIntoContext(\n this.doc.context,\n this.ref,\n );\n\n if (!this.doc.catalog.has(PDFName.of('Names'))) {\n this.doc.catalog.set(PDFName.of('Names'), this.doc.context.obj({}));\n }\n const Names = this.doc.catalog.lookup(PDFName.of('Names'), PDFDict);\n\n if (!Names.has(PDFName.of('EmbeddedFiles'))) {\n Names.set(PDFName.of('EmbeddedFiles'), this.doc.context.obj({}));\n }\n const EmbeddedFiles = Names.lookup(PDFName.of('EmbeddedFiles'), PDFDict);\n\n if (!EmbeddedFiles.has(PDFName.of('Names'))) {\n EmbeddedFiles.set(PDFName.of('Names'), this.doc.context.obj([]));\n }\n const EFNames = EmbeddedFiles.lookup(PDFName.of('Names'), PDFArray);\n\n EFNames.push(PDFHexString.fromText(this.embedder.fileName));\n EFNames.push(ref);\n\n /**\n * The AF-Tag is needed to achieve PDF-A3 compliance for embedded files\n *\n * The following document outlines the uses cases of the associated files (AF) tag.\n * See:\n * https://www.pdfa.org/wp-content/uploads/2018/10/PDF20_AN002-AF.pdf\n */\n\n if (!this.doc.catalog.has(PDFName.of('AF'))) {\n this.doc.catalog.set(PDFName.of('AF'), this.doc.context.obj([]));\n }\n const AF = this.doc.catalog.lookup(PDFName.of('AF'), PDFArray);\n AF.push(ref);\n\n this.alreadyEmbedded = true;\n }\n }\n}\n","import Embeddable from 'src/api/Embeddable';\nimport PDFDocument from 'src/api/PDFDocument';\nimport JavaScriptEmbedder from 'src/core/embedders/JavaScriptEmbedder';\nimport { PDFName, PDFArray, PDFDict, PDFHexString, PDFRef } from 'src/core';\n\n/**\n * Represents JavaScript that has been embedded in a [[PDFDocument]].\n */\nexport default class PDFJavaScript implements Embeddable {\n /**\n * > **NOTE:** You probably don't want to call this method directly. Instead,\n * > consider using the [[PDFDocument.addJavaScript]] method, which will\n * create instances of [[PDFJavaScript]] for you.\n *\n * Create an instance of [[PDFJavaScript]] from an existing ref and script\n *\n * @param ref The unique reference for this script.\n * @param doc The document to which the script will belong.\n * @param embedder The embedder that will be used to embed the script.\n */\n static of = (ref: PDFRef, doc: PDFDocument, embedder: JavaScriptEmbedder) =>\n new PDFJavaScript(ref, doc, embedder);\n\n /** The unique reference assigned to this embedded script within the document. */\n readonly ref: PDFRef;\n\n /** The document to which this embedded script belongs. */\n readonly doc: PDFDocument;\n\n private alreadyEmbedded = false;\n private readonly embedder: JavaScriptEmbedder;\n\n private constructor(\n ref: PDFRef,\n doc: PDFDocument,\n embedder: JavaScriptEmbedder,\n ) {\n this.ref = ref;\n this.doc = doc;\n this.embedder = embedder;\n }\n\n /**\n * > **NOTE:** You probably don't need to call this method directly. The\n * > [[PDFDocument.save]] and [[PDFDocument.saveAsBase64]] methods will\n * > automatically ensure all JavaScripts get embedded.\n *\n * Embed this JavaScript in its document.\n *\n * @returns Resolves when the embedding is complete.\n */\n async embed(): Promise {\n if (!this.alreadyEmbedded) {\n const { catalog, context } = this.doc;\n\n const ref = await this.embedder.embedIntoContext(\n this.doc.context,\n this.ref,\n );\n\n if (!catalog.has(PDFName.of('Names'))) {\n catalog.set(PDFName.of('Names'), context.obj({}));\n }\n const Names = catalog.lookup(PDFName.of('Names'), PDFDict);\n\n if (!Names.has(PDFName.of('JavaScript'))) {\n Names.set(PDFName.of('JavaScript'), context.obj({}));\n }\n const Javascript = Names.lookup(PDFName.of('JavaScript'), PDFDict);\n\n if (!Javascript.has(PDFName.of('Names'))) {\n Javascript.set(PDFName.of('Names'), context.obj([]));\n }\n const JSNames = Javascript.lookup(PDFName.of('Names'), PDFArray);\n\n JSNames.push(PDFHexString.fromText(this.embedder.scriptName));\n JSNames.push(ref);\n\n this.alreadyEmbedded = true;\n }\n }\n}\n","import Embeddable from 'src/api/Embeddable';\nimport {\n EncryptedPDFError,\n FontkitNotRegisteredError,\n ForeignPageError,\n RemovePageFromEmptyDocumentError,\n} from 'src/api/errors';\nimport PDFEmbeddedPage from 'src/api/PDFEmbeddedPage';\nimport PDFFont from 'src/api/PDFFont';\nimport PDFImage from 'src/api/PDFImage';\nimport PDFPage from 'src/api/PDFPage';\nimport PDFForm from 'src/api/form/PDFForm';\nimport { PageSizes } from 'src/api/sizes';\nimport { StandardFonts } from 'src/api/StandardFonts';\nimport {\n CustomFontEmbedder,\n CustomFontSubsetEmbedder,\n JpegEmbedder,\n PageBoundingBox,\n PageEmbeddingMismatchedContextError,\n PDFCatalog,\n PDFContext,\n PDFDict,\n PDFHexString,\n PDFName,\n PDFObjectCopier,\n PDFPageEmbedder,\n PDFPageLeaf,\n PDFPageTree,\n PDFParser,\n PDFStreamWriter,\n PDFString,\n PDFWriter,\n PngEmbedder,\n StandardFontEmbedder,\n UnexpectedObjectTypeError,\n} from 'src/core';\nimport {\n ParseSpeeds,\n AttachmentOptions,\n SaveOptions,\n Base64SaveOptions,\n LoadOptions,\n CreateOptions,\n EmbedFontOptions,\n SetTitleOptions,\n} from 'src/api/PDFDocumentOptions';\nimport PDFObject from 'src/core/objects/PDFObject';\nimport PDFRef from 'src/core/objects/PDFRef';\nimport { Fontkit } from 'src/types/fontkit';\nimport { TransformationMatrix } from 'src/types/matrix';\nimport {\n assertIs,\n assertIsOneOfOrUndefined,\n assertOrUndefined,\n assertRange,\n Cache,\n canBeConvertedToUint8Array,\n encodeToBase64,\n isStandardFont,\n pluckIndices,\n range,\n toUint8Array,\n} from 'src/utils';\nimport FileEmbedder, { AFRelationship } from 'src/core/embedders/FileEmbedder';\nimport PDFEmbeddedFile from 'src/api/PDFEmbeddedFile';\nimport PDFJavaScript from 'src/api/PDFJavaScript';\nimport JavaScriptEmbedder from 'src/core/embedders/JavaScriptEmbedder';\n\n/**\n * Represents a PDF document.\n */\nexport default class PDFDocument {\n /**\n * Load an existing [[PDFDocument]]. The input data can be provided in\n * multiple formats:\n *\n * | Type | Contents |\n * | ------------- | ------------------------------------------------------ |\n * | `string` | A base64 encoded string (or data URI) containing a PDF |\n * | `Uint8Array` | The raw bytes of a PDF |\n * | `ArrayBuffer` | The raw bytes of a PDF |\n *\n * For example:\n * ```js\n * import { PDFDocument } from 'pdf-lib'\n *\n * // pdf=string\n * const base64 =\n * 'JVBERi0xLjcKJYGBgYEKCjUgMCBvYmoKPDwKL0ZpbHRlciAvRmxhdGVEZWNvZGUKL0xlbm' +\n * 'd0aCAxMDQKPj4Kc3RyZWFtCniccwrhMlAAwaJ0Ln2P1Jyy1JLM5ERdc0MjCwUjE4WQNC4Q' +\n * '6cNlCFZkqGCqYGSqEJLLZWNuYGZiZmbkYuZsZmlmZGRgZmluDCQNzc3NTM2NzdzMXMxMjQ' +\n * 'ztFEKyuEK0uFxDuAAOERdVCmVuZHN0cmVhbQplbmRvYmoKCjYgMCBvYmoKPDwKL0ZpbHRl' +\n * 'ciAvRmxhdGVEZWNvZGUKL1R5cGUgL09ialN0bQovTiA0Ci9GaXJzdCAyMAovTGVuZ3RoID' +\n * 'IxNQo+PgpzdHJlYW0KeJxVj9GqwjAMhu/zFHkBzTo3nCCCiiKIHPEICuJF3cKoSCu2E8/b' +\n * '20wPIr1p8v9/8kVhgilmGfawX2CGaVrgcAi0/bsy0lrX7IGWpvJ4iJYEN3gEmrrGBlQwGs' +\n * 'HHO9VBX1wNrxAqMX87RBD5xpJuddqwd82tjAHxzV1U5LPgy52DKXWnr1Lheg+j/c/pzGVr' +\n * 'iqV0VlwZPXGPCJjElw/ybkwUmeoWgxesDXGhHJC/D/iikp1Av80ptKU0FdBEe25pPihAM1' +\n * 'u6ytgaaWfs2Hrz35CJT1+EWmAKZW5kc3RyZWFtCmVuZG9iagoKNyAwIG9iago8PAovU2l6' +\n * 'ZSA4Ci9Sb290IDIgMCBSCi9GaWx0ZXIgL0ZsYXRlRGVjb2RlCi9UeXBlIC9YUmVmCi9MZW' +\n * '5ndGggMzgKL1cgWyAxIDIgMiBdCi9JbmRleCBbIDAgOCBdCj4+CnN0cmVhbQp4nBXEwREA' +\n * 'EBAEsCwz3vrvRmOOyyOoGhZdutHN2MT55fIAVocD+AplbmRzdHJlYW0KZW5kb2JqCgpzdG' +\n * 'FydHhyZWYKNTEwCiUlRU9G'\n *\n * const dataUri = 'data:application/pdf;base64,' + base64\n *\n * const pdfDoc1 = await PDFDocument.load(base64)\n * const pdfDoc2 = await PDFDocument.load(dataUri)\n *\n * // pdf=Uint8Array\n * import fs from 'fs'\n * const uint8Array = fs.readFileSync('with_update_sections.pdf')\n * const pdfDoc3 = await PDFDocument.load(uint8Array)\n *\n * // pdf=ArrayBuffer\n * const url = 'https://pdf-lib.js.org/assets/with_update_sections.pdf'\n * const arrayBuffer = await fetch(url).then(res => res.arrayBuffer())\n * const pdfDoc4 = await PDFDocument.load(arrayBuffer)\n *\n * ```\n *\n * @param pdf The input data containing a PDF document.\n * @param options The options to be used when loading the document.\n * @returns Resolves with a document loaded from the input.\n */\n static async load(\n pdf: string | Uint8Array | ArrayBuffer,\n options: LoadOptions = {},\n ) {\n const {\n ignoreEncryption = false,\n parseSpeed = ParseSpeeds.Slow,\n throwOnInvalidObject = false,\n updateMetadata = true,\n capNumbers = false,\n } = options;\n\n assertIs(pdf, 'pdf', ['string', Uint8Array, ArrayBuffer]);\n assertIs(ignoreEncryption, 'ignoreEncryption', ['boolean']);\n assertIs(parseSpeed, 'parseSpeed', ['number']);\n assertIs(throwOnInvalidObject, 'throwOnInvalidObject', ['boolean']);\n\n const bytes = toUint8Array(pdf);\n const context = await PDFParser.forBytesWithOptions(\n bytes,\n parseSpeed,\n throwOnInvalidObject,\n capNumbers,\n ).parseDocument();\n return new PDFDocument(context, ignoreEncryption, updateMetadata);\n }\n\n /**\n * Create a new [[PDFDocument]].\n * @returns Resolves with the newly created document.\n */\n static async create(options: CreateOptions = {}) {\n const { updateMetadata = true } = options;\n\n const context = PDFContext.create();\n const pageTree = PDFPageTree.withContext(context);\n const pageTreeRef = context.register(pageTree);\n const catalog = PDFCatalog.withContextAndPages(context, pageTreeRef);\n context.trailerInfo.Root = context.register(catalog);\n\n return new PDFDocument(context, false, updateMetadata);\n }\n\n /** The low-level context of this document. */\n readonly context: PDFContext;\n\n /** The catalog of this document. */\n readonly catalog: PDFCatalog;\n\n /** Whether or not this document is encrypted. */\n readonly isEncrypted: boolean;\n\n /** The default word breaks used in PDFPage.drawText */\n defaultWordBreaks: string[] = [' '];\n\n private fontkit?: Fontkit;\n private pageCount: number | undefined;\n private readonly pageCache: Cache;\n private readonly pageMap: Map;\n private readonly formCache: Cache;\n private readonly fonts: PDFFont[];\n private readonly images: PDFImage[];\n private readonly embeddedPages: PDFEmbeddedPage[];\n private readonly embeddedFiles: PDFEmbeddedFile[];\n private readonly javaScripts: PDFJavaScript[];\n\n private constructor(\n context: PDFContext,\n ignoreEncryption: boolean,\n updateMetadata: boolean,\n ) {\n assertIs(context, 'context', [[PDFContext, 'PDFContext']]);\n assertIs(ignoreEncryption, 'ignoreEncryption', ['boolean']);\n\n this.context = context;\n this.catalog = context.lookup(context.trailerInfo.Root) as PDFCatalog;\n this.isEncrypted = !!context.lookup(context.trailerInfo.Encrypt);\n\n this.pageCache = Cache.populatedBy(this.computePages);\n this.pageMap = new Map();\n this.formCache = Cache.populatedBy(this.getOrCreateForm);\n this.fonts = [];\n this.images = [];\n this.embeddedPages = [];\n this.embeddedFiles = [];\n this.javaScripts = [];\n\n if (!ignoreEncryption && this.isEncrypted) throw new EncryptedPDFError();\n\n if (updateMetadata) this.updateInfoDict();\n }\n\n /**\n * Register a fontkit instance. This must be done before custom fonts can\n * be embedded. See [here](https://github.com/Hopding/pdf-lib/tree/master#fontkit-installation)\n * for instructions on how to install and register a fontkit instance.\n *\n * > You do **not** need to call this method to embed standard fonts.\n *\n * For example:\n * ```js\n * import { PDFDocument } from 'pdf-lib'\n * import fontkit from '@pdf-lib/fontkit'\n *\n * const pdfDoc = await PDFDocument.create()\n * pdfDoc.registerFontkit(fontkit)\n * ```\n *\n * @param fontkit The fontkit instance to be registered.\n */\n registerFontkit(fontkit: Fontkit): void {\n this.fontkit = fontkit;\n }\n\n /**\n * Get the [[PDFForm]] containing all interactive fields for this document.\n * For example:\n * ```js\n * const form = pdfDoc.getForm()\n * const fields = form.getFields()\n * fields.forEach(field => {\n * const type = field.constructor.name\n * const name = field.getName()\n * console.log(`${type}: ${name}`)\n * })\n * ```\n * @returns The form for this document.\n */\n getForm(): PDFForm {\n const form = this.formCache.access();\n if (form.hasXFA()) {\n console.warn(\n 'Removing XFA form data as pdf-lib does not support reading or writing XFA',\n );\n form.deleteXFA();\n }\n return form;\n }\n\n /**\n * Get this document's title metadata. The title appears in the\n * \"Document Properties\" section of most PDF readers. For example:\n * ```js\n * const title = pdfDoc.getTitle()\n * ```\n * @returns A string containing the title of this document, if it has one.\n */\n getTitle(): string | undefined {\n const title = this.getInfoDict().lookup(PDFName.Title);\n if (!title) return undefined;\n assertIsLiteralOrHexString(title);\n return title.decodeText();\n }\n\n /**\n * Get this document's author metadata. The author appears in the\n * \"Document Properties\" section of most PDF readers. For example:\n * ```js\n * const author = pdfDoc.getAuthor()\n * ```\n * @returns A string containing the author of this document, if it has one.\n */\n getAuthor(): string | undefined {\n const author = this.getInfoDict().lookup(PDFName.Author);\n if (!author) return undefined;\n assertIsLiteralOrHexString(author);\n return author.decodeText();\n }\n\n /**\n * Get this document's subject metadata. The subject appears in the\n * \"Document Properties\" section of most PDF readers. For example:\n * ```js\n * const subject = pdfDoc.getSubject()\n * ```\n * @returns A string containing the subject of this document, if it has one.\n */\n getSubject(): string | undefined {\n const subject = this.getInfoDict().lookup(PDFName.Subject);\n if (!subject) return undefined;\n assertIsLiteralOrHexString(subject);\n return subject.decodeText();\n }\n\n /**\n * Get this document's keywords metadata. The keywords appear in the\n * \"Document Properties\" section of most PDF readers. For example:\n * ```js\n * const keywords = pdfDoc.getKeywords()\n * ```\n * @returns A string containing the keywords of this document, if it has any.\n */\n getKeywords(): string | undefined {\n const keywords = this.getInfoDict().lookup(PDFName.Keywords);\n if (!keywords) return undefined;\n assertIsLiteralOrHexString(keywords);\n return keywords.decodeText();\n }\n\n /**\n * Get this document's creator metadata. The creator appears in the\n * \"Document Properties\" section of most PDF readers. For example:\n * ```js\n * const creator = pdfDoc.getCreator()\n * ```\n * @returns A string containing the creator of this document, if it has one.\n */\n getCreator(): string | undefined {\n const creator = this.getInfoDict().lookup(PDFName.Creator);\n if (!creator) return undefined;\n assertIsLiteralOrHexString(creator);\n return creator.decodeText();\n }\n\n /**\n * Get this document's producer metadata. The producer appears in the\n * \"Document Properties\" section of most PDF readers. For example:\n * ```js\n * const producer = pdfDoc.getProducer()\n * ```\n * @returns A string containing the producer of this document, if it has one.\n */\n getProducer(): string | undefined {\n const producer = this.getInfoDict().lookup(PDFName.Producer);\n if (!producer) return undefined;\n assertIsLiteralOrHexString(producer);\n return producer.decodeText();\n }\n\n /**\n * Get this document's creation date metadata. The creation date appears in\n * the \"Document Properties\" section of most PDF readers. For example:\n * ```js\n * const creationDate = pdfDoc.getCreationDate()\n * ```\n * @returns A Date containing the creation date of this document,\n * if it has one.\n */\n getCreationDate(): Date | undefined {\n const creationDate = this.getInfoDict().lookup(PDFName.CreationDate);\n if (!creationDate) return undefined;\n assertIsLiteralOrHexString(creationDate);\n return creationDate.decodeDate();\n }\n\n /**\n * Get this document's modification date metadata. The modification date\n * appears in the \"Document Properties\" section of most PDF readers.\n * For example:\n * ```js\n * const modification = pdfDoc.getModificationDate()\n * ```\n * @returns A Date containing the modification date of this document,\n * if it has one.\n */\n getModificationDate(): Date | undefined {\n const modificationDate = this.getInfoDict().lookup(PDFName.ModDate);\n if (!modificationDate) return undefined;\n assertIsLiteralOrHexString(modificationDate);\n return modificationDate.decodeDate();\n }\n\n /**\n * Set this document's title metadata. The title will appear in the\n * \"Document Properties\" section of most PDF readers. For example:\n * ```js\n * pdfDoc.setTitle('🥚 The Life of an Egg 🍳')\n * ```\n *\n * To display the title in the window's title bar, set the\n * `showInWindowTitleBar` option to `true` (works for _most_ PDF readers).\n * For example:\n * ```js\n * pdfDoc.setTitle('🥚 The Life of an Egg 🍳', { showInWindowTitleBar: true })\n * ```\n *\n * @param title The title of this document.\n * @param options The options to be used when setting the title.\n */\n setTitle(title: string, options?: SetTitleOptions): void {\n assertIs(title, 'title', ['string']);\n const key = PDFName.of('Title');\n this.getInfoDict().set(key, PDFHexString.fromText(title));\n\n // Indicate that readers should display the title rather than the filename\n if (options?.showInWindowTitleBar) {\n const prefs = this.catalog.getOrCreateViewerPreferences();\n prefs.setDisplayDocTitle(true);\n }\n }\n\n /**\n * Set this document's author metadata. The author will appear in the\n * \"Document Properties\" section of most PDF readers. For example:\n * ```js\n * pdfDoc.setAuthor('Humpty Dumpty')\n * ```\n * @param author The author of this document.\n */\n setAuthor(author: string): void {\n assertIs(author, 'author', ['string']);\n const key = PDFName.of('Author');\n this.getInfoDict().set(key, PDFHexString.fromText(author));\n }\n\n /**\n * Set this document's subject metadata. The subject will appear in the\n * \"Document Properties\" section of most PDF readers. For example:\n * ```js\n * pdfDoc.setSubject('📘 An Epic Tale of Woe 📖')\n * ```\n * @param subject The subject of this document.\n */\n setSubject(subject: string): void {\n assertIs(subject, 'author', ['string']);\n const key = PDFName.of('Subject');\n this.getInfoDict().set(key, PDFHexString.fromText(subject));\n }\n\n /**\n * Set this document's keyword metadata. These keywords will appear in the\n * \"Document Properties\" section of most PDF readers. For example:\n * ```js\n * pdfDoc.setKeywords(['eggs', 'wall', 'fall', 'king', 'horses', 'men'])\n * ```\n * @param keywords An array of keywords associated with this document.\n */\n setKeywords(keywords: string[]): void {\n assertIs(keywords, 'keywords', [Array]);\n const key = PDFName.of('Keywords');\n this.getInfoDict().set(key, PDFHexString.fromText(keywords.join(' ')));\n }\n\n /**\n * Set this document's creator metadata. The creator will appear in the\n * \"Document Properties\" section of most PDF readers. For example:\n * ```js\n * pdfDoc.setCreator('PDF App 9000 🤖')\n * ```\n * @param creator The creator of this document.\n */\n setCreator(creator: string): void {\n assertIs(creator, 'creator', ['string']);\n const key = PDFName.of('Creator');\n this.getInfoDict().set(key, PDFHexString.fromText(creator));\n }\n\n /**\n * Set this document's producer metadata. The producer will appear in the\n * \"Document Properties\" section of most PDF readers. For example:\n * ```js\n * pdfDoc.setProducer('PDF App 9000 🤖')\n * ```\n * @param producer The producer of this document.\n */\n setProducer(producer: string): void {\n assertIs(producer, 'creator', ['string']);\n const key = PDFName.of('Producer');\n this.getInfoDict().set(key, PDFHexString.fromText(producer));\n }\n\n /**\n * Set this document's language metadata. The language will appear in the\n * \"Document Properties\" section of some PDF readers. For example:\n * ```js\n * pdfDoc.setLanguage('en-us')\n * ```\n *\n * @param language An RFC 3066 _Language-Tag_ denoting the language of this\n * document, or an empty string if the language is unknown.\n */\n setLanguage(language: string): void {\n assertIs(language, 'language', ['string']);\n const key = PDFName.of('Lang');\n this.catalog.set(key, PDFString.of(language));\n }\n\n /**\n * Set this document's creation date metadata. The creation date will appear\n * in the \"Document Properties\" section of most PDF readers. For example:\n * ```js\n * pdfDoc.setCreationDate(new Date())\n * ```\n * @param creationDate The date this document was created.\n */\n setCreationDate(creationDate: Date): void {\n assertIs(creationDate, 'creationDate', [[Date, 'Date']]);\n const key = PDFName.of('CreationDate');\n this.getInfoDict().set(key, PDFString.fromDate(creationDate));\n }\n\n /**\n * Set this document's modification date metadata. The modification date will\n * appear in the \"Document Properties\" section of most PDF readers. For\n * example:\n * ```js\n * pdfDoc.setModificationDate(new Date())\n * ```\n * @param modificationDate The date this document was last modified.\n */\n setModificationDate(modificationDate: Date): void {\n assertIs(modificationDate, 'modificationDate', [[Date, 'Date']]);\n const key = PDFName.of('ModDate');\n this.getInfoDict().set(key, PDFString.fromDate(modificationDate));\n }\n\n /**\n * Get the number of pages contained in this document. For example:\n * ```js\n * const totalPages = pdfDoc.getPageCount()\n * ```\n * @returns The number of pages in this document.\n */\n getPageCount(): number {\n if (this.pageCount === undefined) this.pageCount = this.getPages().length;\n return this.pageCount;\n }\n\n /**\n * Get an array of all the pages contained in this document. The pages are\n * stored in the array in the same order that they are rendered in the\n * document. For example:\n * ```js\n * const pages = pdfDoc.getPages()\n * pages[0] // The first page of the document\n * pages[2] // The third page of the document\n * pages[197] // The 198th page of the document\n * ```\n * @returns An array of all the pages contained in this document.\n */\n getPages(): PDFPage[] {\n return this.pageCache.access();\n }\n\n /**\n * Get the page rendered at a particular `index` of the document. For example:\n * ```js\n * pdfDoc.getPage(0) // The first page of the document\n * pdfDoc.getPage(2) // The third page of the document\n * pdfDoc.getPage(197) // The 198th page of the document\n * ```\n * @returns The [[PDFPage]] rendered at the given `index` of the document.\n */\n getPage(index: number): PDFPage {\n const pages = this.getPages();\n assertRange(index, 'index', 0, pages.length - 1);\n return pages[index];\n }\n\n /**\n * Get an array of indices for all the pages contained in this document. The\n * array will contain a range of integers from\n * `0..pdfDoc.getPageCount() - 1`. For example:\n * ```js\n * const pdfDoc = await PDFDocument.create()\n * pdfDoc.addPage()\n * pdfDoc.addPage()\n * pdfDoc.addPage()\n *\n * const indices = pdfDoc.getPageIndices()\n * indices // => [0, 1, 2]\n * ```\n * @returns An array of indices for all pages contained in this document.\n */\n getPageIndices(): number[] {\n return range(0, this.getPageCount());\n }\n\n /**\n * Remove the page at a given index from this document. For example:\n * ```js\n * pdfDoc.removePage(0) // Remove the first page of the document\n * pdfDoc.removePage(2) // Remove the third page of the document\n * pdfDoc.removePage(197) // Remove the 198th page of the document\n * ```\n * Once a page has been removed, it will no longer be rendered at that index\n * in the document.\n * @param index The index of the page to be removed.\n */\n removePage(index: number): void {\n const pageCount = this.getPageCount();\n if (this.pageCount === 0) throw new RemovePageFromEmptyDocumentError();\n assertRange(index, 'index', 0, pageCount - 1);\n this.catalog.removeLeafNode(index);\n this.pageCount = pageCount - 1;\n }\n\n /**\n * Add a page to the end of this document. This method accepts three\n * different value types for the `page` parameter:\n *\n * | Type | Behavior |\n * | ------------------ | ----------------------------------------------------------------------------------- |\n * | `undefined` | Create a new page and add it to the end of this document |\n * | `[number, number]` | Create a new page with the given dimensions and add it to the end of this document |\n * | `PDFPage` | Add the existing page to the end of this document |\n *\n * For example:\n * ```js\n * // page=undefined\n * const newPage = pdfDoc.addPage()\n *\n * // page=[number, number]\n * import { PageSizes } from 'pdf-lib'\n * const newPage1 = pdfDoc.addPage(PageSizes.A7)\n * const newPage2 = pdfDoc.addPage(PageSizes.Letter)\n * const newPage3 = pdfDoc.addPage([500, 750])\n *\n * // page=PDFPage\n * const pdfDoc1 = await PDFDocument.create()\n * const pdfDoc2 = await PDFDocument.load(...)\n * const [existingPage] = await pdfDoc1.copyPages(pdfDoc2, [0])\n * pdfDoc1.addPage(existingPage)\n * ```\n *\n * @param page Optionally, the desired dimensions or existing page.\n * @returns The newly created (or existing) page.\n */\n addPage(page?: PDFPage | [number, number]): PDFPage {\n assertIs(page, 'page', ['undefined', [PDFPage, 'PDFPage'], Array]);\n return this.insertPage(this.getPageCount(), page);\n }\n\n /**\n * Insert a page at a given index within this document. This method accepts\n * three different value types for the `page` parameter:\n *\n * | Type | Behavior |\n * | ------------------ | ------------------------------------------------------------------------------ |\n * | `undefined` | Create a new page and insert it into this document |\n * | `[number, number]` | Create a new page with the given dimensions and insert it into this document |\n * | `PDFPage` | Insert the existing page into this document |\n *\n * For example:\n * ```js\n * // page=undefined\n * const newPage = pdfDoc.insertPage(2)\n *\n * // page=[number, number]\n * import { PageSizes } from 'pdf-lib'\n * const newPage1 = pdfDoc.insertPage(2, PageSizes.A7)\n * const newPage2 = pdfDoc.insertPage(0, PageSizes.Letter)\n * const newPage3 = pdfDoc.insertPage(198, [500, 750])\n *\n * // page=PDFPage\n * const pdfDoc1 = await PDFDocument.create()\n * const pdfDoc2 = await PDFDocument.load(...)\n * const [existingPage] = await pdfDoc1.copyPages(pdfDoc2, [0])\n * pdfDoc1.insertPage(0, existingPage)\n * ```\n *\n * @param index The index at which the page should be inserted (zero-based).\n * @param page Optionally, the desired dimensions or existing page.\n * @returns The newly created (or existing) page.\n */\n insertPage(index: number, page?: PDFPage | [number, number]): PDFPage {\n const pageCount = this.getPageCount();\n assertRange(index, 'index', 0, pageCount);\n assertIs(page, 'page', ['undefined', [PDFPage, 'PDFPage'], Array]);\n if (!page || Array.isArray(page)) {\n const dims = Array.isArray(page) ? page : PageSizes.A4;\n page = PDFPage.create(this);\n page.setSize(...dims);\n } else if (page.doc !== this) {\n throw new ForeignPageError();\n }\n\n const parentRef = this.catalog.insertLeafNode(page.ref, index);\n page.node.setParent(parentRef);\n\n this.pageMap.set(page.node, page);\n this.pageCache.invalidate();\n\n this.pageCount = pageCount + 1;\n\n return page;\n }\n\n /**\n * Copy pages from a source document into this document. Allows pages to be\n * copied between different [[PDFDocument]] instances. For example:\n * ```js\n * const pdfDoc = await PDFDocument.create()\n * const srcDoc = await PDFDocument.load(...)\n *\n * const copiedPages = await pdfDoc.copyPages(srcDoc, [0, 3, 89])\n * const [firstPage, fourthPage, ninetiethPage] = copiedPages;\n *\n * pdfDoc.addPage(fourthPage)\n * pdfDoc.insertPage(0, ninetiethPage)\n * pdfDoc.addPage(firstPage)\n * ```\n * @param srcDoc The document from which pages should be copied.\n * @param indices The indices of the pages that should be copied.\n * @returns Resolves with an array of pages copied into this document.\n */\n async copyPages(srcDoc: PDFDocument, indices: number[]): Promise {\n assertIs(srcDoc, 'srcDoc', [[PDFDocument, 'PDFDocument']]);\n assertIs(indices, 'indices', [Array]);\n await srcDoc.flush();\n const copier = PDFObjectCopier.for(srcDoc.context, this.context);\n const srcPages = srcDoc.getPages();\n const copiedPages: PDFPage[] = new Array(indices.length);\n for (let idx = 0, len = indices.length; idx < len; idx++) {\n const srcPage = srcPages[indices[idx]];\n const copiedPage = copier.copy(srcPage.node);\n const ref = this.context.register(copiedPage);\n copiedPages[idx] = PDFPage.of(copiedPage, ref, this);\n }\n return copiedPages;\n }\n\n /**\n * Get a copy of this document.\n *\n * For example:\n * ```js\n * const srcDoc = await PDFDocument.load(...)\n * const pdfDoc = await srcDoc.copy()\n * ```\n *\n * > **NOTE:** This method won't copy all information over to the new\n * > document (acroforms, outlines, etc...).\n *\n * @returns Resolves with a copy this document.\n */\n async copy(): Promise {\n const pdfCopy = await PDFDocument.create();\n const contentPages = await pdfCopy.copyPages(this, this.getPageIndices());\n\n for (let idx = 0, len = contentPages.length; idx < len; idx++) {\n pdfCopy.addPage(contentPages[idx]);\n }\n\n if (this.getAuthor() !== undefined) {\n pdfCopy.setAuthor(this.getAuthor()!);\n }\n if (this.getCreationDate() !== undefined) {\n pdfCopy.setCreationDate(this.getCreationDate()!);\n }\n if (this.getCreator() !== undefined) {\n pdfCopy.setCreator(this.getCreator()!);\n }\n if (this.getModificationDate() !== undefined) {\n pdfCopy.setModificationDate(this.getModificationDate()!);\n }\n if (this.getProducer() !== undefined) {\n pdfCopy.setProducer(this.getProducer()!);\n }\n if (this.getSubject() !== undefined) {\n pdfCopy.setSubject(this.getSubject()!);\n }\n if (this.getTitle() !== undefined) {\n pdfCopy.setTitle(this.getTitle()!);\n }\n pdfCopy.defaultWordBreaks = this.defaultWordBreaks;\n\n return pdfCopy;\n }\n\n /**\n * Add JavaScript to this document. The supplied `script` is executed when the\n * document is opened. The `script` can be used to perform some operation\n * when the document is opened (e.g. logging to the console), or it can be\n * used to define a function that can be referenced later in a JavaScript\n * action. For example:\n * ```js\n * // Show \"Hello World!\" in the console when the PDF is opened\n * pdfDoc.addJavaScript(\n * 'main',\n * 'console.show(); console.println(\"Hello World!\");'\n * );\n *\n * // Define a function named \"foo\" that can be called in JavaScript Actions\n * pdfDoc.addJavaScript(\n * 'foo',\n * 'function foo() { return \"foo\"; }'\n * );\n * ```\n * See the [JavaScript for Acrobat API Reference](https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/js_api_reference.pdf)\n * for details.\n * @param name The name of the script. Must be unique per document.\n * @param script The JavaScript to execute.\n */\n addJavaScript(name: string, script: string) {\n assertIs(name, 'name', ['string']);\n assertIs(script, 'script', ['string']);\n\n const embedder = JavaScriptEmbedder.for(script, name);\n\n const ref = this.context.nextRef();\n const javaScript = PDFJavaScript.of(ref, this, embedder);\n this.javaScripts.push(javaScript);\n }\n\n /**\n * Add an attachment to this document. Attachments are visible in the\n * \"Attachments\" panel of Adobe Acrobat and some other PDF readers. Any\n * type of file can be added as an attachment. This includes, but is not\n * limited to, `.png`, `.jpg`, `.pdf`, `.csv`, `.docx`, and `.xlsx` files.\n *\n * The input data can be provided in multiple formats:\n *\n * | Type | Contents |\n * | ------------- | -------------------------------------------------------------- |\n * | `string` | A base64 encoded string (or data URI) containing an attachment |\n * | `Uint8Array` | The raw bytes of an attachment |\n * | `ArrayBuffer` | The raw bytes of an attachment |\n *\n * For example:\n * ```js\n * // attachment=string\n * await pdfDoc.attach('/9j/4AAQSkZJRgABAQAAAQABAAD/2wBD...', 'cat_riding_unicorn.jpg', {\n * mimeType: 'image/jpeg',\n * description: 'Cool cat riding a unicorn! 🦄🐈🕶️',\n * creationDate: new Date('2019/12/01'),\n * modificationDate: new Date('2020/04/19'),\n * })\n * await pdfDoc.attach('data:image/jpeg;base64,/9j/4AAQ...', 'cat_riding_unicorn.jpg', {\n * mimeType: 'image/jpeg',\n * description: 'Cool cat riding a unicorn! 🦄🐈🕶️',\n * creationDate: new Date('2019/12/01'),\n * modificationDate: new Date('2020/04/19'),\n * })\n *\n * // attachment=Uint8Array\n * import fs from 'fs'\n * const uint8Array = fs.readFileSync('cat_riding_unicorn.jpg')\n * await pdfDoc.attach(uint8Array, 'cat_riding_unicorn.jpg', {\n * mimeType: 'image/jpeg',\n * description: 'Cool cat riding a unicorn! 🦄🐈🕶️',\n * creationDate: new Date('2019/12/01'),\n * modificationDate: new Date('2020/04/19'),\n * })\n *\n * // attachment=ArrayBuffer\n * const url = 'https://pdf-lib.js.org/assets/cat_riding_unicorn.jpg'\n * const arrayBuffer = await fetch(url).then(res => res.arrayBuffer())\n * await pdfDoc.attach(arrayBuffer, 'cat_riding_unicorn.jpg', {\n * mimeType: 'image/jpeg',\n * description: 'Cool cat riding a unicorn! 🦄🐈🕶️',\n * creationDate: new Date('2019/12/01'),\n * modificationDate: new Date('2020/04/19'),\n * })\n * ```\n *\n * @param attachment The input data containing the file to be attached.\n * @param name The name of the file to be attached.\n * @returns Resolves when the attachment is complete.\n */\n async attach(\n attachment: string | Uint8Array | ArrayBuffer,\n name: string,\n options: AttachmentOptions = {},\n ): Promise {\n assertIs(attachment, 'attachment', ['string', Uint8Array, ArrayBuffer]);\n assertIs(name, 'name', ['string']);\n assertOrUndefined(options.mimeType, 'mimeType', ['string']);\n assertOrUndefined(options.description, 'description', ['string']);\n assertOrUndefined(options.creationDate, 'options.creationDate', [Date]);\n assertOrUndefined(options.modificationDate, 'options.modificationDate', [\n Date,\n ]);\n assertIsOneOfOrUndefined(\n options.afRelationship,\n 'options.afRelationship',\n AFRelationship,\n );\n\n const bytes = toUint8Array(attachment);\n const embedder = FileEmbedder.for(bytes, name, options);\n\n const ref = this.context.nextRef();\n const embeddedFile = PDFEmbeddedFile.of(ref, this, embedder);\n this.embeddedFiles.push(embeddedFile);\n }\n\n /**\n * Embed a font into this document. The input data can be provided in multiple\n * formats:\n *\n * | Type | Contents |\n * | --------------- | ------------------------------------------------------- |\n * | `StandardFonts` | One of the standard 14 fonts |\n * | `string` | A base64 encoded string (or data URI) containing a font |\n * | `Uint8Array` | The raw bytes of a font |\n * | `ArrayBuffer` | The raw bytes of a font |\n *\n * For example:\n * ```js\n * // font=StandardFonts\n * import { StandardFonts } from 'pdf-lib'\n * const font1 = await pdfDoc.embedFont(StandardFonts.Helvetica)\n *\n * // font=string\n * const font2 = await pdfDoc.embedFont('AAEAAAAVAQAABABQRFNJRx/upe...')\n * const font3 = await pdfDoc.embedFont('data:font/opentype;base64,AAEAAA...')\n *\n * // font=Uint8Array\n * import fs from 'fs'\n * const font4 = await pdfDoc.embedFont(fs.readFileSync('Ubuntu-R.ttf'))\n *\n * // font=ArrayBuffer\n * const url = 'https://pdf-lib.js.org/assets/ubuntu/Ubuntu-R.ttf'\n * const ubuntuBytes = await fetch(url).then(res => res.arrayBuffer())\n * const font5 = await pdfDoc.embedFont(ubuntuBytes)\n * ```\n * See also: [[registerFontkit]]\n * @param font The input data for a font.\n * @param options The options to be used when embedding the font.\n * @returns Resolves with the embedded font.\n */\n async embedFont(\n font: StandardFonts | string | Uint8Array | ArrayBuffer,\n options: EmbedFontOptions = {},\n ): Promise {\n const { subset = false, customName, features } = options;\n\n assertIs(font, 'font', ['string', Uint8Array, ArrayBuffer]);\n assertIs(subset, 'subset', ['boolean']);\n\n let embedder: CustomFontEmbedder | StandardFontEmbedder;\n if (isStandardFont(font)) {\n embedder = StandardFontEmbedder.for(font, customName);\n } else if (canBeConvertedToUint8Array(font)) {\n const bytes = toUint8Array(font);\n const fontkit = this.assertFontkit();\n embedder = subset\n ? await CustomFontSubsetEmbedder.for(\n fontkit,\n bytes,\n customName,\n features,\n )\n : await CustomFontEmbedder.for(fontkit, bytes, customName, features);\n } else {\n throw new TypeError(\n '`font` must be one of `StandardFonts | string | Uint8Array | ArrayBuffer`',\n );\n }\n\n const ref = this.context.nextRef();\n const pdfFont = PDFFont.of(ref, this, embedder);\n this.fonts.push(pdfFont);\n\n return pdfFont;\n }\n\n /**\n * Embed a standard font into this document.\n * For example:\n * ```js\n * import { StandardFonts } from 'pdf-lib'\n * const helveticaFont = pdfDoc.embedFont(StandardFonts.Helvetica)\n * ```\n * @param font The standard font to be embedded.\n * @param customName The name to be used when embedding the font.\n * @returns The embedded font.\n */\n embedStandardFont(font: StandardFonts, customName?: string): PDFFont {\n assertIs(font, 'font', ['string']);\n if (!isStandardFont(font)) {\n throw new TypeError('`font` must be one of type `StandardFonts`');\n }\n\n const embedder = StandardFontEmbedder.for(font, customName);\n\n const ref = this.context.nextRef();\n const pdfFont = PDFFont.of(ref, this, embedder);\n this.fonts.push(pdfFont);\n\n return pdfFont;\n }\n\n /**\n * Embed a JPEG image into this document. The input data can be provided in\n * multiple formats:\n *\n * | Type | Contents |\n * | ------------- | ------------------------------------------------------------- |\n * | `string` | A base64 encoded string (or data URI) containing a JPEG image |\n * | `Uint8Array` | The raw bytes of a JPEG image |\n * | `ArrayBuffer` | The raw bytes of a JPEG image |\n *\n * For example:\n * ```js\n * // jpg=string\n * const image1 = await pdfDoc.embedJpg('/9j/4AAQSkZJRgABAQAAAQABAAD/2wBD...')\n * const image2 = await pdfDoc.embedJpg('data:image/jpeg;base64,/9j/4AAQ...')\n *\n * // jpg=Uint8Array\n * import fs from 'fs'\n * const uint8Array = fs.readFileSync('cat_riding_unicorn.jpg')\n * const image3 = await pdfDoc.embedJpg(uint8Array)\n *\n * // jpg=ArrayBuffer\n * const url = 'https://pdf-lib.js.org/assets/cat_riding_unicorn.jpg'\n * const arrayBuffer = await fetch(url).then(res => res.arrayBuffer())\n * const image4 = await pdfDoc.embedJpg(arrayBuffer)\n * ```\n *\n * @param jpg The input data for a JPEG image.\n * @returns Resolves with the embedded image.\n */\n async embedJpg(jpg: string | Uint8Array | ArrayBuffer): Promise {\n assertIs(jpg, 'jpg', ['string', Uint8Array, ArrayBuffer]);\n const bytes = toUint8Array(jpg);\n const embedder = await JpegEmbedder.for(bytes);\n const ref = this.context.nextRef();\n const pdfImage = PDFImage.of(ref, this, embedder);\n this.images.push(pdfImage);\n return pdfImage;\n }\n\n /**\n * Embed a PNG image into this document. The input data can be provided in\n * multiple formats:\n *\n * | Type | Contents |\n * | ------------- | ------------------------------------------------------------ |\n * | `string` | A base64 encoded string (or data URI) containing a PNG image |\n * | `Uint8Array` | The raw bytes of a PNG image |\n * | `ArrayBuffer` | The raw bytes of a PNG image |\n *\n * For example:\n * ```js\n * // png=string\n * const image1 = await pdfDoc.embedPng('iVBORw0KGgoAAAANSUhEUgAAAlgAAAF3...')\n * const image2 = await pdfDoc.embedPng('data:image/png;base64,iVBORw0KGg...')\n *\n * // png=Uint8Array\n * import fs from 'fs'\n * const uint8Array = fs.readFileSync('small_mario.png')\n * const image3 = await pdfDoc.embedPng(uint8Array)\n *\n * // png=ArrayBuffer\n * const url = 'https://pdf-lib.js.org/assets/small_mario.png'\n * const arrayBuffer = await fetch(url).then(res => res.arrayBuffer())\n * const image4 = await pdfDoc.embedPng(arrayBuffer)\n * ```\n *\n * @param png The input data for a PNG image.\n * @returns Resolves with the embedded image.\n */\n async embedPng(png: string | Uint8Array | ArrayBuffer): Promise {\n assertIs(png, 'png', ['string', Uint8Array, ArrayBuffer]);\n const bytes = toUint8Array(png);\n const embedder = await PngEmbedder.for(bytes);\n const ref = this.context.nextRef();\n const pdfImage = PDFImage.of(ref, this, embedder);\n this.images.push(pdfImage);\n return pdfImage;\n }\n\n /**\n * Embed one or more PDF pages into this document.\n *\n * For example:\n * ```js\n * const pdfDoc = await PDFDocument.create()\n *\n * const sourcePdfUrl = 'https://pdf-lib.js.org/assets/with_large_page_count.pdf'\n * const sourcePdf = await fetch(sourcePdfUrl).then((res) => res.arrayBuffer())\n *\n * // Embed page 74 of `sourcePdf` into `pdfDoc`\n * const [embeddedPage] = await pdfDoc.embedPdf(sourcePdf, [73])\n * ```\n *\n * See [[PDFDocument.load]] for examples of the allowed input data formats.\n *\n * @param pdf The input data containing a PDF document.\n * @param indices The indices of the pages that should be embedded.\n * @returns Resolves with an array of the embedded pages.\n */\n async embedPdf(\n pdf: string | Uint8Array | ArrayBuffer | PDFDocument,\n indices: number[] = [0],\n ): Promise {\n assertIs(pdf, 'pdf', [\n 'string',\n Uint8Array,\n ArrayBuffer,\n [PDFDocument, 'PDFDocument'],\n ]);\n assertIs(indices, 'indices', [Array]);\n\n const srcDoc =\n pdf instanceof PDFDocument ? pdf : await PDFDocument.load(pdf);\n\n const srcPages = pluckIndices(srcDoc.getPages(), indices);\n\n return this.embedPages(srcPages);\n }\n\n /**\n * Embed a single PDF page into this document.\n *\n * For example:\n * ```js\n * const pdfDoc = await PDFDocument.create()\n *\n * const sourcePdfUrl = 'https://pdf-lib.js.org/assets/with_large_page_count.pdf'\n * const sourceBuffer = await fetch(sourcePdfUrl).then((res) => res.arrayBuffer())\n * const sourcePdfDoc = await PDFDocument.load(sourceBuffer)\n * const sourcePdfPage = sourcePdfDoc.getPages()[73]\n *\n * const embeddedPage = await pdfDoc.embedPage(\n * sourcePdfPage,\n *\n * // Clip a section of the source page so that we only embed part of it\n * { left: 100, right: 450, bottom: 330, top: 570 },\n *\n * // Translate all drawings of the embedded page by (10, 200) units\n * [1, 0, 0, 1, 10, 200],\n * )\n * ```\n *\n * @param page The page to be embedded.\n * @param boundingBox\n * Optionally, an area of the source page that should be embedded\n * (defaults to entire page).\n * @param transformationMatrix\n * Optionally, a transformation matrix that is always applied to the embedded\n * page anywhere it is drawn.\n * @returns Resolves with the embedded pdf page.\n */\n async embedPage(\n page: PDFPage,\n boundingBox?: PageBoundingBox,\n transformationMatrix?: TransformationMatrix,\n ): Promise {\n assertIs(page, 'page', [[PDFPage, 'PDFPage']]);\n const [embeddedPage] = await this.embedPages(\n [page],\n [boundingBox],\n [transformationMatrix],\n );\n return embeddedPage;\n }\n\n /**\n * Embed one or more PDF pages into this document.\n *\n * For example:\n * ```js\n * const pdfDoc = await PDFDocument.create()\n *\n * const sourcePdfUrl = 'https://pdf-lib.js.org/assets/with_large_page_count.pdf'\n * const sourceBuffer = await fetch(sourcePdfUrl).then((res) => res.arrayBuffer())\n * const sourcePdfDoc = await PDFDocument.load(sourceBuffer)\n *\n * const page1 = sourcePdfDoc.getPages()[0]\n * const page2 = sourcePdfDoc.getPages()[52]\n * const page3 = sourcePdfDoc.getPages()[73]\n *\n * const embeddedPages = await pdfDoc.embedPages([page1, page2, page3])\n * ```\n *\n * @param page\n * The pages to be embedded (they must all share the same context).\n * @param boundingBoxes\n * Optionally, an array of clipping boundaries - one for each page\n * (defaults to entirety of each page).\n * @param transformationMatrices\n * Optionally, an array of transformation matrices - one for each page\n * (each page's transformation will apply anywhere it is drawn).\n * @returns Resolves with an array of the embedded pdf pages.\n */\n async embedPages(\n pages: PDFPage[],\n boundingBoxes: (PageBoundingBox | undefined)[] = [],\n transformationMatrices: (TransformationMatrix | undefined)[] = [],\n ) {\n if (pages.length === 0) return [];\n\n // Assert all pages have the same context\n for (let idx = 0, len = pages.length - 1; idx < len; idx++) {\n const currPage = pages[idx];\n const nextPage = pages[idx + 1];\n if (currPage.node.context !== nextPage.node.context) {\n throw new PageEmbeddingMismatchedContextError();\n }\n }\n\n const context = pages[0].node.context;\n const maybeCopyPage =\n context === this.context\n ? (p: PDFPageLeaf) => p\n : PDFObjectCopier.for(context, this.context).copy;\n\n const embeddedPages = new Array(pages.length);\n for (let idx = 0, len = pages.length; idx < len; idx++) {\n const page = maybeCopyPage(pages[idx].node);\n const box = boundingBoxes[idx];\n const matrix = transformationMatrices[idx];\n\n const embedder = await PDFPageEmbedder.for(page, box, matrix);\n\n const ref = this.context.nextRef();\n embeddedPages[idx] = PDFEmbeddedPage.of(ref, this, embedder);\n }\n\n this.embeddedPages.push(...embeddedPages);\n\n return embeddedPages;\n }\n\n /**\n * > **NOTE:** You shouldn't need to call this method directly. The [[save]]\n * > and [[saveAsBase64]] methods will automatically ensure that all embedded\n * > assets are flushed before serializing the document.\n *\n * Flush all embedded fonts, PDF pages, and images to this document's\n * [[context]].\n *\n * @returns Resolves when the flush is complete.\n */\n async flush(): Promise {\n await this.embedAll(this.fonts);\n await this.embedAll(this.images);\n await this.embedAll(this.embeddedPages);\n await this.embedAll(this.embeddedFiles);\n await this.embedAll(this.javaScripts);\n }\n\n /**\n * Serialize this document to an array of bytes making up a PDF file.\n * For example:\n * ```js\n * const pdfBytes = await pdfDoc.save()\n * ```\n *\n * There are a number of things you can do with the serialized document,\n * depending on the JavaScript environment you're running in:\n * * Write it to a file in Node or React Native\n * * Download it as a Blob in the browser\n * * Render it in an `iframe`\n *\n * @param options The options to be used when saving the document.\n * @returns Resolves with the bytes of the serialized document.\n */\n async save(options: SaveOptions = {}): Promise {\n const {\n useObjectStreams = true,\n addDefaultPage = true,\n objectsPerTick = 50,\n updateFieldAppearances = true,\n } = options;\n\n assertIs(useObjectStreams, 'useObjectStreams', ['boolean']);\n assertIs(addDefaultPage, 'addDefaultPage', ['boolean']);\n assertIs(objectsPerTick, 'objectsPerTick', ['number']);\n assertIs(updateFieldAppearances, 'updateFieldAppearances', ['boolean']);\n\n if (addDefaultPage && this.getPageCount() === 0) this.addPage();\n\n if (updateFieldAppearances) {\n const form = this.formCache.getValue();\n if (form) form.updateFieldAppearances();\n }\n\n await this.flush();\n\n const Writer = useObjectStreams ? PDFStreamWriter : PDFWriter;\n return Writer.forContext(this.context, objectsPerTick).serializeToBuffer();\n }\n\n /**\n * Serialize this document to a base64 encoded string or data URI making up a\n * PDF file. For example:\n * ```js\n * const base64String = await pdfDoc.saveAsBase64()\n * base64String // => 'JVBERi0xLjcKJYGBgYEKC...'\n *\n * const base64DataUri = await pdfDoc.saveAsBase64({ dataUri: true })\n * base64DataUri // => 'data:application/pdf;base64,JVBERi0xLjcKJYGBgYEKC...'\n * ```\n *\n * @param options The options to be used when saving the document.\n * @returns Resolves with a base64 encoded string or data URI of the\n * serialized document.\n */\n async saveAsBase64(options: Base64SaveOptions = {}): Promise {\n const { dataUri = false, ...otherOptions } = options;\n assertIs(dataUri, 'dataUri', ['boolean']);\n const bytes = await this.save(otherOptions);\n const base64 = encodeToBase64(bytes);\n return dataUri ? `data:application/pdf;base64,${base64}` : base64;\n }\n\n findPageForAnnotationRef(ref: PDFRef): PDFPage | undefined {\n const pages = this.getPages();\n for (let idx = 0, len = pages.length; idx < len; idx++) {\n const page = pages[idx];\n const annotations = page.node.Annots();\n\n if (annotations?.indexOf(ref) !== undefined) {\n return page;\n }\n }\n\n return undefined;\n }\n\n private async embedAll(embeddables: Embeddable[]): Promise {\n for (let idx = 0, len = embeddables.length; idx < len; idx++) {\n await embeddables[idx].embed();\n }\n }\n\n private updateInfoDict(): void {\n const pdfLib = `pdf-lib (https://github.com/Hopding/pdf-lib)`;\n const now = new Date();\n\n const info = this.getInfoDict();\n\n this.setProducer(pdfLib);\n this.setModificationDate(now);\n\n if (!info.get(PDFName.of('Creator'))) this.setCreator(pdfLib);\n if (!info.get(PDFName.of('CreationDate'))) this.setCreationDate(now);\n }\n\n private getInfoDict(): PDFDict {\n const existingInfo = this.context.lookup(this.context.trailerInfo.Info);\n if (existingInfo instanceof PDFDict) return existingInfo;\n\n const newInfo = this.context.obj({});\n this.context.trailerInfo.Info = this.context.register(newInfo);\n\n return newInfo;\n }\n\n private assertFontkit(): Fontkit {\n if (!this.fontkit) throw new FontkitNotRegisteredError();\n return this.fontkit;\n }\n\n private computePages = (): PDFPage[] => {\n const pages: PDFPage[] = [];\n this.catalog.Pages().traverse((node, ref) => {\n if (node instanceof PDFPageLeaf) {\n let page = this.pageMap.get(node);\n if (!page) {\n page = PDFPage.of(node, ref, this);\n this.pageMap.set(node, page);\n }\n pages.push(page);\n }\n });\n return pages;\n };\n\n private getOrCreateForm = (): PDFForm => {\n const acroForm = this.catalog.getOrCreateAcroForm();\n return PDFForm.of(acroForm, this);\n };\n}\n\n/* tslint:disable-next-line only-arrow-functions */\nfunction assertIsLiteralOrHexString(\n pdfObject: PDFObject,\n): asserts pdfObject is PDFHexString | PDFString {\n if (\n !(pdfObject instanceof PDFHexString) &&\n !(pdfObject instanceof PDFString)\n ) {\n throw new UnexpectedObjectTypeError([PDFHexString, PDFString], pdfObject);\n }\n}\n","import { Color } from 'src/api/colors';\nimport PDFFont from 'src/api/PDFFont';\nimport { Rotation } from 'src/api/rotations';\nimport { LineCapStyle } from 'src/api/operators';\n\nexport enum BlendMode {\n Normal = 'Normal',\n Multiply = 'Multiply',\n Screen = 'Screen',\n Overlay = 'Overlay',\n Darken = 'Darken',\n Lighten = 'Lighten',\n ColorDodge = 'ColorDodge',\n ColorBurn = 'ColorBurn',\n HardLight = 'HardLight',\n SoftLight = 'SoftLight',\n Difference = 'Difference',\n Exclusion = 'Exclusion',\n}\n\nexport interface PDFPageDrawTextOptions {\n color?: Color;\n opacity?: number;\n blendMode?: BlendMode;\n font?: PDFFont;\n size?: number;\n rotate?: Rotation;\n xSkew?: Rotation;\n ySkew?: Rotation;\n x?: number;\n y?: number;\n lineHeight?: number;\n maxWidth?: number;\n wordBreaks?: string[];\n}\n\nexport interface PDFPageDrawImageOptions {\n x?: number;\n y?: number;\n width?: number;\n height?: number;\n rotate?: Rotation;\n xSkew?: Rotation;\n ySkew?: Rotation;\n opacity?: number;\n blendMode?: BlendMode;\n}\n\nexport interface PDFPageDrawPageOptions {\n x?: number;\n y?: number;\n xScale?: number;\n yScale?: number;\n width?: number;\n height?: number;\n rotate?: Rotation;\n xSkew?: Rotation;\n ySkew?: Rotation;\n opacity?: number;\n blendMode?: BlendMode;\n}\n\nexport interface PDFPageDrawSVGOptions {\n x?: number;\n y?: number;\n scale?: number;\n rotate?: Rotation;\n borderWidth?: number;\n color?: Color;\n opacity?: number;\n borderColor?: Color;\n borderOpacity?: number;\n borderDashArray?: number[];\n borderDashPhase?: number;\n borderLineCap?: LineCapStyle;\n blendMode?: BlendMode;\n}\n\nexport interface PDFPageDrawLineOptions {\n start: { x: number; y: number };\n end: { x: number; y: number };\n thickness?: number;\n color?: Color;\n opacity?: number;\n lineCap?: LineCapStyle;\n dashArray?: number[];\n dashPhase?: number;\n blendMode?: BlendMode;\n}\n\nexport interface PDFPageDrawRectangleOptions {\n x?: number;\n y?: number;\n width?: number;\n height?: number;\n rotate?: Rotation;\n xSkew?: Rotation;\n ySkew?: Rotation;\n borderWidth?: number;\n color?: Color;\n opacity?: number;\n borderColor?: Color;\n borderOpacity?: number;\n borderDashArray?: number[];\n borderDashPhase?: number;\n borderLineCap?: LineCapStyle;\n blendMode?: BlendMode;\n}\n\nexport interface PDFPageDrawSquareOptions {\n x?: number;\n y?: number;\n size?: number;\n rotate?: Rotation;\n xSkew?: Rotation;\n ySkew?: Rotation;\n borderWidth?: number;\n color?: Color;\n opacity?: number;\n borderColor?: Color;\n borderOpacity?: number;\n borderDashArray?: number[];\n borderDashPhase?: number;\n borderLineCap?: LineCapStyle;\n blendMode?: BlendMode;\n}\n\nexport interface PDFPageDrawEllipseOptions {\n x?: number;\n y?: number;\n xScale?: number;\n yScale?: number;\n rotate?: Rotation;\n color?: Color;\n opacity?: number;\n borderColor?: Color;\n borderOpacity?: number;\n borderWidth?: number;\n borderDashArray?: number[];\n borderDashPhase?: number;\n borderLineCap?: LineCapStyle;\n blendMode?: BlendMode;\n}\n\nexport interface PDFPageDrawCircleOptions {\n x?: number;\n y?: number;\n size?: number;\n color?: Color;\n opacity?: number;\n borderColor?: Color;\n borderOpacity?: number;\n borderWidth?: number;\n borderDashArray?: number[];\n borderDashPhase?: number;\n borderLineCap?: LineCapStyle;\n blendMode?: BlendMode;\n}\n","import { Color, rgb } from 'src/api/colors';\nimport {\n drawImage,\n drawLine,\n drawLinesOfText,\n drawPage,\n drawRectangle,\n drawSvgPath,\n drawEllipse,\n} from 'src/api/operations';\nimport {\n popGraphicsState,\n pushGraphicsState,\n translate,\n LineCapStyle,\n scale,\n} from 'src/api/operators';\nimport PDFDocument from 'src/api/PDFDocument';\nimport PDFEmbeddedPage from 'src/api/PDFEmbeddedPage';\nimport PDFFont from 'src/api/PDFFont';\nimport PDFImage from 'src/api/PDFImage';\nimport {\n PDFPageDrawCircleOptions,\n PDFPageDrawEllipseOptions,\n PDFPageDrawImageOptions,\n PDFPageDrawLineOptions,\n PDFPageDrawPageOptions,\n PDFPageDrawRectangleOptions,\n PDFPageDrawSquareOptions,\n PDFPageDrawSVGOptions,\n PDFPageDrawTextOptions,\n BlendMode,\n} from 'src/api/PDFPageOptions';\nimport { degrees, Rotation, toDegrees } from 'src/api/rotations';\nimport { StandardFonts } from 'src/api/StandardFonts';\nimport {\n PDFContentStream,\n PDFHexString,\n PDFName,\n PDFOperator,\n PDFPageLeaf,\n PDFRef,\n PDFDict,\n PDFArray,\n} from 'src/core';\nimport {\n assertEachIs,\n assertIs,\n assertMultiple,\n assertOrUndefined,\n breakTextIntoLines,\n cleanText,\n rectanglesAreEqual,\n lineSplit,\n assertRangeOrUndefined,\n assertIsOneOfOrUndefined,\n} from 'src/utils';\n\n/**\n * Represents a single page of a [[PDFDocument]].\n */\nexport default class PDFPage {\n /**\n * > **NOTE:** You probably don't want to call this method directly. Instead,\n * > consider using the [[PDFDocument.addPage]] and [[PDFDocument.insertPage]]\n * > methods, which can create instances of [[PDFPage]] for you.\n *\n * Create an instance of [[PDFPage]] from an existing leaf node.\n *\n * @param leafNode The leaf node to be wrapped.\n * @param ref The unique reference for the page.\n * @param doc The document to which the page will belong.\n */\n static of = (leafNode: PDFPageLeaf, ref: PDFRef, doc: PDFDocument) =>\n new PDFPage(leafNode, ref, doc);\n\n /**\n * > **NOTE:** You probably don't want to call this method directly. Instead,\n * > consider using the [[PDFDocument.addPage]] and [[PDFDocument.insertPage]]\n * > methods, which can create instances of [[PDFPage]] for you.\n *\n * Create an instance of [[PDFPage]].\n *\n * @param doc The document to which the page will belong.\n */\n static create = (doc: PDFDocument) => {\n assertIs(doc, 'doc', [[PDFDocument, 'PDFDocument']]);\n const dummyRef = PDFRef.of(-1);\n const pageLeaf = PDFPageLeaf.withContextAndParent(doc.context, dummyRef);\n const pageRef = doc.context.register(pageLeaf);\n return new PDFPage(pageLeaf, pageRef, doc);\n };\n\n /** The low-level PDFDictionary wrapped by this page. */\n readonly node: PDFPageLeaf;\n\n /** The unique reference assigned to this page within the document. */\n readonly ref: PDFRef;\n\n /** The document to which this page belongs. */\n readonly doc: PDFDocument;\n\n private fontKey?: PDFName;\n private font?: PDFFont;\n private fontSize = 24;\n private fontColor = rgb(0, 0, 0) as Color;\n private lineHeight = 24;\n private x = 0;\n private y = 0;\n private contentStream?: PDFContentStream;\n private contentStreamRef?: PDFRef;\n\n private constructor(leafNode: PDFPageLeaf, ref: PDFRef, doc: PDFDocument) {\n assertIs(leafNode, 'leafNode', [[PDFPageLeaf, 'PDFPageLeaf']]);\n assertIs(ref, 'ref', [[PDFRef, 'PDFRef']]);\n assertIs(doc, 'doc', [[PDFDocument, 'PDFDocument']]);\n\n this.node = leafNode;\n this.ref = ref;\n this.doc = doc;\n }\n\n /**\n * Rotate this page by a multiple of 90 degrees. For example:\n * ```js\n * import { degrees } from 'pdf-lib'\n *\n * page.setRotation(degrees(-90))\n * page.setRotation(degrees(0))\n * page.setRotation(degrees(90))\n * page.setRotation(degrees(180))\n * page.setRotation(degrees(270))\n * ```\n * @param angle The angle to rotate this page.\n */\n setRotation(angle: Rotation): void {\n const degreesAngle = toDegrees(angle);\n assertMultiple(degreesAngle, 'degreesAngle', 90);\n this.node.set(PDFName.of('Rotate'), this.doc.context.obj(degreesAngle));\n }\n\n /**\n * Get this page's rotation angle in degrees. For example:\n * ```js\n * const rotationAngle = page.getRotation().angle;\n * ```\n * @returns The rotation angle of the page in degrees (always a multiple of\n * 90 degrees).\n */\n getRotation(): Rotation {\n const Rotate = this.node.Rotate();\n return degrees(Rotate ? Rotate.asNumber() : 0);\n }\n\n /**\n * Resize this page by increasing or decreasing its width and height. For\n * example:\n * ```js\n * page.setSize(250, 500)\n * page.setSize(page.getWidth() + 50, page.getHeight() + 100)\n * page.setSize(page.getWidth() - 50, page.getHeight() - 100)\n * ```\n *\n * Note that the PDF specification does not allow for pages to have explicit\n * widths and heights. Instead it defines the \"size\" of a page in terms of\n * five rectangles: the MediaBox, CropBox, BleedBox, TrimBox, and ArtBox. As a\n * result, this method cannot directly change the width and height of a page.\n * Instead, it works by adjusting these five boxes.\n *\n * This method performs the following steps:\n * 1. Set width & height of MediaBox.\n * 2. Set width & height of CropBox, if it has same dimensions as MediaBox.\n * 3. Set width & height of BleedBox, if it has same dimensions as MediaBox.\n * 4. Set width & height of TrimBox, if it has same dimensions as MediaBox.\n * 5. Set width & height of ArtBox, if it has same dimensions as MediaBox.\n *\n * This approach works well for most PDF documents as all PDF pages must\n * have a MediaBox, but relatively few have a CropBox, BleedBox, TrimBox, or\n * ArtBox. And when they do have these additional boxes, they often have the\n * same dimensions as the MediaBox. However, if you find this method does not\n * work for your document, consider setting the boxes directly:\n * * [[PDFPage.setMediaBox]]\n * * [[PDFPage.setCropBox]]\n * * [[PDFPage.setBleedBox]]\n * * [[PDFPage.setTrimBox]]\n * * [[PDFPage.setArtBox]]\n *\n * @param width The new width of the page.\n * @param height The new height of the page.\n */\n setSize(width: number, height: number): void {\n assertIs(width, 'width', ['number']);\n assertIs(height, 'height', ['number']);\n\n const mediaBox = this.getMediaBox();\n this.setMediaBox(mediaBox.x, mediaBox.y, width, height);\n\n const cropBox = this.getCropBox();\n const bleedBox = this.getBleedBox();\n const trimBox = this.getTrimBox();\n const artBox = this.getArtBox();\n\n const hasCropBox = this.node.CropBox()!!;\n const hasBleedBox = this.node.BleedBox()!!;\n const hasTrimBox = this.node.TrimBox()!!;\n const hasArtBox = this.node.ArtBox()!!;\n\n if (hasCropBox && rectanglesAreEqual(cropBox, mediaBox)) {\n this.setCropBox(mediaBox.x, mediaBox.y, width, height);\n }\n if (hasBleedBox && rectanglesAreEqual(bleedBox, mediaBox)) {\n this.setBleedBox(mediaBox.x, mediaBox.y, width, height);\n }\n if (hasTrimBox && rectanglesAreEqual(trimBox, mediaBox)) {\n this.setTrimBox(mediaBox.x, mediaBox.y, width, height);\n }\n if (hasArtBox && rectanglesAreEqual(artBox, mediaBox)) {\n this.setArtBox(mediaBox.x, mediaBox.y, width, height);\n }\n }\n\n /**\n * Resize this page by increasing or decreasing its width. For example:\n * ```js\n * page.setWidth(250)\n * page.setWidth(page.getWidth() + 50)\n * page.setWidth(page.getWidth() - 50)\n * ```\n *\n * This method uses [[PDFPage.setSize]] to set the page's width.\n *\n * @param width The new width of the page.\n */\n setWidth(width: number): void {\n assertIs(width, 'width', ['number']);\n this.setSize(width, this.getSize().height);\n }\n\n /**\n * Resize this page by increasing or decreasing its height. For example:\n * ```js\n * page.setHeight(500)\n * page.setHeight(page.getWidth() + 100)\n * page.setHeight(page.getWidth() - 100)\n * ```\n *\n * This method uses [[PDFPage.setSize]] to set the page's height.\n *\n * @param height The new height of the page.\n */\n setHeight(height: number): void {\n assertIs(height, 'height', ['number']);\n this.setSize(this.getSize().width, height);\n }\n\n /**\n * Set the MediaBox of this page. For example:\n * ```js\n * const mediaBox = page.getMediaBox()\n *\n * page.setMediaBox(0, 0, 250, 500)\n * page.setMediaBox(mediaBox.x, mediaBox.y, 50, 100)\n * page.setMediaBox(15, 5, mediaBox.width - 50, mediaBox.height - 100)\n * ```\n *\n * See [[PDFPage.getMediaBox]] for details about what the MediaBox represents.\n *\n * @param x The x coordinate of the lower left corner of the new MediaBox.\n * @param y The y coordinate of the lower left corner of the new MediaBox.\n * @param width The width of the new MediaBox.\n * @param height The height of the new MediaBox.\n */\n setMediaBox(x: number, y: number, width: number, height: number): void {\n assertIs(x, 'x', ['number']);\n assertIs(y, 'y', ['number']);\n assertIs(width, 'width', ['number']);\n assertIs(height, 'height', ['number']);\n const mediaBox = this.doc.context.obj([x, y, x + width, y + height]);\n this.node.set(PDFName.MediaBox, mediaBox);\n }\n\n /**\n * Set the CropBox of this page. For example:\n * ```js\n * const cropBox = page.getCropBox()\n *\n * page.setCropBox(0, 0, 250, 500)\n * page.setCropBox(cropBox.x, cropBox.y, 50, 100)\n * page.setCropBox(15, 5, cropBox.width - 50, cropBox.height - 100)\n * ```\n *\n * See [[PDFPage.getCropBox]] for details about what the CropBox represents.\n *\n * @param x The x coordinate of the lower left corner of the new CropBox.\n * @param y The y coordinate of the lower left corner of the new CropBox.\n * @param width The width of the new CropBox.\n * @param height The height of the new CropBox.\n */\n setCropBox(x: number, y: number, width: number, height: number): void {\n assertIs(x, 'x', ['number']);\n assertIs(y, 'y', ['number']);\n assertIs(width, 'width', ['number']);\n assertIs(height, 'height', ['number']);\n const cropBox = this.doc.context.obj([x, y, x + width, y + height]);\n this.node.set(PDFName.CropBox, cropBox);\n }\n\n /**\n * Set the BleedBox of this page. For example:\n * ```js\n * const bleedBox = page.getBleedBox()\n *\n * page.setBleedBox(0, 0, 250, 500)\n * page.setBleedBox(bleedBox.x, bleedBox.y, 50, 100)\n * page.setBleedBox(15, 5, bleedBox.width - 50, bleedBox.height - 100)\n * ```\n *\n * See [[PDFPage.getBleedBox]] for details about what the BleedBox represents.\n *\n * @param x The x coordinate of the lower left corner of the new BleedBox.\n * @param y The y coordinate of the lower left corner of the new BleedBox.\n * @param width The width of the new BleedBox.\n * @param height The height of the new BleedBox.\n */\n setBleedBox(x: number, y: number, width: number, height: number): void {\n assertIs(x, 'x', ['number']);\n assertIs(y, 'y', ['number']);\n assertIs(width, 'width', ['number']);\n assertIs(height, 'height', ['number']);\n const bleedBox = this.doc.context.obj([x, y, x + width, y + height]);\n this.node.set(PDFName.BleedBox, bleedBox);\n }\n\n /**\n * Set the TrimBox of this page. For example:\n * ```js\n * const trimBox = page.getTrimBox()\n *\n * page.setTrimBox(0, 0, 250, 500)\n * page.setTrimBox(trimBox.x, trimBox.y, 50, 100)\n * page.setTrimBox(15, 5, trimBox.width - 50, trimBox.height - 100)\n * ```\n *\n * See [[PDFPage.getTrimBox]] for details about what the TrimBox represents.\n *\n * @param x The x coordinate of the lower left corner of the new TrimBox.\n * @param y The y coordinate of the lower left corner of the new TrimBox.\n * @param width The width of the new TrimBox.\n * @param height The height of the new TrimBox.\n */\n setTrimBox(x: number, y: number, width: number, height: number): void {\n assertIs(x, 'x', ['number']);\n assertIs(y, 'y', ['number']);\n assertIs(width, 'width', ['number']);\n assertIs(height, 'height', ['number']);\n const trimBox = this.doc.context.obj([x, y, x + width, y + height]);\n this.node.set(PDFName.TrimBox, trimBox);\n }\n\n /**\n * Set the ArtBox of this page. For example:\n * ```js\n * const artBox = page.getArtBox()\n *\n * page.setArtBox(0, 0, 250, 500)\n * page.setArtBox(artBox.x, artBox.y, 50, 100)\n * page.setArtBox(15, 5, artBox.width - 50, artBox.height - 100)\n * ```\n *\n * See [[PDFPage.getArtBox]] for details about what the ArtBox represents.\n *\n * @param x The x coordinate of the lower left corner of the new ArtBox.\n * @param y The y coordinate of the lower left corner of the new ArtBox.\n * @param width The width of the new ArtBox.\n * @param height The height of the new ArtBox.\n */\n setArtBox(x: number, y: number, width: number, height: number): void {\n assertIs(x, 'x', ['number']);\n assertIs(y, 'y', ['number']);\n assertIs(width, 'width', ['number']);\n assertIs(height, 'height', ['number']);\n const artBox = this.doc.context.obj([x, y, x + width, y + height]);\n this.node.set(PDFName.ArtBox, artBox);\n }\n\n /**\n * Get this page's width and height. For example:\n * ```js\n * const { width, height } = page.getSize()\n * ```\n *\n * This method uses [[PDFPage.getMediaBox]] to obtain the page's\n * width and height.\n *\n * @returns The width and height of the page.\n */\n getSize(): { width: number; height: number } {\n const { width, height } = this.getMediaBox();\n return { width, height };\n }\n\n /**\n * Get this page's width. For example:\n * ```js\n * const width = page.getWidth()\n * ```\n *\n * This method uses [[PDFPage.getSize]] to obtain the page's size.\n *\n * @returns The width of the page.\n */\n getWidth(): number {\n return this.getSize().width;\n }\n\n /**\n * Get this page's height. For example:\n * ```js\n * const height = page.getHeight()\n * ```\n *\n * This method uses [[PDFPage.getSize]] to obtain the page's size.\n *\n * @returns The height of the page.\n */\n getHeight(): number {\n return this.getSize().height;\n }\n\n /**\n * Get the rectangle defining this page's MediaBox. For example:\n * ```js\n * const { x, y, width, height } = page.getMediaBox()\n * ```\n *\n * The MediaBox of a page defines the boundaries of the physical medium on\n * which the page is to be displayed/printed. It may include extended area\n * surrounding the page content for bleed marks, printing marks, etc...\n * It may also include areas close to the edges of the medium that cannot be\n * marked because of physical limitations of the output device. Content\n * falling outside this boundary may safely be discarded without affecting\n * the meaning of the PDF file.\n *\n * @returns An object defining the lower left corner of the MediaBox and its\n * width & height.\n */\n getMediaBox(): { x: number; y: number; width: number; height: number } {\n const mediaBox = this.node.MediaBox();\n return mediaBox.asRectangle();\n }\n\n /**\n * Get the rectangle defining this page's CropBox. For example:\n * ```js\n * const { x, y, width, height } = page.getCropBox()\n * ```\n *\n * The CropBox of a page defines the region to which the contents of the page\n * shall be clipped when displayed or printed. Unlike the other boxes, the\n * CropBox does not necessarily represent the physical page geometry. It\n * merely imposes clipping on the page contents.\n *\n * The CropBox's default value is the page's MediaBox.\n *\n * @returns An object defining the lower left corner of the CropBox and its\n * width & height.\n */\n getCropBox(): { x: number; y: number; width: number; height: number } {\n const cropBox = this.node.CropBox();\n return cropBox?.asRectangle() ?? this.getMediaBox();\n }\n\n /**\n * Get the rectangle defining this page's BleedBox. For example:\n * ```js\n * const { x, y, width, height } = page.getBleedBox()\n * ```\n *\n * The BleedBox of a page defines the region to which the contents of the\n * page shall be clipped when output in a production environment. This may\n * include any extra bleed area needed to accommodate the physical\n * limitations of cutting, folding, and trimming equipment. The actual\n * printed page may include printing marks that fall outside the BleedBox.\n *\n * The BleedBox's default value is the page's CropBox.\n *\n * @returns An object defining the lower left corner of the BleedBox and its\n * width & height.\n */\n getBleedBox(): { x: number; y: number; width: number; height: number } {\n const bleedBox = this.node.BleedBox();\n return bleedBox?.asRectangle() ?? this.getCropBox();\n }\n\n /**\n * Get the rectangle defining this page's TrimBox. For example:\n * ```js\n * const { x, y, width, height } = page.getTrimBox()\n * ```\n *\n * The TrimBox of a page defines the intended dimensions of the finished\n * page after trimming. It may be smaller than the MediaBox to allow for\n * production-related content, such as printing instructions, cut marks, or\n * color bars.\n *\n * The TrimBox's default value is the page's CropBox.\n *\n * @returns An object defining the lower left corner of the TrimBox and its\n * width & height.\n */\n getTrimBox(): { x: number; y: number; width: number; height: number } {\n const trimBox = this.node.TrimBox();\n return trimBox?.asRectangle() ?? this.getCropBox();\n }\n\n /**\n * Get the rectangle defining this page's ArtBox. For example:\n * ```js\n * const { x, y, width, height } = page.getArtBox()\n * ```\n *\n * The ArtBox of a page defines the extent of the page's meaningful content\n * (including potential white space).\n *\n * The ArtBox's default value is the page's CropBox.\n *\n * @returns An object defining the lower left corner of the ArtBox and its\n * width & height.\n */\n getArtBox(): { x: number; y: number; width: number; height: number } {\n const artBox = this.node.ArtBox();\n return artBox?.asRectangle() ?? this.getCropBox();\n }\n\n /**\n * Translate this page's content to a new location on the page. This operation\n * is often useful after resizing the page with [[setSize]]. For example:\n * ```js\n * // Add 50 units of whitespace to the top and right of the page\n * page.setSize(page.getWidth() + 50, page.getHeight() + 50)\n *\n * // Move the page's content from the lower-left corner of the page\n * // to the top-right corner.\n * page.translateContent(50, 50)\n *\n * // Now there are 50 units of whitespace to the left and bottom of the page\n * ```\n * See also: [[resetPosition]]\n * @param x The new position on the x-axis for this page's content.\n * @param y The new position on the y-axis for this page's content.\n */\n translateContent(x: number, y: number): void {\n assertIs(x, 'x', ['number']);\n assertIs(y, 'y', ['number']);\n\n this.node.normalize();\n this.getContentStream();\n\n const start = this.createContentStream(\n pushGraphicsState(),\n translate(x, y),\n );\n const startRef = this.doc.context.register(start);\n\n const end = this.createContentStream(popGraphicsState());\n const endRef = this.doc.context.register(end);\n\n this.node.wrapContentStreams(startRef, endRef);\n }\n\n /**\n * Scale the size, content, and annotations of a page.\n *\n * For example:\n * ```js\n * page.scale(0.5, 0.5);\n * ```\n *\n * @param x The factor by which the width for the page should be scaled\n * (e.g. `0.5` is 50%).\n * @param y The factor by which the height for the page should be scaled\n * (e.g. `2.0` is 200%).\n */\n scale(x: number, y: number): void {\n assertIs(x, 'x', ['number']);\n assertIs(y, 'y', ['number']);\n this.setSize(this.getWidth() * x, this.getHeight() * y);\n this.scaleContent(x, y);\n this.scaleAnnotations(x, y);\n }\n\n /**\n * Scale the content of a page. This is useful after resizing an existing\n * page. This scales only the content, not the annotations.\n *\n * For example:\n * ```js\n * // Bisect the size of the page\n * page.setSize(page.getWidth() / 2, page.getHeight() / 2);\n *\n * // Scale the content of the page down by 50% in x and y\n * page.scaleContent(0.5, 0.5);\n * ```\n * See also: [[scaleAnnotations]]\n * @param x The factor by which the x-axis for the content should be scaled\n * (e.g. `0.5` is 50%).\n * @param y The factor by which the y-axis for the content should be scaled\n * (e.g. `2.0` is 200%).\n */\n scaleContent(x: number, y: number): void {\n assertIs(x, 'x', ['number']);\n assertIs(y, 'y', ['number']);\n\n this.node.normalize();\n this.getContentStream();\n\n const start = this.createContentStream(pushGraphicsState(), scale(x, y));\n const startRef = this.doc.context.register(start);\n\n const end = this.createContentStream(popGraphicsState());\n const endRef = this.doc.context.register(end);\n\n this.node.wrapContentStreams(startRef, endRef);\n }\n\n /**\n * Scale the annotations of a page. This is useful if you want to scale a\n * page with comments or other annotations.\n * ```js\n * // Scale the content of the page down by 50% in x and y\n * page.scaleContent(0.5, 0.5);\n *\n * // Scale the content of the page down by 50% in x and y\n * page.scaleAnnotations(0.5, 0.5);\n * ```\n * See also: [[scaleContent]]\n * @param x The factor by which the x-axis for the annotations should be\n * scaled (e.g. `0.5` is 50%).\n * @param y The factor by which the y-axis for the annotations should be\n * scaled (e.g. `2.0` is 200%).\n */\n scaleAnnotations(x: number, y: number) {\n assertIs(x, 'x', ['number']);\n assertIs(y, 'y', ['number']);\n\n const annots = this.node.Annots();\n if (!annots) return;\n\n for (let idx = 0; idx < annots.size(); idx++) {\n const annot = annots.lookup(idx);\n if (annot instanceof PDFDict) this.scaleAnnot(annot, x, y);\n }\n }\n\n /**\n * Reset the x and y coordinates of this page to `(0, 0)`. This operation is\n * often useful after calling [[translateContent]]. For example:\n * ```js\n * // Shift the page's contents up and to the right by 50 units\n * page.translateContent(50, 50)\n *\n * // This text will shifted - it will be drawn at (50, 50)\n * page.drawText('I am shifted')\n *\n * // Move back to (0, 0)\n * page.resetPosition()\n *\n * // This text will not be shifted - it will be drawn at (0, 0)\n * page.drawText('I am not shifted')\n * ```\n */\n resetPosition(): void {\n this.getContentStream(false);\n this.x = 0;\n this.y = 0;\n }\n\n /**\n * Choose a default font for this page. The default font will be used whenever\n * text is drawn on this page and no font is specified. For example:\n * ```js\n * import { StandardFonts } from 'pdf-lib'\n *\n * const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman)\n * const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica)\n * const courierFont = await pdfDoc.embedFont(StandardFonts.Courier)\n *\n * const page = pdfDoc.addPage()\n *\n * page.setFont(helveticaFont)\n * page.drawText('I will be drawn in Helvetica')\n *\n * page.setFont(timesRomanFont)\n * page.drawText('I will be drawn in Courier', { font: courierFont })\n * ```\n * @param font The default font to be used when drawing text on this page.\n */\n setFont(font: PDFFont): void {\n // TODO: Reuse image Font name if we've already added this image to Resources.Fonts\n assertIs(font, 'font', [[PDFFont, 'PDFFont']]);\n this.font = font;\n this.fontKey = this.node.newFontDictionary(this.font.name, this.font.ref);\n }\n\n /**\n * Choose a default font size for this page. The default font size will be\n * used whenever text is drawn on this page and no font size is specified.\n * For example:\n * ```js\n * page.setFontSize(12)\n * page.drawText('I will be drawn in size 12')\n *\n * page.setFontSize(36)\n * page.drawText('I will be drawn in size 24', { fontSize: 24 })\n * ```\n * @param fontSize The default font size to be used when drawing text on this\n * page.\n */\n setFontSize(fontSize: number): void {\n assertIs(fontSize, 'fontSize', ['number']);\n this.fontSize = fontSize;\n }\n\n /**\n * Choose a default font color for this page. The default font color will be\n * used whenever text is drawn on this page and no font color is specified.\n * For example:\n * ```js\n * import { rgb, cmyk, grayscale } from 'pdf-lib'\n *\n * page.setFontColor(rgb(0.97, 0.02, 0.97))\n * page.drawText('I will be drawn in pink')\n *\n * page.setFontColor(cmyk(0.4, 0.7, 0.39, 0.15))\n * page.drawText('I will be drawn in gray', { color: grayscale(0.5) })\n * ```\n * @param fontColor The default font color to be used when drawing text on\n * this page.\n */\n setFontColor(fontColor: Color): void {\n assertIs(fontColor, 'fontColor', [[Object, 'Color']]);\n this.fontColor = fontColor;\n }\n\n /**\n * Choose a default line height for this page. The default line height will be\n * used whenever text is drawn on this page and no line height is specified.\n * For example:\n * ```js\n * page.setLineHeight(12);\n * page.drawText('These lines will be vertically \\n separated by 12 units')\n *\n * page.setLineHeight(36);\n * page.drawText('These lines will be vertically \\n separated by 24 units', {\n * lineHeight: 24\n * })\n * ```\n * @param lineHeight The default line height to be used when drawing text on\n * this page.\n */\n setLineHeight(lineHeight: number): void {\n assertIs(lineHeight, 'lineHeight', ['number']);\n this.lineHeight = lineHeight;\n }\n\n /**\n * Get the default position of this page. For example:\n * ```js\n * const { x, y } = page.getPosition()\n * ```\n * @returns The default position of the page.\n */\n getPosition(): { x: number; y: number } {\n return { x: this.x, y: this.y };\n }\n\n /**\n * Get the default x coordinate of this page. For example:\n * ```js\n * const x = page.getX()\n * ```\n * @returns The default x coordinate of the page.\n */\n getX(): number {\n return this.x;\n }\n\n /**\n * Get the default y coordinate of this page. For example:\n * ```js\n * const y = page.getY()\n * ```\n * @returns The default y coordinate of the page.\n */\n getY(): number {\n return this.y;\n }\n\n /**\n * Change the default position of this page. For example:\n * ```js\n * page.moveTo(0, 0)\n * page.drawText('I will be drawn at the origin')\n *\n * page.moveTo(0, 25)\n * page.drawText('I will be drawn 25 units up')\n *\n * page.moveTo(25, 25)\n * page.drawText('I will be drawn 25 units up and 25 units to the right')\n * ```\n * @param x The new default position on the x-axis for this page.\n * @param y The new default position on the y-axis for this page.\n */\n moveTo(x: number, y: number): void {\n assertIs(x, 'x', ['number']);\n assertIs(y, 'y', ['number']);\n this.x = x;\n this.y = y;\n }\n\n /**\n * Change the default position of this page to be further down the y-axis.\n * For example:\n * ```js\n * page.moveTo(50, 50)\n * page.drawText('I will be drawn at (50, 50)')\n *\n * page.moveDown(10)\n * page.drawText('I will be drawn at (50, 40)')\n * ```\n * @param yDecrease The amount by which the page's default position along the\n * y-axis should be decreased.\n */\n moveDown(yDecrease: number): void {\n assertIs(yDecrease, 'yDecrease', ['number']);\n this.y -= yDecrease;\n }\n\n /**\n * Change the default position of this page to be further up the y-axis.\n * For example:\n * ```js\n * page.moveTo(50, 50)\n * page.drawText('I will be drawn at (50, 50)')\n *\n * page.moveUp(10)\n * page.drawText('I will be drawn at (50, 60)')\n * ```\n * @param yIncrease The amount by which the page's default position along the\n * y-axis should be increased.\n */\n moveUp(yIncrease: number): void {\n assertIs(yIncrease, 'yIncrease', ['number']);\n this.y += yIncrease;\n }\n\n /**\n * Change the default position of this page to be further left on the x-axis.\n * For example:\n * ```js\n * page.moveTo(50, 50)\n * page.drawText('I will be drawn at (50, 50)')\n *\n * page.moveLeft(10)\n * page.drawText('I will be drawn at (40, 50)')\n * ```\n * @param xDecrease The amount by which the page's default position along the\n * x-axis should be decreased.\n */\n moveLeft(xDecrease: number): void {\n assertIs(xDecrease, 'xDecrease', ['number']);\n this.x -= xDecrease;\n }\n\n /**\n * Change the default position of this page to be further right on the y-axis.\n * For example:\n * ```js\n * page.moveTo(50, 50)\n * page.drawText('I will be drawn at (50, 50)')\n *\n * page.moveRight(10)\n * page.drawText('I will be drawn at (60, 50)')\n * ```\n * @param xIncrease The amount by which the page's default position along the\n * x-axis should be increased.\n */\n moveRight(xIncrease: number): void {\n assertIs(xIncrease, 'xIncrease', ['number']);\n this.x += xIncrease;\n }\n\n /**\n * Push one or more operators to the end of this page's current content\n * stream. For example:\n * ```js\n * import {\n * pushGraphicsState,\n * moveTo,\n * lineTo,\n * closePath,\n * setFillingColor,\n * rgb,\n * fill,\n * popGraphicsState,\n * } from 'pdf-lib'\n *\n * // Draw a green triangle in the lower-left corner of the page\n * page.pushOperators(\n * pushGraphicsState(),\n * moveTo(0, 0),\n * lineTo(100, 0),\n * lineTo(50, 100),\n * closePath(),\n * setFillingColor(rgb(0.0, 1.0, 0.0)),\n * fill(),\n * popGraphicsState(),\n * )\n * ```\n * @param operator The operators to be pushed.\n */\n pushOperators(...operator: PDFOperator[]): void {\n assertEachIs(operator, 'operator', [[PDFOperator, 'PDFOperator']]);\n const contentStream = this.getContentStream();\n contentStream.push(...operator);\n }\n\n /**\n * Draw one or more lines of text on this page. For example:\n * ```js\n * import { StandardFonts, rgb } from 'pdf-lib'\n *\n * const helveticaFont = await pdfDoc.embedFont(StandardFonts.Helvetica)\n * const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman)\n *\n * const page = pdfDoc.addPage()\n *\n * page.setFont(helveticaFont)\n *\n * page.moveTo(5, 200)\n * page.drawText('The Life of an Egg', { size: 36 })\n *\n * page.moveDown(36)\n * page.drawText('An Epic Tale of Woe', { size: 30 })\n *\n * page.drawText(\n * `Humpty Dumpty sat on a wall \\n` +\n * `Humpty Dumpty had a great fall; \\n` +\n * `All the king's horses and all the king's men \\n` +\n * `Couldn't put Humpty together again. \\n`,\n * {\n * x: 25,\n * y: 100,\n * font: timesRomanFont,\n * size: 24,\n * color: rgb(1, 0, 0),\n * lineHeight: 24,\n * opacity: 0.75,\n * },\n * )\n * ```\n * @param text The text to be drawn.\n * @param options The options to be used when drawing the text.\n */\n drawText(text: string, options: PDFPageDrawTextOptions = {}): void {\n assertIs(text, 'text', ['string']);\n assertOrUndefined(options.color, 'options.color', [[Object, 'Color']]);\n assertRangeOrUndefined(options.opacity, 'opacity.opacity', 0, 1);\n assertOrUndefined(options.font, 'options.font', [[PDFFont, 'PDFFont']]);\n assertOrUndefined(options.size, 'options.size', ['number']);\n assertOrUndefined(options.rotate, 'options.rotate', [[Object, 'Rotation']]);\n assertOrUndefined(options.xSkew, 'options.xSkew', [[Object, 'Rotation']]);\n assertOrUndefined(options.ySkew, 'options.ySkew', [[Object, 'Rotation']]);\n assertOrUndefined(options.x, 'options.x', ['number']);\n assertOrUndefined(options.y, 'options.y', ['number']);\n assertOrUndefined(options.lineHeight, 'options.lineHeight', ['number']);\n assertOrUndefined(options.maxWidth, 'options.maxWidth', ['number']);\n assertOrUndefined(options.wordBreaks, 'options.wordBreaks', [Array]);\n assertIsOneOfOrUndefined(options.blendMode, 'options.blendMode', BlendMode);\n\n const { oldFont, newFont, newFontKey } = this.setOrEmbedFont(options.font);\n const fontSize = options.size || this.fontSize;\n\n const wordBreaks = options.wordBreaks || this.doc.defaultWordBreaks;\n const textWidth = (t: string) => newFont.widthOfTextAtSize(t, fontSize);\n const lines =\n options.maxWidth === undefined\n ? lineSplit(cleanText(text))\n : breakTextIntoLines(text, wordBreaks, options.maxWidth, textWidth);\n\n const encodedLines = new Array(lines.length) as PDFHexString[];\n for (let idx = 0, len = lines.length; idx < len; idx++) {\n encodedLines[idx] = newFont.encodeText(lines[idx]);\n }\n\n const graphicsStateKey = this.maybeEmbedGraphicsState({\n opacity: options.opacity,\n blendMode: options.blendMode,\n });\n\n const contentStream = this.getContentStream();\n contentStream.push(\n ...drawLinesOfText(encodedLines, {\n color: options.color ?? this.fontColor,\n font: newFontKey,\n size: fontSize,\n rotate: options.rotate ?? degrees(0),\n xSkew: options.xSkew ?? degrees(0),\n ySkew: options.ySkew ?? degrees(0),\n x: options.x ?? this.x,\n y: options.y ?? this.y,\n lineHeight: options.lineHeight ?? this.lineHeight,\n graphicsState: graphicsStateKey,\n }),\n );\n\n if (options.font) {\n if (oldFont) this.setFont(oldFont);\n else this.resetFont();\n }\n }\n\n /**\n * Draw an image on this page. For example:\n * ```js\n * import { degrees } from 'pdf-lib'\n *\n * const jpgUrl = 'https://pdf-lib.js.org/assets/cat_riding_unicorn.jpg'\n * const jpgImageBytes = await fetch(jpgUrl).then((res) => res.arrayBuffer())\n *\n * const jpgImage = await pdfDoc.embedJpg(jpgImageBytes)\n * const jpgDims = jpgImage.scale(0.5)\n *\n * const page = pdfDoc.addPage()\n *\n * page.drawImage(jpgImage, {\n * x: 25,\n * y: 25,\n * width: jpgDims.width,\n * height: jpgDims.height,\n * rotate: degrees(30),\n * opacity: 0.75,\n * })\n * ```\n * @param image The image to be drawn.\n * @param options The options to be used when drawing the image.\n */\n drawImage(image: PDFImage, options: PDFPageDrawImageOptions = {}): void {\n // TODO: Reuse image XObject name if we've already added this image to Resources.XObjects\n assertIs(image, 'image', [[PDFImage, 'PDFImage']]);\n assertOrUndefined(options.x, 'options.x', ['number']);\n assertOrUndefined(options.y, 'options.y', ['number']);\n assertOrUndefined(options.width, 'options.width', ['number']);\n assertOrUndefined(options.height, 'options.height', ['number']);\n assertOrUndefined(options.rotate, 'options.rotate', [[Object, 'Rotation']]);\n assertOrUndefined(options.xSkew, 'options.xSkew', [[Object, 'Rotation']]);\n assertOrUndefined(options.ySkew, 'options.ySkew', [[Object, 'Rotation']]);\n assertRangeOrUndefined(options.opacity, 'opacity.opacity', 0, 1);\n assertIsOneOfOrUndefined(options.blendMode, 'options.blendMode', BlendMode);\n\n const xObjectKey = this.node.newXObject('Image', image.ref);\n\n const graphicsStateKey = this.maybeEmbedGraphicsState({\n opacity: options.opacity,\n blendMode: options.blendMode,\n });\n\n const contentStream = this.getContentStream();\n contentStream.push(\n ...drawImage(xObjectKey, {\n x: options.x ?? this.x,\n y: options.y ?? this.y,\n width: options.width ?? image.size().width,\n height: options.height ?? image.size().height,\n rotate: options.rotate ?? degrees(0),\n xSkew: options.xSkew ?? degrees(0),\n ySkew: options.ySkew ?? degrees(0),\n graphicsState: graphicsStateKey,\n }),\n );\n }\n\n /**\n * Draw an embedded PDF page on this page. For example:\n * ```js\n * import { degrees } from 'pdf-lib'\n *\n * const pdfDoc = await PDFDocument.create()\n * const page = pdfDoc.addPage()\n *\n * const sourcePdfUrl = 'https://pdf-lib.js.org/assets/with_large_page_count.pdf'\n * const sourcePdf = await fetch(sourcePdfUrl).then((res) => res.arrayBuffer())\n *\n * // Embed page 74 from the PDF\n * const [embeddedPage] = await pdfDoc.embedPdf(sourcePdf, 73)\n *\n * page.drawPage(embeddedPage, {\n * x: 250,\n * y: 200,\n * xScale: 0.5,\n * yScale: 0.5,\n * rotate: degrees(30),\n * opacity: 0.75,\n * })\n * ```\n *\n * The `options` argument accepts both `width`/`height` and `xScale`/`yScale`\n * as options. Since each of these options defines the size of the drawn page,\n * if both options are given, `width` and `height` take precedence and the\n * corresponding scale variants are ignored.\n *\n * @param embeddedPage The embedded page to be drawn.\n * @param options The options to be used when drawing the embedded page.\n */\n drawPage(\n embeddedPage: PDFEmbeddedPage,\n options: PDFPageDrawPageOptions = {},\n ): void {\n // TODO: Reuse embeddedPage XObject name if we've already added this embeddedPage to Resources.XObjects\n assertIs(embeddedPage, 'embeddedPage', [\n [PDFEmbeddedPage, 'PDFEmbeddedPage'],\n ]);\n assertOrUndefined(options.x, 'options.x', ['number']);\n assertOrUndefined(options.y, 'options.y', ['number']);\n assertOrUndefined(options.xScale, 'options.xScale', ['number']);\n assertOrUndefined(options.yScale, 'options.yScale', ['number']);\n assertOrUndefined(options.width, 'options.width', ['number']);\n assertOrUndefined(options.height, 'options.height', ['number']);\n assertOrUndefined(options.rotate, 'options.rotate', [[Object, 'Rotation']]);\n assertOrUndefined(options.xSkew, 'options.xSkew', [[Object, 'Rotation']]);\n assertOrUndefined(options.ySkew, 'options.ySkew', [[Object, 'Rotation']]);\n assertRangeOrUndefined(options.opacity, 'opacity.opacity', 0, 1);\n assertIsOneOfOrUndefined(options.blendMode, 'options.blendMode', BlendMode);\n\n const xObjectKey = this.node.newXObject(\n 'EmbeddedPdfPage',\n embeddedPage.ref,\n );\n\n const graphicsStateKey = this.maybeEmbedGraphicsState({\n opacity: options.opacity,\n blendMode: options.blendMode,\n });\n\n // prettier-ignore\n const xScale = (\n options.width !== undefined ? options.width / embeddedPage.width\n : options.xScale !== undefined ? options.xScale\n : 1\n );\n\n // prettier-ignore\n const yScale = (\n options.height !== undefined ? options.height / embeddedPage.height\n : options.yScale !== undefined ? options.yScale\n : 1\n );\n\n const contentStream = this.getContentStream();\n contentStream.push(\n ...drawPage(xObjectKey, {\n x: options.x ?? this.x,\n y: options.y ?? this.y,\n xScale,\n yScale,\n rotate: options.rotate ?? degrees(0),\n xSkew: options.xSkew ?? degrees(0),\n ySkew: options.ySkew ?? degrees(0),\n graphicsState: graphicsStateKey,\n }),\n );\n }\n\n /**\n * Draw an SVG path on this page. For example:\n * ```js\n * import { rgb } from 'pdf-lib'\n *\n * const svgPath = 'M 0,20 L 100,160 Q 130,200 150,120 C 190,-40 200,200 300,150 L 400,90'\n *\n * // Draw path as black line\n * page.drawSvgPath(svgPath, { x: 25, y: 75 })\n *\n * // Change border style and opacity\n * page.drawSvgPath(svgPath, {\n * x: 25,\n * y: 275,\n * borderColor: rgb(0.5, 0.5, 0.5),\n * borderWidth: 2,\n * borderOpacity: 0.75,\n * })\n *\n * // Set fill color and opacity\n * page.drawSvgPath(svgPath, {\n * x: 25,\n * y: 475,\n * color: rgb(1.0, 0, 0),\n * opacity: 0.75,\n * })\n *\n * // Draw 50% of original size\n * page.drawSvgPath(svgPath, {\n * x: 25,\n * y: 675,\n * scale: 0.5,\n * })\n * ```\n * @param path The SVG path to be drawn.\n * @param options The options to be used when drawing the SVG path.\n */\n drawSvgPath(path: string, options: PDFPageDrawSVGOptions = {}): void {\n assertIs(path, 'path', ['string']);\n assertOrUndefined(options.x, 'options.x', ['number']);\n assertOrUndefined(options.y, 'options.y', ['number']);\n assertOrUndefined(options.scale, 'options.scale', ['number']);\n assertOrUndefined(options.rotate, 'options.rotate', [[Object, 'Rotation']]);\n assertOrUndefined(options.borderWidth, 'options.borderWidth', ['number']);\n assertOrUndefined(options.color, 'options.color', [[Object, 'Color']]);\n assertRangeOrUndefined(options.opacity, 'opacity.opacity', 0, 1);\n assertOrUndefined(options.borderColor, 'options.borderColor', [\n [Object, 'Color'],\n ]);\n assertOrUndefined(options.borderDashArray, 'options.borderDashArray', [\n Array,\n ]);\n assertOrUndefined(options.borderDashPhase, 'options.borderDashPhase', [\n 'number',\n ]);\n assertIsOneOfOrUndefined(\n options.borderLineCap,\n 'options.borderLineCap',\n LineCapStyle,\n );\n assertRangeOrUndefined(\n options.borderOpacity,\n 'options.borderOpacity',\n 0,\n 1,\n );\n assertIsOneOfOrUndefined(options.blendMode, 'options.blendMode', BlendMode);\n\n const graphicsStateKey = this.maybeEmbedGraphicsState({\n opacity: options.opacity,\n borderOpacity: options.borderOpacity,\n blendMode: options.blendMode,\n });\n\n if (!('color' in options) && !('borderColor' in options)) {\n options.borderColor = rgb(0, 0, 0);\n }\n\n const contentStream = this.getContentStream();\n contentStream.push(\n ...drawSvgPath(path, {\n x: options.x ?? this.x,\n y: options.y ?? this.y,\n scale: options.scale,\n rotate: options.rotate ?? degrees(0),\n color: options.color ?? undefined,\n borderColor: options.borderColor ?? undefined,\n borderWidth: options.borderWidth ?? 0,\n borderDashArray: options.borderDashArray ?? undefined,\n borderDashPhase: options.borderDashPhase ?? undefined,\n borderLineCap: options.borderLineCap ?? undefined,\n graphicsState: graphicsStateKey,\n }),\n );\n }\n\n /**\n * Draw a line on this page. For example:\n * ```js\n * import { rgb } from 'pdf-lib'\n *\n * page.drawLine({\n * start: { x: 25, y: 75 },\n * end: { x: 125, y: 175 },\n * thickness: 2,\n * color: rgb(0.75, 0.2, 0.2),\n * opacity: 0.75,\n * })\n * ```\n * @param options The options to be used when drawing the line.\n */\n drawLine(options: PDFPageDrawLineOptions): void {\n assertIs(options.start, 'options.start', [\n [Object, '{ x: number, y: number }'],\n ]);\n assertIs(options.end, 'options.end', [\n [Object, '{ x: number, y: number }'],\n ]);\n assertIs(options.start.x, 'options.start.x', ['number']);\n assertIs(options.start.y, 'options.start.y', ['number']);\n assertIs(options.end.x, 'options.end.x', ['number']);\n assertIs(options.end.y, 'options.end.y', ['number']);\n assertOrUndefined(options.thickness, 'options.thickness', ['number']);\n assertOrUndefined(options.color, 'options.color', [[Object, 'Color']]);\n assertOrUndefined(options.dashArray, 'options.dashArray', [Array]);\n assertOrUndefined(options.dashPhase, 'options.dashPhase', ['number']);\n assertIsOneOfOrUndefined(options.lineCap, 'options.lineCap', LineCapStyle);\n assertRangeOrUndefined(options.opacity, 'opacity.opacity', 0, 1);\n assertIsOneOfOrUndefined(options.blendMode, 'options.blendMode', BlendMode);\n\n const graphicsStateKey = this.maybeEmbedGraphicsState({\n borderOpacity: options.opacity,\n blendMode: options.blendMode,\n });\n\n if (!('color' in options)) {\n options.color = rgb(0, 0, 0);\n }\n\n const contentStream = this.getContentStream();\n contentStream.push(\n ...drawLine({\n start: options.start,\n end: options.end,\n thickness: options.thickness ?? 1,\n color: options.color ?? undefined,\n dashArray: options.dashArray ?? undefined,\n dashPhase: options.dashPhase ?? undefined,\n lineCap: options.lineCap ?? undefined,\n graphicsState: graphicsStateKey,\n }),\n );\n }\n\n /**\n * Draw a rectangle on this page. For example:\n * ```js\n * import { degrees, grayscale, rgb } from 'pdf-lib'\n *\n * page.drawRectangle({\n * x: 25,\n * y: 75,\n * width: 250,\n * height: 75,\n * rotate: degrees(-15),\n * borderWidth: 5,\n * borderColor: grayscale(0.5),\n * color: rgb(0.75, 0.2, 0.2),\n * opacity: 0.5,\n * borderOpacity: 0.75,\n * })\n * ```\n * @param options The options to be used when drawing the rectangle.\n */\n drawRectangle(options: PDFPageDrawRectangleOptions = {}): void {\n assertOrUndefined(options.x, 'options.x', ['number']);\n assertOrUndefined(options.y, 'options.y', ['number']);\n assertOrUndefined(options.width, 'options.width', ['number']);\n assertOrUndefined(options.height, 'options.height', ['number']);\n assertOrUndefined(options.rotate, 'options.rotate', [[Object, 'Rotation']]);\n assertOrUndefined(options.xSkew, 'options.xSkew', [[Object, 'Rotation']]);\n assertOrUndefined(options.ySkew, 'options.ySkew', [[Object, 'Rotation']]);\n assertOrUndefined(options.borderWidth, 'options.borderWidth', ['number']);\n assertOrUndefined(options.color, 'options.color', [[Object, 'Color']]);\n assertRangeOrUndefined(options.opacity, 'opacity.opacity', 0, 1);\n assertOrUndefined(options.borderColor, 'options.borderColor', [\n [Object, 'Color'],\n ]);\n assertOrUndefined(options.borderDashArray, 'options.borderDashArray', [\n Array,\n ]);\n assertOrUndefined(options.borderDashPhase, 'options.borderDashPhase', [\n 'number',\n ]);\n assertIsOneOfOrUndefined(\n options.borderLineCap,\n 'options.borderLineCap',\n LineCapStyle,\n );\n assertRangeOrUndefined(\n options.borderOpacity,\n 'options.borderOpacity',\n 0,\n 1,\n );\n assertIsOneOfOrUndefined(options.blendMode, 'options.blendMode', BlendMode);\n\n const graphicsStateKey = this.maybeEmbedGraphicsState({\n opacity: options.opacity,\n borderOpacity: options.borderOpacity,\n blendMode: options.blendMode,\n });\n\n if (!('color' in options) && !('borderColor' in options)) {\n options.color = rgb(0, 0, 0);\n }\n\n const contentStream = this.getContentStream();\n contentStream.push(\n ...drawRectangle({\n x: options.x ?? this.x,\n y: options.y ?? this.y,\n width: options.width ?? 150,\n height: options.height ?? 100,\n rotate: options.rotate ?? degrees(0),\n xSkew: options.xSkew ?? degrees(0),\n ySkew: options.ySkew ?? degrees(0),\n borderWidth: options.borderWidth ?? 0,\n color: options.color ?? undefined,\n borderColor: options.borderColor ?? undefined,\n borderDashArray: options.borderDashArray ?? undefined,\n borderDashPhase: options.borderDashPhase ?? undefined,\n graphicsState: graphicsStateKey,\n borderLineCap: options.borderLineCap ?? undefined,\n }),\n );\n }\n\n /**\n * Draw a square on this page. For example:\n * ```js\n * import { degrees, grayscale, rgb } from 'pdf-lib'\n *\n * page.drawSquare({\n * x: 25,\n * y: 75,\n * size: 100,\n * rotate: degrees(-15),\n * borderWidth: 5,\n * borderColor: grayscale(0.5),\n * color: rgb(0.75, 0.2, 0.2),\n * opacity: 0.5,\n * borderOpacity: 0.75,\n * })\n * ```\n * @param options The options to be used when drawing the square.\n */\n drawSquare(options: PDFPageDrawSquareOptions = {}): void {\n const { size } = options;\n assertOrUndefined(size, 'size', ['number']);\n this.drawRectangle({ ...options, width: size, height: size });\n }\n\n /**\n * Draw an ellipse on this page. For example:\n * ```js\n * import { grayscale, rgb } from 'pdf-lib'\n *\n * page.drawEllipse({\n * x: 200,\n * y: 75,\n * xScale: 100,\n * yScale: 50,\n * borderWidth: 5,\n * borderColor: grayscale(0.5),\n * color: rgb(0.75, 0.2, 0.2),\n * opacity: 0.5,\n * borderOpacity: 0.75,\n * })\n * ```\n * @param options The options to be used when drawing the ellipse.\n */\n drawEllipse(options: PDFPageDrawEllipseOptions = {}): void {\n assertOrUndefined(options.x, 'options.x', ['number']);\n assertOrUndefined(options.y, 'options.y', ['number']);\n assertOrUndefined(options.xScale, 'options.xScale', ['number']);\n assertOrUndefined(options.yScale, 'options.yScale', ['number']);\n assertOrUndefined(options.rotate, 'options.rotate', [[Object, 'Rotation']]);\n assertOrUndefined(options.color, 'options.color', [[Object, 'Color']]);\n assertRangeOrUndefined(options.opacity, 'opacity.opacity', 0, 1);\n assertOrUndefined(options.borderColor, 'options.borderColor', [\n [Object, 'Color'],\n ]);\n assertRangeOrUndefined(\n options.borderOpacity,\n 'options.borderOpacity',\n 0,\n 1,\n );\n assertOrUndefined(options.borderWidth, 'options.borderWidth', ['number']);\n assertOrUndefined(options.borderDashArray, 'options.borderDashArray', [\n Array,\n ]);\n assertOrUndefined(options.borderDashPhase, 'options.borderDashPhase', [\n 'number',\n ]);\n assertIsOneOfOrUndefined(\n options.borderLineCap,\n 'options.borderLineCap',\n LineCapStyle,\n );\n assertIsOneOfOrUndefined(options.blendMode, 'options.blendMode', BlendMode);\n const graphicsStateKey = this.maybeEmbedGraphicsState({\n opacity: options.opacity,\n borderOpacity: options.borderOpacity,\n blendMode: options.blendMode,\n });\n\n if (!('color' in options) && !('borderColor' in options)) {\n options.color = rgb(0, 0, 0);\n }\n\n const contentStream = this.getContentStream();\n contentStream.push(\n ...drawEllipse({\n x: options.x ?? this.x,\n y: options.y ?? this.y,\n xScale: options.xScale ?? 100,\n yScale: options.yScale ?? 100,\n rotate: options.rotate ?? undefined,\n color: options.color ?? undefined,\n borderColor: options.borderColor ?? undefined,\n borderWidth: options.borderWidth ?? 0,\n borderDashArray: options.borderDashArray ?? undefined,\n borderDashPhase: options.borderDashPhase ?? undefined,\n borderLineCap: options.borderLineCap ?? undefined,\n graphicsState: graphicsStateKey,\n }),\n );\n }\n\n /**\n * Draw a circle on this page. For example:\n * ```js\n * import { grayscale, rgb } from 'pdf-lib'\n *\n * page.drawCircle({\n * x: 200,\n * y: 150,\n * size: 100,\n * borderWidth: 5,\n * borderColor: grayscale(0.5),\n * color: rgb(0.75, 0.2, 0.2),\n * opacity: 0.5,\n * borderOpacity: 0.75,\n * })\n * ```\n * @param options The options to be used when drawing the ellipse.\n */\n drawCircle(options: PDFPageDrawCircleOptions = {}): void {\n const { size = 100 } = options;\n assertOrUndefined(size, 'size', ['number']);\n this.drawEllipse({ ...options, xScale: size, yScale: size });\n }\n\n private setOrEmbedFont(font?: PDFFont) {\n const oldFont = this.font;\n const oldFontKey = this.fontKey;\n\n if (font) this.setFont(font);\n else this.getFont();\n\n const newFont = this.font!;\n const newFontKey = this.fontKey!;\n\n return { oldFont, oldFontKey, newFont, newFontKey };\n }\n\n private getFont(): [PDFFont, PDFName] {\n if (!this.font || !this.fontKey) {\n const font = this.doc.embedStandardFont(StandardFonts.Helvetica);\n this.setFont(font);\n }\n return [this.font!, this.fontKey!];\n }\n\n private resetFont(): void {\n this.font = undefined;\n this.fontKey = undefined;\n }\n\n private getContentStream(useExisting = true): PDFContentStream {\n if (useExisting && this.contentStream) return this.contentStream;\n this.contentStream = this.createContentStream();\n this.contentStreamRef = this.doc.context.register(this.contentStream);\n this.node.addContentStream(this.contentStreamRef);\n return this.contentStream;\n }\n\n private createContentStream(...operators: PDFOperator[]): PDFContentStream {\n const dict = this.doc.context.obj({});\n const contentStream = PDFContentStream.of(dict, operators);\n return contentStream;\n }\n\n private maybeEmbedGraphicsState(options: {\n opacity?: number;\n borderOpacity?: number;\n blendMode?: BlendMode;\n }): PDFName | undefined {\n const { opacity, borderOpacity, blendMode } = options;\n\n if (\n opacity === undefined &&\n borderOpacity === undefined &&\n blendMode === undefined\n ) {\n return undefined;\n }\n\n const graphicsState = this.doc.context.obj({\n Type: 'ExtGState',\n ca: opacity,\n CA: borderOpacity,\n BM: blendMode,\n });\n\n const key = this.node.newExtGState('GS', graphicsState);\n\n return key;\n }\n\n private scaleAnnot(annot: PDFDict, x: number, y: number) {\n const selectors = ['RD', 'CL', 'Vertices', 'QuadPoints', 'L', 'Rect'];\n for (let idx = 0, len = selectors.length; idx < len; idx++) {\n const list = annot.lookup(PDFName.of(selectors[idx]));\n if (list instanceof PDFArray) list.scalePDFNumbers(x, y);\n }\n\n const inkLists = annot.lookup(PDFName.of('InkList'));\n if (inkLists instanceof PDFArray) {\n for (let idx = 0, len = inkLists.size(); idx < len; idx++) {\n const arr = inkLists.lookup(idx);\n if (arr instanceof PDFArray) arr.scalePDFNumbers(x, y);\n }\n }\n }\n}\n","import PDFDocument from 'src/api/PDFDocument';\nimport PDFPage from 'src/api/PDFPage';\nimport PDFFont from 'src/api/PDFFont';\nimport PDFImage from 'src/api/PDFImage';\nimport { ImageAlignment } from 'src/api/image/alignment';\nimport {\n AppearanceProviderFor,\n normalizeAppearance,\n defaultButtonAppearanceProvider,\n} from 'src/api/form/appearances';\nimport PDFField, {\n FieldAppearanceOptions,\n assertFieldAppearanceOptions,\n} from 'src/api/form/PDFField';\nimport { rgb } from 'src/api/colors';\nimport { degrees } from 'src/api/rotations';\n\nimport {\n PDFRef,\n PDFStream,\n PDFAcroPushButton,\n PDFWidgetAnnotation,\n} from 'src/core';\nimport { assertIs, assertOrUndefined, assertPositive } from 'src/utils';\n\n/**\n * Represents a button field of a [[PDFForm]].\n *\n * [[PDFButton]] fields are interactive controls that users can click with their\n * mouse. This type of [[PDFField]] is not stateful. The purpose of a button\n * is to perform an action when the user clicks on it, such as opening a print\n * modal or resetting the form. Buttons are typically rectangular in shape and\n * have a text label describing the action that they perform when clicked.\n */\nexport default class PDFButton extends PDFField {\n /**\n * > **NOTE:** You probably don't want to call this method directly. Instead,\n * > consider using the [[PDFForm.getButton]] method, which will create an\n * > instance of [[PDFButton]] for you.\n *\n * Create an instance of [[PDFButton]] from an existing acroPushButton and ref\n *\n * @param acroPushButton The underlying `PDFAcroPushButton` for this button.\n * @param ref The unique reference for this button.\n * @param doc The document to which this button will belong.\n */\n static of = (\n acroPushButton: PDFAcroPushButton,\n ref: PDFRef,\n doc: PDFDocument,\n ) => new PDFButton(acroPushButton, ref, doc);\n\n /** The low-level PDFAcroPushButton wrapped by this button. */\n readonly acroField: PDFAcroPushButton;\n\n private constructor(\n acroPushButton: PDFAcroPushButton,\n ref: PDFRef,\n doc: PDFDocument,\n ) {\n super(acroPushButton, ref, doc);\n\n assertIs(acroPushButton, 'acroButton', [\n [PDFAcroPushButton, 'PDFAcroPushButton'],\n ]);\n\n this.acroField = acroPushButton;\n }\n\n /**\n * Display an image inside the bounds of this button's widgets. For example:\n * ```js\n * const pngImage = await pdfDoc.embedPng(...)\n * const button = form.getButton('some.button.field')\n * button.setImage(pngImage, ImageAlignment.Center)\n * ```\n * This will update the appearances streams for each of this button's widgets.\n * @param image The image that should be displayed.\n * @param alignment The alignment of the image.\n */\n setImage(image: PDFImage, alignment = ImageAlignment.Center) {\n const widgets = this.acroField.getWidgets();\n for (let idx = 0, len = widgets.length; idx < len; idx++) {\n const widget = widgets[idx];\n const streamRef = this.createImageAppearanceStream(\n widget,\n image,\n alignment,\n );\n this.updateWidgetAppearances(widget, { normal: streamRef });\n }\n\n this.markAsClean();\n }\n\n /**\n * Set the font size for this field. Larger font sizes will result in larger\n * text being displayed when PDF readers render this button. Font sizes may\n * be integer or floating point numbers. Supplying a negative font size will\n * cause this method to throw an error.\n *\n * For example:\n * ```js\n * const button = form.getButton('some.button.field')\n * button.setFontSize(4)\n * button.setFontSize(15.7)\n * ```\n *\n * > This method depends upon the existence of a default appearance\n * > (`/DA`) string. If this field does not have a default appearance string,\n * > or that string does not contain a font size (via the `Tf` operator),\n * > then this method will throw an error.\n *\n * @param fontSize The font size to be used when rendering text in this field.\n */\n setFontSize(fontSize: number) {\n assertPositive(fontSize, 'fontSize');\n this.acroField.setFontSize(fontSize);\n this.markAsDirty();\n }\n\n /**\n * Show this button on the specified page with the given text. For example:\n * ```js\n * const ubuntuFont = await pdfDoc.embedFont(ubuntuFontBytes)\n * const page = pdfDoc.addPage()\n *\n * const form = pdfDoc.getForm()\n * const button = form.createButton('some.button.field')\n *\n * button.addToPage('Do Stuff', page, {\n * x: 50,\n * y: 75,\n * width: 200,\n * height: 100,\n * textColor: rgb(1, 0, 0),\n * backgroundColor: rgb(0, 1, 0),\n * borderColor: rgb(0, 0, 1),\n * borderWidth: 2,\n * rotate: degrees(90),\n * font: ubuntuFont,\n * })\n * ```\n * This will create a new widget for this button field.\n * @param text The text to be displayed for this button widget.\n * @param page The page to which this button widget should be added.\n * @param options The options to be used when adding this button widget.\n */\n addToPage(\n // TODO: This needs to be optional, e.g. for image buttons\n text: string,\n page: PDFPage,\n options?: FieldAppearanceOptions,\n ) {\n assertOrUndefined(text, 'text', ['string']);\n assertOrUndefined(page, 'page', [[PDFPage, 'PDFPage']]);\n assertFieldAppearanceOptions(options);\n\n // Create a widget for this button\n const widget = this.createWidget({\n x: (options?.x ?? 0) - (options?.borderWidth ?? 0) / 2,\n y: (options?.y ?? 0) - (options?.borderWidth ?? 0) / 2,\n width: options?.width ?? 100,\n height: options?.height ?? 50,\n textColor: options?.textColor ?? rgb(0, 0, 0),\n backgroundColor: options?.backgroundColor ?? rgb(0.75, 0.75, 0.75),\n borderColor: options?.borderColor,\n borderWidth: options?.borderWidth ?? 0,\n rotate: options?.rotate ?? degrees(0),\n caption: text,\n hidden: options?.hidden,\n page: page.ref,\n });\n const widgetRef = this.doc.context.register(widget.dict);\n\n // Add widget to this field\n this.acroField.addWidget(widgetRef);\n\n // Set appearance streams for widget\n const font = options?.font ?? this.doc.getForm().getDefaultFont();\n this.updateWidgetAppearance(widget, font);\n\n // Add widget to the given page\n page.node.addAnnot(widgetRef);\n }\n\n /**\n * Returns `true` if this button has been marked as dirty, or if any of this\n * button's widgets do not have an appearance stream. For example:\n * ```js\n * const button = form.getButton('some.button.field')\n * if (button.needsAppearancesUpdate()) console.log('Needs update')\n * ```\n * @returns Whether or not this button needs an appearance update.\n */\n needsAppearancesUpdate(): boolean {\n if (this.isDirty()) return true;\n\n const widgets = this.acroField.getWidgets();\n for (let idx = 0, len = widgets.length; idx < len; idx++) {\n const widget = widgets[idx];\n const hasAppearances =\n widget.getAppearances()?.normal instanceof PDFStream;\n if (!hasAppearances) return true;\n }\n\n return false;\n }\n\n /**\n * Update the appearance streams for each of this button's widgets using\n * the default appearance provider for buttons. For example:\n * ```js\n * const helvetica = await pdfDoc.embedFont(StandardFonts.Helvetica)\n * const button = form.getButton('some.button.field')\n * button.defaultUpdateAppearances(helvetica)\n * ```\n * @param font The font to be used for creating the appearance streams.\n */\n defaultUpdateAppearances(font: PDFFont) {\n assertIs(font, 'font', [[PDFFont, 'PDFFont']]);\n this.updateAppearances(font);\n }\n\n /**\n * Update the appearance streams for each of this button's widgets using\n * the given appearance provider. If no `provider` is passed, the default\n * appearance provider for buttons will be used. For example:\n * ```js\n * const helvetica = await pdfDoc.embedFont(StandardFonts.Helvetica)\n * const button = form.getButton('some.button.field')\n * button.updateAppearances(helvetica, (field, widget, font) => {\n * ...\n * return {\n * normal: drawButton(...),\n * down: drawButton(...),\n * }\n * })\n * ```\n * @param font The font to be used for creating the appearance streams.\n * @param provider Optionally, the appearance provider to be used for\n * generating the contents of the appearance streams.\n */\n updateAppearances(\n font: PDFFont,\n provider?: AppearanceProviderFor,\n ) {\n assertIs(font, 'font', [[PDFFont, 'PDFFont']]);\n assertOrUndefined(provider, 'provider', [Function]);\n\n const widgets = this.acroField.getWidgets();\n for (let idx = 0, len = widgets.length; idx < len; idx++) {\n const widget = widgets[idx];\n this.updateWidgetAppearance(widget, font, provider);\n }\n }\n\n private updateWidgetAppearance(\n widget: PDFWidgetAnnotation,\n font: PDFFont,\n provider?: AppearanceProviderFor,\n ) {\n const apProvider = provider ?? defaultButtonAppearanceProvider;\n const appearances = normalizeAppearance(apProvider(this, widget, font));\n this.updateWidgetAppearanceWithFont(widget, font, appearances);\n }\n}\n"],"names":["ColorTypes","grayscale","gray","type","Grayscale","rgb","red","green","blue","RGB","cmyk","cyan","magenta","yellow","key","CMYK","setFillingColor","color","JSON","stringify","setStrokingColor","componentsToColor","comps","scale","length","undefined","colorToComponents","Error","name","msg","expected","actual","constructor","onValue","namePart","fieldName","lineLength","cellCount","textLength","maxLength","normalizeAppearance","appearance","normal","tfRegex","getDefaultFontSize","field","da","getDefaultAppearance","daMatch","match","defaultFontSize","Number","isFinite","colorRegex","getDefaultColor","c1","c2","c3","c4","colorSpace","updateDefaultAppearance","font","fontSize","toString","join","setDefaultAppearance","defaultCheckBoxAppearanceProvider","checkBox","widget","widgetColor","fieldColor","acroField","rectangle","getRectangle","ap","getAppearanceCharacteristics","bs","getBorderStyle","borderWidth","getWidth","rotation","getRotation","width","height","rotate","black","borderColor","getBorderColor","normalBackgroundColor","getBackgroundColor","downBackgroundColor","textColor","options","x","y","thickness","markColor","on","filled","off","down","defaultRadioGroupAppearanceProvider","radioGroup","dotColor","defaultButtonAppearanceProvider","button","widgetFontSize","fieldFontSize","captions","getCaptions","normalText","downText","bounds","normalLayout","alignment","Center","downLayout","Math","min","textLines","line","defaultTextFieldAppearanceProvider","textField","text","getText","padding","isCombed","isMultiline","layout","getAlignment","lines","getMaxLength","cells","defaultDropdownAppearanceProvider","dropdown","getSelected","Left","defaultOptionListAppearanceProvider","optionList","getOptions","selected","isSorted","sort","idx","len","lineHeight","selectedLines","includes","push","selectedColor","ref","doc","embedder","alreadyEmbedded","this","factor","size","embed","embedIntoContext","context","of","PDFEmbeddedPage","modified","fontName","encodeText","widthOfTextAtSize","heightAtSize","descender","heightOfFontAtSize","sizeAtHeight","sizeOfFontAtHeight","getCharacterSet","encoding","supportedCodePoints","characterSet","PDFFont","scaleToFit","imgWidthScale","imgHeightScale","embedTask","PDFImage","ImageAlignment","assertFieldAppearanceOptions","Object","backgroundColor","getName","getFullyQualifiedName","isReadOnly","hasFlag","ReadOnly","enableReadOnly","setFlagTo","disableReadOnly","isRequired","Required","enableRequired","disableRequired","isExported","NoExport","enableExporting","disableExporting","needsAppearancesUpdate","defaultUpdateAppearances","_font","markAsDirty","getForm","markFieldAsDirty","markAsClean","markFieldAsClean","isDirty","fieldIsDirty","createWidget","degreesAngle","caption","hidden","Boolean","pageRef","page","create","rect","setRectangle","setP","ac","getOrCreateAppearanceCharacteristics","setBackgroundColor","setRotation","setCaptions","setBorderColor","getOrCreateBorderStyle","setWidth","Print","Hidden","Invisible","newDa","updateWidgetAppearanceWithFont","rollover","updateWidgetAppearances","createAppearanceStream","updateOnOffWidgetAppearance","createAppearanceDict","setNormalAppearance","setRolloverAppearance","removeRolloverAppearance","setDownAppearance","removeDownAppearance","dict","Resources","Font","stream","formXObject","BBox","obj","Matrix","register","createImageAppearanceStream","image","adj","imageDims","xSkew","ySkew","Right","imageName","addRandomSuffix","XObject","onStreamRef","offStreamRef","appearanceDict","set","acroCheckBox","check","getOnValue","setValue","uncheck","isChecked","getValue","addToPage","widgetRef","addWidget","setAppearanceState","updateWidgetAppearance","node","addAnnot","widgets","getWidgets","state","getAppearanceState","getAppearances","has","updateAppearances","provider","Function","appearances","PDFCheckBox","acroComboBox","rawOptions","Array","display","value","decodeText","values","getValues","setOptions","optionObjects","fromText","addOptions","optionsArr","isArray","existingOptions","newOptions","concat","select","merge","validOptions","find","option","enableEditing","enableMultiselect","existingValues","setValues","clear","setFontSize","isEditable","Edit","disableEditing","Sort","enableSorting","disableSorting","isMultiselect","MultiSelect","disableMultiselect","isSpellChecked","DoNotSpellCheck","enableSpellChecking","disableSpellChecking","isSelectOnClick","CommitOnSelChange","enableSelectOnClick","disableSelectOnClick","getDefaultFont","PDFDropdown","acroListBox","PDFOptionList","acroRadioButton","exportValues","getExportValues","exportOptions","onValues","getOnValues","onOptions","isOffToggleable","NoToggleToOff","enableOffToggling","disableOffToggling","isMutuallyExclusive","RadiosInUnison","enableMutualExclusion","disableMutualExclusion","addOptionToPage","apStateValue","addWidgetWithOpt","PDFRadioGroup","acroSignature","PDFSignature","acroText","isRichFormatted","setText","disableRichFormatting","removeValue","quadding","getQuadding","setAlignment","setQuadding","setMaxLength","MAX_SAFE_INTEGER","removeMaxLength","setImage","fieldAlignment","streamRef","Multiline","enableMultiline","disableMultiline","isPassword","Password","enablePassword","disablePassword","isFileSelector","FileSelect","enableFileSelection","disableFileSelection","isScrollable","DoNotScroll","enableScrolling","disableScrolling","Comb","enableCombing","console","warn","disableCombing","RichText","enableRichFormatting","PDFTextField","StandardFonts","acroForm","embedDefaultFont","embedStandardFont","Helvetica","dirtyFields","Set","defaultFontCache","populatedBy","hasXFA","deleteXFA","delete","getFields","allFields","getAllFields","fields","convertToPDFField","getFieldMaybe","getField","getButton","getCheckBox","getDropdown","getOptionList","getRadioGroup","getSignature","getTextField","createButton","nameParts","splitFieldName","parent","findOrCreateNonTerminals","nonTerminal","setPartialName","terminal","addFieldToParent","createCheckBox","createDropdown","comboBox","createOptionList","listBox","createRadioGroup","radioButton","createTextField","flatten","updateFieldAppearances","i","lenFields","j","lenWidgets","findWidgetPage","findWidgetAppearanceRef","xObjectKey","newXObject","operators","filter","pushOperators","removeField","pages","add","removeAnnot","forEach","fieldKids","normalizedEntries","Kids","kidsCount","childIndex","child","get","fieldRef","access","P","getPages","getObjectRef","findPageForAnnotationRef","refOrDict","getNormalAppearance","partialNames","parentRef","res","findNonTerminal","setParent","nodeRef","addField","partialName","getPartialName","PDFForm","ParseSpeeds","fullyQualifiedName","parts","split","slice","entries","Fields","catalog","Names","lookup","EmbeddedFiles","EFNames","fileName","PDFEmbeddedFile","Javascript","JSNames","scriptName","PDFJavaScript","ignoreEncryption","updateMetadata","defaultWordBreaks","computePages","Pages","traverse","pageMap","getOrCreateForm","getOrCreateAcroForm","trailerInfo","Root","isEncrypted","Encrypt","pageCache","Map","formCache","fonts","images","embeddedPages","embeddedFiles","javaScripts","updateInfoDict","load","pdf","parseSpeed","Slow","throwOnInvalidObject","capNumbers","Uint8Array","ArrayBuffer","bytes","forBytesWithOptions","parseDocument","PDFDocument","pageTree","withContext","pageTreeRef","withContextAndPages","registerFontkit","fontkit","form","getTitle","title","getInfoDict","Title","assertIsLiteralOrHexString","getAuthor","author","Author","getSubject","subject","Subject","getKeywords","keywords","Keywords","getCreator","creator","Creator","getProducer","producer","Producer","getCreationDate","creationDate","CreationDate","decodeDate","getModificationDate","modificationDate","ModDate","setTitle","showInWindowTitleBar","getOrCreateViewerPreferences","setDisplayDocTitle","setAuthor","setSubject","setKeywords","setCreator","setProducer","setLanguage","language","setCreationDate","Date","fromDate","setModificationDate","getPageCount","pageCount","getPage","index","getPageIndices","removePage","removeLeafNode","addPage","insertPage","dims","A4","setSize","insertLeafNode","invalidate","copyPages","srcDoc","indices","flush","copier","for","srcPages","copiedPages","srcPage","copiedPage","copy","pdfCopy","contentPages","addJavaScript","script","JavaScriptEmbedder","nextRef","javaScript","attach","attachment","mimeType","description","afRelationship","FileEmbedder","embeddedFile","embedFont","subset","customName","features","assertFontkit","TypeError","pdfFont","embedJpg","jpg","pdfImage","embedPng","png","embedPdf","embedPages","embedPage","boundingBox","transformationMatrix","boundingBoxes","transformationMatrices","currPage","nextPage","maybeCopyPage","p","box","matrix","embedAll","save","useObjectStreams","addDefaultPage","objectsPerTick","forContext","serializeToBuffer","saveAsBase64","dataUri","otherOptions","base64","annotations","Annots","indexOf","embeddables","pdfLib","now","info","existingInfo","Info","newInfo","pdfObject","BlendMode","leafNode","fontColor","angle","Rotate","asNumber","mediaBox","getMediaBox","setMediaBox","cropBox","getCropBox","bleedBox","getBleedBox","trimBox","getTrimBox","artBox","getArtBox","hasCropBox","CropBox","hasBleedBox","BleedBox","hasTrimBox","TrimBox","hasArtBox","ArtBox","setCropBox","setBleedBox","setTrimBox","setArtBox","getSize","setHeight","MediaBox","getHeight","asRectangle","translateContent","normalize","getContentStream","start","createContentStream","startRef","end","endRef","wrapContentStreams","scaleContent","scaleAnnotations","annots","annot","scaleAnnot","resetPosition","setFont","fontKey","newFontDictionary","setFontColor","setLineHeight","getPosition","getX","getY","moveTo","moveDown","yDecrease","moveUp","yIncrease","moveLeft","xDecrease","moveRight","xIncrease","operator","contentStream","drawText","opacity","maxWidth","wordBreaks","blendMode","setOrEmbedFont","oldFont","newFont","newFontKey","t","encodedLines","graphicsStateKey","maybeEmbedGraphicsState","graphicsState","resetFont","drawImage","drawPage","embeddedPage","xScale","yScale","drawSvgPath","path","borderDashArray","borderDashPhase","borderLineCap","borderOpacity","drawLine","dashArray","dashPhase","lineCap","drawRectangle","drawSquare","drawEllipse","drawCircle","oldFontKey","getFont","useExisting","contentStreamRef","addContentStream","Type","ca","CA","BM","newExtGState","selectors","list","scalePDFNumbers","inkLists","arr","PDFPage","dummyRef","pageLeaf","withContextAndParent","acroPushButton","PDFButton"],"sourceRoot":""}