How do I serve up a PDF from a servlet?
Author: Deron Eriksson
Description: This tutorial describes how to serve up a PDF from a servlet.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0) || Tomcat 5.5.20


Page:    1 2 >

It's possible to have a servletW serve up PDF content by specifying the content type of the servlet response to be the 'application/pdf' MIME type via response.setContentType("application/pdf"). This tutorial will demonstrate this using a project with the following structure.

'test' project

The TestServlet class is mapped to /test. When the TestServlet is hit by a browser request, it locates the pdf-test.pdf file in the web directory. It sets the response content type to be 'application/pdf', specifies that the response is an attachment, and sets the response content length. Following that, it writes the contents of the PDF file to the response output stream.

TestServlet.java

package com.cakes;

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

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

public class TestServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		performTask(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		performTask(request, response);
	}

	private void performTask(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {

		String pdfFileName = "pdf-test.pdf";
		String contextPath = getServletContext().getRealPath(File.separator);
		File pdfFile = new File(contextPath + pdfFileName);

		response.setContentType("application/pdf");
		response.addHeader("Content-Disposition", "attachment; filename=" + pdfFileName);
		response.setContentLength((int) pdfFile.length());

		FileInputStream fileInputStream = new FileInputStream(pdfFile);
		OutputStream responseOutputStream = response.getOutputStream();
		int bytes;
		while ((bytes = fileInputStream.read()) != -1) {
			responseOutputStream.write(bytes);
		}

	}

}

(Continued on page 2)

Page:    1 2 >