From c95254c874f69c4a135cae965c8f669b30fd4174 Mon Sep 17 00:00:00 2001
From: Nadun Sanjeevana <108867149+NadunSanjeevana@users.noreply.github.com>
Date: Tue, 12 Sep 2023 00:19:21 +0530
Subject: [PATCH] pdf upload to firebase
---
package-lock.json | 14 +++-
package.json | 1 +
src/api/report/reportsdata.js | 13 ++++
src/api/report/saveReport.js | 11 +--
.../sign-in/config.js => firebase.js} | 4 ++
src/layouts/authentication/sign-in/index.js | 2 +-
src/layouts/reports/data/reportsdata.js | 40 +++++++++++
src/layouts/reports/reports.js | 69 ++++++++++---------
8 files changed, 112 insertions(+), 42 deletions(-)
create mode 100644 src/api/report/reportsdata.js
rename src/{layouts/authentication/sign-in/config.js => firebase.js} (91%)
diff --git a/package-lock.json b/package-lock.json
index dc9c5c1..0a06e92 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -39,6 +39,7 @@
"react-table": "7.8.0",
"stylis": "4.1.4",
"stylis-plugin-rtl": "2.1.1",
+ "uuid": "^9.0.0",
"xlsx": "^0.18.5",
"yup": "1.1.1"
},
@@ -13661,6 +13662,14 @@
"websocket-driver": "^0.7.4"
}
},
+ "node_modules/sockjs/node_modules/uuid": {
+ "version": "8.3.2",
+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
+ "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
+ "bin": {
+ "uuid": "dist/bin/uuid"
+ }
+ },
"node_modules/source-list-map": {
"version": "2.0.1",
"license": "MIT"
@@ -14725,8 +14734,9 @@
}
},
"node_modules/uuid": {
- "version": "8.3.2",
- "license": "MIT",
+ "version": "9.0.0",
+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.0.tgz",
+ "integrity": "sha512-MXcSTerfPa4uqyzStbRoTgt5XIe3x5+42+q1sDuy3R5MDk66URdLMOZe5aPX/SQd+kuYAh0FdP/pO28IkQyTeg==",
"bin": {
"uuid": "dist/bin/uuid"
}
diff --git a/package.json b/package.json
index 79481db..54c08f1 100644
--- a/package.json
+++ b/package.json
@@ -44,6 +44,7 @@
"react-table": "7.8.0",
"stylis": "4.1.4",
"stylis-plugin-rtl": "2.1.1",
+ "uuid": "^9.0.0",
"xlsx": "^0.18.5",
"yup": "1.1.1"
},
diff --git a/src/api/report/reportsdata.js b/src/api/report/reportsdata.js
new file mode 100644
index 0000000..0b825e5
--- /dev/null
+++ b/src/api/report/reportsdata.js
@@ -0,0 +1,13 @@
+import axios from "axios";
+
+// Function to fetch data from the backend
+export async function getReportList() {
+ try {
+ const response = await axios.get("/get-all-reports"); // Adjust the endpoint URL
+ console.log(response.data);
+ return response.data;
+ } catch (error) {
+ console.error("Error fetching data from the backend:", error);
+ throw error;
+ }
+}
diff --git a/src/api/report/saveReport.js b/src/api/report/saveReport.js
index 3c96233..97c2263 100644
--- a/src/api/report/saveReport.js
+++ b/src/api/report/saveReport.js
@@ -1,13 +1,14 @@
import axios from "axios";
-// Function to send a PDF to the backend
-export async function savePdf(pdf, userID, title) {
+// Function to send the PDF URL to the backend
+export async function savePdf(pdfURL, userID, title) {
try {
const formData = new FormData();
- formData.append("pdf", pdf, "report.pdf"); // Attach the PDF with a filename
+ formData.append("pdfURL", pdfURL); // Attach the PDF URL
formData.append("userID", userID); // Include the userID in the form data
formData.append("title", title);
- const response = await axios.post("/upload-pdf", formData, {
+
+ const response = await axios.post("/upload-pdf-url", formData, {
headers: {
"Content-Type": "multipart/form-data",
},
@@ -16,7 +17,7 @@ export async function savePdf(pdf, userID, title) {
console.log(response.data);
return response.data;
} catch (error) {
- console.error("Error sending PDF to the backend:", error);
+ console.error("Error sending PDF URL to the backend:", error);
throw error;
}
}
diff --git a/src/layouts/authentication/sign-in/config.js b/src/firebase.js
similarity index 91%
rename from src/layouts/authentication/sign-in/config.js
rename to src/firebase.js
index 17d5279..2cee295 100644
--- a/src/layouts/authentication/sign-in/config.js
+++ b/src/firebase.js
@@ -1,6 +1,8 @@
import { initializeApp } from "firebase/app";
import { getAuth, GoogleAuthProvider } from "firebase/auth";
+import { getStorage } from "firebase/storage";
+
// Load environment variables
const apiKey = process.env.REACT_APP_API_KEY;
const authDomain = process.env.REACT_APP_AUTH_DOMAIN;
@@ -27,3 +29,5 @@ const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const provider = new GoogleAuthProvider();
export { auth, provider };
+
+export const storage = getStorage(app);
diff --git a/src/layouts/authentication/sign-in/index.js b/src/layouts/authentication/sign-in/index.js
index 7383bca..9be41db 100644
--- a/src/layouts/authentication/sign-in/index.js
+++ b/src/layouts/authentication/sign-in/index.js
@@ -35,7 +35,7 @@ import BasicLayout from "layouts/authentication/components/BasicLayout";
import bgImage from "assets/images/bg-sign-in-basic.jpeg";
import GoogleButton from "react-google-button";
-import { auth, provider } from "layouts/authentication/sign-in/config";
+import { auth, provider } from "../../../firebase";
import { signInWithPopup } from "firebase/auth";
import { useNavigate } from "react-router-dom";
diff --git a/src/layouts/reports/data/reportsdata.js b/src/layouts/reports/data/reportsdata.js
index 29f886b..29dc803 100644
--- a/src/layouts/reports/data/reportsdata.js
+++ b/src/layouts/reports/data/reportsdata.js
@@ -19,6 +19,9 @@ Coded by www.creative-tim.com
import MDBox from "components/MDBox";
import MDTypography from "components/MDTypography";
import MDBadge from "components/MDBadge";
+// import { useEffect } from "react";
+// import { getReportList } from "api/report/reportsdata";
+// import { useState } from "react";
export default function data() {
const Job = ({ title, description }) => (
@@ -30,6 +33,20 @@ export default function data() {
);
+ // const [reportDetails, setReportsDetails] = useState([]);
+
+ // useEffect(() => {
+ // // Fetch average price data from the Flask API endpoint
+ // getReportList()
+ // .then((data) => {
+ // setReportsDetails(data);
+ // //console.log(adDistribution);
+ // })
+ // .catch((error) => {
+ // console.error("Error fetching data:", error);
+ // });
+ // }, []);
+
return {
rawData: [
{
@@ -71,6 +88,29 @@ export default function data() {
{ Header: "Download", accessor: "action", align: "center" },
],
+ // rows: getReportList.map((report, index) => ({
+ // author: (
+ //
+ // DemographicAnalysis
+ //
+ // ),
+ // function: ,
+ // status: (
+ //
+ //
+ //
+ // ),
+ // employed: (
+ //
+ // 23/04/18
+ //
+ // ),
+ // action: (
+ //
+ // Download
+ //
+ // ),
+ // })),
rows: [
{
author: (
diff --git a/src/layouts/reports/reports.js b/src/layouts/reports/reports.js
index 0422139..9631f9a 100644
--- a/src/layouts/reports/reports.js
+++ b/src/layouts/reports/reports.js
@@ -3,6 +3,8 @@ import "jspdf-autotable";
import html2canvas from "html2canvas";
import * as XLSX from "xlsx";
import { savePdf } from "api/report/saveReport";
+import { storage } from "../../firebase";
+import { ref, uploadBytes, getDownloadURL } from "firebase/storage";
export const generateCSV = (data, filename) => {
const csvContent = "data:text/csv;charset=utf-8," + data.map((row) => row.join(",")).join("\n");
@@ -23,47 +25,46 @@ export const generateExcel = (data, filename) => {
// Function to generate PDF
const generatePDF = async (componentsToPrint, contentRef, title) => {
- // Create a new jsPDF instance
- const doc = new jsPDF();
+ try {
+ // Create a new jsPDF instance
+ const doc = new jsPDF();
+
+ const pageHeight = doc.internal.pageSize.height;
+ let yOffset = 10;
- const pageHeight = doc.internal.pageSize.height;
- let yOffset = 10;
+ for (let i = 0; i < componentsToPrint.length; i++) {
+ if (contentRef.current.children[i]) {
+ const canvas = await html2canvas(contentRef.current.children[i]);
+ const componentHeight = (canvas.height * 190) / canvas.width;
- for (let i = 0; i < componentsToPrint.length; i++) {
- // Skip components that are not rendered (e.g., if they are conditionally displayed)
- if (contentRef.current.children[i]) {
- // Use html2canvas to capture the content of the component
- const canvas = await html2canvas(contentRef.current.children[i]);
+ if (yOffset + componentHeight > pageHeight) {
+ doc.addPage();
+ yOffset = 10;
+ }
- // Check if there's enough space on the current page for the component
- const componentHeight = (canvas.height * 190) / canvas.width; // Calculate component height based on width
- if (yOffset + componentHeight > pageHeight) {
- // If not enough space, add a new page
- doc.addPage();
- yOffset = 10; // Reset yOffset for the new page
+ const contentDataURL = canvas.toDataURL("image/jpeg");
+ doc.addImage(contentDataURL, "JPEG", 10, yOffset + 15, 190, componentHeight);
+ yOffset += componentHeight + 25;
}
+ }
- // Convert the captured canvas to a data URL
- const contentDataURL = canvas.toDataURL("image/jpeg");
+ // Save the PDF with a file name
+ if (!title) {
+ title = "graphs.pdf";
+ }
- // Adjust the position as needed
+ doc.save(`${title}.pdf`);
+ const pdfBlob = doc.output("blob");
+ const userID = "pu123";
+ const pdfRef = ref(storage, `Reports/${title}`);
- // Add the component content as an image to the PDF
- doc.addImage(contentDataURL, "JPEG", 10, yOffset + 15, 190, componentHeight); // Adjust the position and size as needed
- yOffset += componentHeight + 25; // Add vertical spacing between title and component
- }
- }
+ // Upload the PDF to Firebase Storage
+ await uploadBytes(pdfRef, pdfBlob);
- // Save the PDF with a file name
- if (!title) {
- title = "graphs.pdf";
- }
- doc.save(`${title}.pdf`);
- const pdfBlob = doc.output("blob");
- const userID = "pu123";
- try {
- // Send the PDF to the backend using the savePdf function
- const response = await savePdf(pdfBlob, userID, title);
+ // Get the download URL of the uploaded PDF
+ const downloadURL = await getDownloadURL(pdfRef); // Add this import: import { getDownloadURL } from "firebase/storage";
+ // Send the PDF URL to the backend using the savePdf function or do whatever you need with it
+ const response = await savePdf(downloadURL, userID, title);
if (response && response.message) {
console.log("PDF uploaded successfully!");
@@ -71,7 +72,7 @@ const generatePDF = async (componentsToPrint, contentRef, title) => {
console.error("Failed to upload PDF:", response.error);
}
} catch (error) {
- console.error("An error occurred while uploading PDF:", error);
+ console.error("An error occurred while generating/uploading PDF:", error);
}
};