How to Download PDF File in Servlet

Download PDF File in Servlet

In this example, we will show you how to download PDF file in servlet. The example application was tested with Apache Tomcat Web Server and output has been shared in the same post.

Project Structure

Download PDF File in Servlet

Servlet Class (Downloader.java)

package com.dineshkrish.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @author Dinesh Krishnan
 * 
 */

public class Downloader extends HttpServlet {

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		final String filepath = "C:\\File.pdf";
		
		ServletOutputStream outputStream = response.getOutputStream();
		
		// setting http header information
		response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "inline; filename=java_book.pdf");// download file name
		
        // defining File object
        File file = new File(filepath);
		
        // defining InputStream object
		FileInputStream inputStream = new FileInputStream(file);
		
		int data = inputStream.read();
		
		while(data != -1) {
			
			outputStream.write(data);
			data = inputStream.read();
		}
	
		outputStream.close();
		inputStream.close();
			
	}

}

Configuration File (web.xml)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	
	<servlet>
		<servlet-name>Downloader</servlet-name>
		<servlet-class>com.dineshkrish.servlet.Downloader</servlet-class>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>Downloader</servlet-name>
		<url-pattern>/download</url-pattern>
	</servlet-mapping>
	
</web-app>

Output

When you call the /download url after the context root, It will produce the following output in the web browser.

Download PDF File in Servlet

References

1. Java EE HttpServletRequest Interface
2. Java EE HttpServletResponse Interface
3. Java EE ServletException Class
4. Java IOException Class
5. Java EE ServletOutputStream Class
6. Java File Class
7. Java FileOutputStream Class