Simply copy and paste the following command line in your terminal to create your first Strapi project.
npx create-strapi-app
my-project
Reading PDF documents can be boring sometimes. We struggle to find the keywords and important information we need in them. If you’ve ever found yourself in this category, don't worry—I’ve got something for you, so sit back and relax!
In this tutorial, we’ll build a simple PDF summarizer in Next.js using PDF.js, Gemini AI, and Strapi. By the end of this tutorial, you’ll build a PDF summarizer and learn how to use the different tools you would be using to build it.
To follow through this tutorial, the following prerequisites should be met:
Before setting up and installing the tools needed to build, it’s important to familiarize yourself with each tool's purpose.
Let's take a glance at each of them:
Next.js: This would be used to build the frontend with Tailwind CSS.
PDF.js: This open-source JavaScript library allows web browsers to render portable document format (PDF) files directly in the browser without additional plugins. For our project, we’ll use it to extract the data from the uploaded PDF, which Gemini will summarize.
Gemini Ai: A powerful and versatile large language model(LLM) created by Google. For our project, we’ll use it to summarize the PDF parsed by Pdf.js, leveraging Gemini AI prompts to generate summaries quickly and accurately.
To use Gemini AI for sentiment analysis, you need an API key. Head to the get an API key section. Click on create API
to create your API:
Save the API somewhere because you'll need it when you start creating code.
To get the CDN links for Pdf.js, navigate to the cdn.js site and copy the following following links:
https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.min.js
https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.worker.min.js
https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf_viewer.min.css
That’s all you need from the site for Pdf.js.
You need to have Strapi installed on your local machine. Strapi v5 will be used for this project. Navigate to the folder you want your project installed in the terminal and run this command:
npx create-strapi-app@rc my-project --quickstart
Replace my-project
with the actual project name you intend on using.
This command will create a new project and install Strapi on your local machine. The –quickstart
ensures your application starts immediately after installation.
You’ll need to sign up to access your Strapi dashboard. After you’re done signing up, you should have a dashboard like this:
The next step to setting up Strapi is to create a collection type. Navigate to Content-Type Builder on the side navigation bar of your dashboard and click on Create new collection type. Give your new collection type a display name. Ensure it’s singular, not plural, as Strapi automatically pluralizes it. I’ll be naming mine SummarizedPDF
; go ahead and give yours a unique name.
Click the "Continue" button. This will take you to the next step: selecting the fields appropriate for your collection type. For the SummarizedPDF
collection type, you need to create two fields representing:
text,
a short text. I’ll name mine as simply Title
.
Click on "add another field" to add the next field.
text,
but this time, it will be long. I’ll name mine simply Summary.
Click on "finish" and then save the collection type. Your collection type should look like this:
After creating your collection type, head over to Settings > USERS & PERMISSIONS PLUGIN > Roles, and click on Public. Then scroll down to Permissions, click on Summarized-Pdf, select all to authorize the application's activity, and click Save.
So we've finished setting up Strapi. Let us now set up and develop the frontend.
To install Next.js, navigate to the project folder again through the terminal. Run the following command:
npx create-next-app@latest
Give your app a name, and following the instructions, select your options:
✔ Would you like to use TypeScript? … No / Yes
✔ Would you like to use ESLint? … No / Yes
✔ Would you like to use Tailwind CSS? … No / Yes
✔ Would you like to use `src/` directory? … No / Yes
✔ Would you like to use App Router? (recommended) … No / Yes
✔ Would you like to customize the default import alias (@/*)? … No / Yes
For this project, we won’t use typescript or the src
directory(we'll use the app router).
After the installation, change to the folder directory and start the application:
cd your-app
npm run dev
Now you’ve got everything set up, so let’s start building.
You’ll need to install two packages:
google/generative-ai: This package interacts with Google's generative AI models. It allows you to access and utilize these models in your applications, enabling you to build AI-powered. For this project, it will be used to interact with Gemini for our summary.
react-markdown: React Markdownis a library that allows you to render Markdown content in your React applications. For this project, it will be used to render the summarized contents since there would be times Gemini AI prompts would give an output in markdown format.
To install these packages, run the following command:
npm install google/generative-ai react-markdown
For the Pdf.js part, you need to add the scripts copied earlier into the layout file. Inside the layout.js
, replace the return statement with this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
return (
<html lang="en">
<head>
<script
type="module"
src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.3.136/pdf.min.mjs"
></script>
<script
type="module"
src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.3.136/pdf_viewer.min.css"
></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.3.136/pdf.worker.mjs"
type="module"
></script>
</head>
<body className={inter.className}>{children}</body>
</html>
);
While everything remains the same, we only added the scripts to it.
The pdf.min.mjs
script will provide the core functionality for parsing and displaying the PDFs. The pdf_viewer.min.css
script will define the styles for the PDF viewer component while the pdf.worker.mjs
script will allow background operations for PDF processing.
Navigate to your page.js
file and replace it with the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
"use client";
import { useState, useEffect, useRef } from "react";
import ReactMarkdown from "react-markdown";
export default function Home() {
const [summary, setSummary] = useState("");
const [title, setTitle] = useState("");
const [file, setFile] = useState(null);
const [showSummary, setShowSummary] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const fileInputRef = useRef(null);
function onFileChange(event) {
setFile(event.target.files[0]);
}
function handleTitleChange(event) {
setTitle(event.target.value);
}
async function handleShowSummary() {
if (file && title) {
setIsLoading(true);
const fileReader = new FileReader();
fileReader.onload = async (event) => {
const typedarray = new Uint8Array(event.target.result);
const pdf = await pdfjsLib.getDocument({ data: typedarray }).promise;
console.log("loaded pdf:", pdf.numPages);
let text = "";
for (let pageNum = 1; pageNum <= pdf.numPages; pageNum++) {
const page = await pdf.getPage(pageNum);
const content = await page.getTextContent();
content.items.forEach((item) => {
text += item.str + " ";
});
}
sendToAPI(text);
};
fileReader.readAsArrayBuffer(file);
}
}
function sendToAPI(text) {
console.log("Sending title to API:", title);
fetch("/api/", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ text, title }),
})
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok " + response.statusText);
}
return response.json();
})
.then((data) => {
if (data.success) {
setSummary(data.Summary);
setShowSummary(true);
} else {
throw new Error(data.message || "Unknown error occurred");
}
})
.catch((error) => {
console.error("There was a problem with the fetch operation:", error);
})
.finally(() => {
setIsLoading(false);
});
}
function handleClear() {
setSummary("");
setTitle("");
setFile(null);
fileInputRef.current.value = null;
setShowSummary(false);
}
return (
<div className="min-h-screen flex flex-col items-center justify-center bg-[#32324d]">
<div className="p-8 rounded shadow-md w-full max-w-md mb-6 border border-gray-600 bg-[#32324d]">
<h1 className="text-2xl font-bold mb-4 text-center text-white">
Upload PDF
</h1>
<form className="space-y-4">
<div>
<label
htmlFor="title"
className="block text-sm font-medium text-gray-200"
>
Enter Title
</label>
<input
id="title"
type="text"
placeholder="Enter Title"
value={title}
onChange={handleTitleChange}
className="border border-gray-500 rounded p-2 mt-1 w-full text-white bg-gray-700"
required
/>
</div>
<div>
<label
htmlFor="file"
className="block text-sm font-medium text-gray-200"
>
Upload PDF
</label>
<input
id="file"
type="file"
name="file"
accept=".pdf"
onChange={onFileChange}
ref={fileInputRef}
className="border border-gray-500 text-white rounded p-2 mt-1 w-full bg-gray-700"
required
/>
</div>
<div className="flex justify-between items-center">
<button
type="button"
onClick={handleShowSummary}
className="text-white px-4 py-2 rounded hover:opacity-90 bg-[#4945ff]"
disabled={!file || !title || isLoading}
>
Show Summary
</button>
<button
type="button"
onClick={handleClear}
className="bg-red-600 text-white px-4 py-2 rounded hover:bg-red-500"
>
Clear
</button>
</div>
</form>
{isLoading && <p className="text-yellow-300 mt-4">Summarizing...</p>}
{showSummary && summary && (
<div className="mt-6 p-4 border rounded border-gray-600 bg-gray-700">
<h2 className="text-xl text-gray-100 font-semibold mb-2">
{title}
</h2>
<ReactMarkdown className="text-gray-200">{summary}</ReactMarkdown>
</div>
)}
</div>
</div>
);
}
So, aside from importing the packages needed, here’s a breakdown of what the code does:
State Management For the state management, the code does the following:
Summary
: Stores the PDF's summarized content.title
: Saves the title of the PDF provided by the user.file
: Contains the uploaded PDF file.showSummary
: A boolean indicating whether the summary should be displayed.isLoading
: A boolean indicating whether the summarization process is currently underway.fileInputRef
: A reference to the file input element, which allows for direct manipulation of the field.Event Handlers
onFileChange
: This function updates the file state with the PDF file that the user has selected.handleTitleChange
: This function updates the title state with the value entered by the user.
handleShowSummary()
: This function reads the uploaded PDF, extracts the text content, and sends that content and the title to an API for summarizing. It uses FileReader
to read the file as an ArrayBuffer
and pdfjsLib
to extract text from each page of the PDF.
After extracting the text, it sends the data to an API endpoint(which we’ll create next) via a POST
request. The response from the API, which contains the summary, is then stored in the summary state and displayed on the page.
handleClear()
: This function resets the form by clearing the state variables i.e summary, title, and file as well as the file input field for a new input.
The JSX structure defines a form where the user can input a title and upload a PDF. It also comprises buttons to either generate a summary or clear the form.
If you check the result in your browser, you should see something like this:
Looking nice, right?
Create a .env
file in the root folder and add your Gemini API key.
API_KEY=YOUR_GEMINI_API_KEY
Now, let’s create the endpoint to receive the extracted PDF, summarize it, store it in the summary
state, and display it on the page. This is also where we’ll need Gemini and Google generative AI.
Next, inside the app
folder, create a folder called api
and a file called route.js
inside it. Add the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
import { NextResponse } from "next/server";
import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-pro" });
export async function POST(req) {
try {
const body = await req.json();
console.log("Received title:", body.title);
console.log("Received text length:", body.text.length);
if (!body.title) {
throw new Error("No title provided");
}
const prompt = "summarize the following extracted texts: " + body.text;
const result = await model.generateContent(prompt);
const summaryText = result.response.text();
console.log("Summary generated successfully");
const strapiRes = await fetch("http://localhost:1337/api/summarized-pdfs", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
data: {
Title: body.title,
Summary: summaryText,
},
}),
});
if (!strapiRes.ok) {
const errorText = await strapiRes.text();
console.error("Strapi error response:", errorText);
throw new Error(
`Failed to store summary in Strapi: ${strapiRes.status} ${strapiRes.statusText}`
);
}
const strapiData = await strapiRes.json();
console.log("Successfully stored in Strapi:", strapiData);
return NextResponse.json({
success: true,
message: "Text summarized and stored successfully",
Summary: summaryText,
});
} catch (error) {
console.error("Error in API route:", error);
return NextResponse.json(
{
success: false,
message: "Error processing request",
error: error.message,
},
{ status: 500 }
);
}
}import { NextResponse } from "next/server";
import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-pro" });
export async function POST(req) {
try {
const body = await req.json();
console.log("Received title:", body.title);
console.log("Received text length:", body.text.length);
if (!body.title) {
throw new Error("No title provided");
}
const prompt = "summarize the following extracted texts: " + body.text;
const result = await model.generateContent(prompt);
const summaryText = result.response.text();
console.log("Summary generated successfully");
const strapiRes = await fetch("http://localhost:1337/api/summarized-pdfs", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
data: {
Title: body.title,
Summary: summaryText,
},
}),
});
if (!strapiRes.ok) {
const errorText = await strapiRes.text();
console.error("Strapi error response:", errorText);
throw new Error(
`Failed to store summary in Strapi: ${strapiRes.status} ${strapiRes.statusText}`,
);
}
const strapiData = await strapiRes.json();
console.log("Successfully stored in Strapi:", strapiData);
return NextResponse.json({
success: true,
message: "Text summarized and stored successfully",
Summary: summaryText,
});
} catch (error) {
console.error("Error in API route:", error);
return NextResponse.json(
{
success: false,
message: "Error processing request",
error: error.message,
},
{ status: 500 },
);
}
}
So here’s the breakdown of the code:
POST Request Handling
The POST
function handles incoming POST
requests asynchronously, it parses the request body as JSON to access the text and title from the client, and logs the received title and text length for debugging.
Input Validation
A validation check ensures that a title is provided. If no title is provided, an error will be thrown, which will be caught and handled later.
Summarize Text
We create a prompt that instructs us to summarize the extracted texts. The generateContent()
method is then used to generate a summary extracted from the AI response.
Store the summary in Strapi
The code makes a POST
to Strapi's /api/summary-pdfs
. This contains the summarized content and title. The request will then be sent to your Strapi backend. If the request to Strapi fails, an error is reported, and an error is thrown, which is caught and handled later.
Let's test the app to see if it works:
You can see it summarizes the PDF. It is also added to your Strapi backend:
We’ve accomplished summarizing a PDF and storing the summarized content in Strapi! That’s huge!
Now, you can choose to stop here or continue with me by creating a table where you can view all your summarized PDFs without having to navigate to the Strapi backend. Let’s try to add that in the next section.
To do this, you’ll need to use the link component. Go back to your page.js
and import it into the page:
1
import Link from "next/link";
Below the div
created for displaying the summarized PDF, add the following:
1
2
3
4
5
6
7
8
<div className="w-full max-w-md text-center">
<Link
href="/summaries"
className="bg-green-600 text-white px-6 py-2 rounded hover:bg-green-500 transition-colors inline-block"
>
View Summarized PDFs
</Link>
</div>;
Now, let’s create the endpoint. Inside the app
folder, create a folder called summaries
Inside the folder, you’ll first create a file called page.js
.
Inside the file, add the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
"use client";
import { useState, useEffect } from "react";
import Link from "next/link";
import ReactMarkdown from "react-markdown";
export default function Summaries() {
const [summaries, setSummaries] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetchSummaries();
}, []);
const fetchSummaries = async () => {
try {
const response = await fetch("http://localhost:1337/api/summarized-pdfs");
if (!response.ok) {
throw new Error("Failed to fetch summaries");
}
const data = await response.json();
console.log("Fetched data:", data);
setSummaries(data.data || []);
setIsLoading(false);
} catch (error) {
console.error("Fetch error:", error);
setError(error.message);
setIsLoading(false);
}
};
if (isLoading) return <div className="text-white">Loading...</div>;
if (error) return <div className="text-white">Error: {error}</div>;
return (
<div className="min-h-screen bg-[#32324d] py-8 text-white">
<div className="max-w-4xl mx-auto">
<h1 className="text-3xl font-bold mb-8 text-center">Summarized PDFs</h1>
<Link
href="/"
className="bg-[#4945ff] text-white px-4 py-2 rounded mb-4 inline-block"
>
Back to Upload
</Link>
{summaries.length === 0 ? (
<p>No summaries available.</p>
) : (
<table className="min-w-full bg-gray-800 border-collapse">
<thead>
<tr>
<th className="border border-gray-600 px-4 py-2">ID</th>
<th className="border border-gray-600 px-4 py-2">Title</th>
<th className="border border-gray-600 px-4 py-2">Short Text</th>
<th className="border border-gray-600 px-4 py-2">View</th>
</tr>
</thead>
<tbody>
{summaries.map((summary) => (
<tr key={summary.id} className="hover:bg-gray-700">
<td className="border border-gray-600 px-4 py-2">
{summary.id}
</td>
<td className="border border-gray-600 px-4 py-2">
{summary.Title}
</td>
<td className="border border-gray-600 px-4 py-2">
<ReactMarkdown className="prose prose-invert max-w-none">
{typeof summary.Summary === "string"
? summary.Summary.slice(0, 100) + "..."
: "Summary not available"}
</ReactMarkdown>
</td>
<td className="border border-gray-600 px-4 py-2">
<Link
href={`/summaries/${summary.id}`}
className="bg-[#4945ff] text-white px-4 py-2 rounded"
>
View
</Link>
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
</div>
);
}
In the code above, we created a React component that displays a list of summarized PDFs fetched from a Strapi backend. It renders a table with summary details, including an ID, title, and a shortened version of the summary content.
The href={/summaries/${summary.id}}
in the "View" button dynamically generates a URL based on the id of each summary. This allows you to click the "View" button and navigate to a page to view the specific summarized PDF for that id
.
If you click the view summarized button, it should redirect you to this page:
To manage dynamic routing for each summary based on its id
, you must create a folder named [id]
and two files inside the app/summaries
directory. The first to create is the page.js
. After creating it, add the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import { Suspense } from "react";
import Link from "next/link";
import SummaryContent from "./SummaryContent";
export default function SummaryPage({ params }) {
return (
<div className="min-h-screen bg-[#32324d] py-8 text-white">
<div className="max-w-4xl mx-auto px-4">
<Link
href="/summaries"
className="bg-[#4945ff] text-white px-4 py-2 rounded mb-4 inline-block"
>
Back to Summaries
</Link>
<Suspense fallback={<div>Loading...</div>}>
<SummaryContent id={params.id} />
</Suspense>
</div>
</div>
);
}
In the code above, we created a component responsible for displaying the detailed view of a summarized PDF based on its id
.
The Suspense
component displays a fallback loading message (<div>Loading...</div>)
while SummaryContent
is fetched. The SummaryContent
component( which we'll create shortly) is passed the id
from params.id
, corresponding to the specific summary being viewed.
Now, let's create the second page. Still, inside the [id]
folder, create a file called SummaryContent.js
and add the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"use client";
import { useState, useEffect } from "react";
import ReactMarkdown from "react-markdown";
export default function SummaryContent({ id }) {
const [summary, setSummary] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchSummary = async () => {
try {
const response = await fetch(
`http://localhost:1337/api/summarized-pdfs?filters[id][$eq]=${id}`,
);
if (!response.ok) {
throw new Error("Failed to fetch summary");
}
const data = await response.json();
if (data.data && data.data.length > 0) {
setSummary(data.data[0]);
} else {
throw new Error("Summary not found");
}
setIsLoading(false);
} catch (error) {
console.error("Fetch error:", error);
setError(error.message);
setIsLoading(false);
}
};
fetchSummary();
}, [id]);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
if (!summary) return <div>Summary not found</div>;
return (
<>
<h1 className="text-3xl font-bold mb-4">{summary.Title}</h1>
<div className="bg-gray-800 p-6 rounded-lg">
<ReactMarkdown className="prose prose-invert max-w-none">
{summary.Summary}
</ReactMarkdown>
</div>
</>
);
}
The SummaryContent
component fetches and displays a specific summarized PDF based on the provided id
.
Now let’s check the result in the browser to see if it works:
It works! Our PDF summarizer is complete! Here’s the link to the code on GitHub.
That’s How to Create a PDF Summarizer.
In this tutorial, we learned how to build a PDF summarizer in Next.js using Pdf.js, Gemini, and Strapi. You can also choose to enhance yours by adding other features too. There are quite a lot of things you can build using AI tools and Strapi.
Love to see what you can build. Please share if you found this tutorial helpful.
I'm a web developer and writer. I love to share my experiences and things I've learned through writing.