Method to get pageNumber for TextFields in pdf-lib ?? #1493
-
Is it possible to get page no for each pdf text fields without iterating over all pages ? import {PDFDocument} from 'pdf-lib';
const pdfDocument = PDFDocument.load("file_path")
pdfDocument
.getForm()
.getFields()
.map((_) => {
return {
pageNo: // ??? Need Logic to do so//
name: _.getName(),
type: _ instanceof PDFCheckBox ? 'generic' : 'string',
};
}) |
Beta Was this translation helpful? Give feedback.
Answered by
satyajitnayk
Aug 2, 2023
Replies: 2 comments
-
Method to give page number map async function getPageNumberMapForFields(pdfDoc: PDFDocument) {
const d: { [key: string]: number } = {};
const form = pdfDoc.getForm();
const pages = pdfDoc.getPages();
form.getFields().forEach((field) => {
form
.getField(field.getName())
.acroField.getWidgets()
.forEach((w) => {
const widgetRef: PDFRef | undefined = pdfDoc.context.getObjectRef(
w.dict,
);
for (let idx = 0, len = pages.length; idx < len; idx++) {
if (
pages[idx].node.Annots()?.indexOf(widgetRef as PDFRef) !==
undefined
) {
d[field.getName()] = idx + 1;
break;
}
}
});
});
return d;
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
satyajitnayk
-
You can also use this optimised version of the function too async function getPageNumberMapForFields(pdfDoc: PDFDocument) {
const pageNoMap: { [key: string]: number } = {};
const form = pdfDoc.getForm();
const pages = pdfDoc.getPages();
// Create a reverse map of widget references to page numbers
const pageNoRefMap: { [ref: string]: number } = {};
pages.forEach((page, index) => {
const annots = page.node.Annots();
annots?.asArray()?.forEach((annot) => {
pageNoRefMap[annot.toString()] = index + 1;
});
});
form.getFields().forEach((field) => {
form
.getField(field.getName())
.acroField.getWidgets()
.forEach((w) => {
const widgetRef: PDFRef | undefined = pdfDoc.context.getObjectRef(
w.dict,
);
pageNoMap[field.getName()] =
pageNoRefMap[widgetRef?.toString() ?? ''];
});
});
return pageNoMap;
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Method to give page number map
as of current code structure of pdf-lib
: