In this tutorial, we are going to learn how to create Angular application that previews PDF files served by Spring Boot server.
2. Project architecture
The architecture presents as follows:
We can distinguish two main layers: the backend and frontend. On the frontend side, we have an Angular application that is responsible for presenting PDF files downloaded from the Spring Boot application server (backend side).
3. Backend side
3.1. Project structure
Let's check the Spring Boot application project structure:
Project contains the following files:
Application - main Spring Boot starter class,
PDFController - Spring Rest Controller used for downloading PDF files,
application.properties - Spring Boot configuration file.
3.2. Rest Controller
The PDFController class is responsible for downloading PDF files selected by the user. Files are located in the folder whose path is taken from the configuration parameter: pdf.path.
This Rest API returns a file content or HTTP 404 code when a file does not exist in the filesystem.
3.3. Spring Boot application class
The main Spring Boot class annotated with @SpringBootApplication is simple, it contains the only main method that will start the server instance.
3.4. Spring Boot configuration
The application.properties has only one entry with a path to a folder that contains PDF files:
4. Frontend side
4.1. Project structure
The angular application was created using ng cli:
To create an Angular project without tests we used:
The angular application contains the main app component that will be responsible for previewing downloaded PDF files. The structure of the application is as follows:
4.2. The package.json file
In the package.json file besides the Angular 11 common libraries, we also have ng2-pdf-viewer and a module responsible for previewing PDF files in web projects.
To add the ng2-pdf-viewer module the following command was used:
4.3. Angular application component
The AppComponent is responsible for presenting selected PDF file and handling navigation through PDF pages using next/previous buttons.
4.4. Application component HTML
The ApplicationComponent will use the following HTML template:
The pdf-viewer is responsible for presenting a PDF file. This module could also render the PDF, so you could select text from the file on the HTML website.
5. Demo
The application presents the following functionality:
6. Conclusion
In this article, we presented a sample Angular application to preview PDF files served by a Spring Boot application server. We used the ng2-pdf-viewer library that is perfect for this and comes with many features like for example rendering PDF files.
As usual code used in this article is allowed for download from our GitHub repository.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}