I am using next js 14 with app router. I am building an application where users enter some fields and I want to display field:value
on a pdf with background. I am aware that these two library will be used but not sure how.
- https://www.npmjs.com/package/react-pdf
- https://www.npmjs.com/package/@react-pdf/renderer
Please help me out how to make it possible. My use case is similar to this site:
https://marriagebiodata.app/en where one can select background.
I have inspected their page and I guess they are using https://www.npmjs.com/package/react-pdf
So far I am here:
'use client'
import { Container } from '@mui/material'
import { useRef } from 'react'
import { pdfjs, Document, Page } from 'react-pdf'
import { CustomTextRenderer } from 'react-pdf/dist/cjs/shared/types'
import 'react-pdf/dist/esm/Page/AnnotationLayer.css'
import 'react-pdf/dist/esm/Page/TextLayer.css'
pdfjs.GlobalWorkerOptions.workerSrc = new URL(
'pdfjs-dist/build/pdf.worker.min.mjs',
import.meta.url,
).toString()
type TemplateEditorProps = {}
const TemplateEditor: React.FC<TemplateEditorProps> = () => {
const pdfFile = '/template.pdf'
const canvasRef = useRef<HTMLCanvasElement | null>(null)
const watermarkText = `© ${new Date().getFullYear()} marriagebiodatamaker.app`
const drawTextOnCanvas = (canvas: HTMLCanvasElement) => {
if (canvas) {
const ctx = canvas.getContext('2d')
if (ctx) {
ctx.font = '48px Arial'
ctx.fillStyle = 'rgba(255, 255, 255, 0.5)'
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
// You can adjust the position based on the canvas size or other criteria
ctx.fillText(watermarkText, canvas.width / 2, canvas.height / 2)
}
}
}
// This function is used to handle the canvas drawing after the page has rendered
const handleRenderSuccess = () => {
if (canvasRef.current) {
drawTextOnCanvas(canvasRef.current)
}
}
return (
<Container maxWidth="lg">
<Document file={pdfFile}>
<Page
width={800}
pageNumber={1}
renderTextLayer={true}
canvasRef={(canvas) => {
if (canvas) {
canvasRef.current = canvas
}
}}
onRenderSuccess={handleRenderSuccess}
/>
</Document>
</Container>
)
}
export default TemplateEditor