I’m using next.js 14 and I’m trying to merge 2 pdf files based on their contents. However, when I try to read the content of the pdf file using const pdf = await pdfjsLib.getDocument(content).promise;, I got the error Unhandled Runtime Error
Error: Element type is invalid. Received a promise that resolves to: [object Promise]. Lazy element type must resolve to a class or function. Can anyone help me solve this? I dont even use lasy elemnt. Thanks in advance!
page.tsx:
import PDFFileMerger from "@/components/PDFFileMerger";
import Image from "next/image";
import React, { useState } from 'react';
export default function Home() {
return (
<main className="overflow-hidden">
<PDFFileMerger />
</main>
);
}
PDFFileMerger.tsx:
"use client";
import React, { useState, ChangeEvent, useEffect } from 'react';
import { PDFDocument, rgb } from 'pdf-lib';
import * as pdfjsLib from 'pdfjs-dist';
function PDFFileMerger() {
const [file1, setFile1] = useState<File | null>(null);
const [file2, setFile2] = useState<File | null>(null);
const [mergedPdf, setMergedPdf] = useState<Uint8Array | null>(null);
const [textOutput, setTextOutput] = useState<string>('');
useEffect(() => {
if (!file1) return;
const fileReader = new FileReader();
fileReader.onload = async function() {
const content = this.result;
if (content) {
try {
const pdf = await pdfjsLib.getDocument(content).promise;
console.log(pdf);
} catch (error) {
console.error('Error loading PDF:', error);
}
}
};
fileReader.readAsArrayBuffer(file1);
}, [file1] );
const handleFile1Change = (event: React.ChangeEvent<HTMLInputElement>) => {
const selectedFile = event.target.files?.[0];
setFile1(selectedFile || null);
};
return (
<div>
<input id="pdf1" type="file" accept=".pdf" onChange={handleFile1Change} />
<input type="file" accept=".pdf" onChange={handleFile2Change} />
<button onClick={handleMerge}>Merge PDFs</button>
{mergedPdf && (
<a
href={URL.createObjectURL(new Blob([mergedPdf], { type: 'application/pdf' }))}
target="_blank"
rel="noopener noreferrer"
download="merged.pdf"
>
Open Merged PDF
</a>
)}
<div id="textOutput">{textOutput}</div>
</div>
);
};
export default PDFFileMerger;
I tried to use with and without useEffect(), and adding async, await, etc… . But the error still occurs whenever I have the line const pdf = await pdfjsLib.getDocument(content).promise;