I'm using react-pdf to render a PDF document in my react app. I've added a function to get the coordinates of the user's click. But when I calculate the Y value based on the clientY
and containerRect, and pass these calculated coordinates to pdf-lib to insert a text field, the field appears way above the clicked position. The Y coordinate seems to be incorrect.
Any suggestions why this would be happening?
React code:
import React from 'react';
import { Document, Page, pdfjs } from 'react-pdf';
import 'react-pdf/dist/esm/Page/TextLayer.css';
import 'react-pdf/dist/esm/Page/AnnotationLayer.css';
pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.js`;
export default function PDFViewer() {
const handleClick = async (event) => {
const { clientX, clientY } = event;
const page = document.querySelector('[data-page-number="6"]');
const containerRect = page.getBoundingClientRect();
const x = clientX - containerRect.left;
const y = clientY - containerRect.top;
console.log('Clicked at coordinates:', x, y);
};
return (
<div>
<Document file='ps-test.pdf'>
<Page pageNumber={6} onClick={handleClick} />
</Document>
</div>
);
}
Node code:
const pdfDoc = await PDFDocument.load(existingPdfBytes);
const form = pdfDoc.getForm();
const page = pdfDoc.getPage(5);
const textFieldStyles = {
width: 260,
height: 14,
borderWidth: 1,
backgroundColor: rgb(1, 1, 1),
};
const dateField = form.createTextField('candidates.date');
dateField.setText('');
dateField.addToPage(page, {
...textFieldStyles,
x: 106,
y: 478,
});
const pdfBytes = await pdfDoc.save();
fs.writeFileSync('my-pdf.pdf', pdfBytes);