[Server Action] return PDF buffer and then open it in a new tab in browser
Unanswered
Cane di Oropa posted this in #help-forum
Cane di OropaOP
async function getPDFBuffer(filename: string) {
"use server";
try {
const buffer = await fs.readFile(filePath);
return buffer;
} catch (error) {
console.error(`Error reading file ${filename}:`, error);
throw new Error("Failed to read PDF file");
}
}while on the client component
onClick={async () => {
try {
// Add your view action logic here
console.log("View PDF:", rowData);
const pdfBuffer = await getPDFBuffer(
rowData.filename
);
console.log("🚀 ~ pdfBuffer ~ pdfBuffer:", pdfBuffer);
// Convert buffer to Blob
const blob = new Blob([pdfBuffer], {
type: "application/pdf",
});
// Create a URL for the Blob
const url = URL.createObjectURL(blob);
// Open the URL in a new tab
window.open(url, "_blank");
// Clean up the URL object after the new tab is opened
// URL.revokeObjectURL(url);
} catch (error) {
console.error(error);
}
}}6 Replies
Cane di OropaOP
One thing that I noticed was console log of buffer in server side
<Buffer 25 50 44 46 2d 31 2e ... while on client side 37, 80, 68, 70, 45, 49, 46, 52 they feels like not so identical to each otherAnd I got this while open it in a new tab
I also tried writing the file into pdf before sending back to client it shows that the file is readable in PDF format
related to https://github.com/facebook/react/issues/27931 ?
Cane di OropaOP
BUMPPPPP
Cane di OropaOP
BUMPPPPP