4:40 pm - Saturday September 23, 2017

Pdf viewer using servlet

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

BACK

Pdf viewer using servlet

index.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="hai">
		<button type="submit">Click to View PDF File</button>
	</form>
</body>
</html>

PdfServlet.java


import javax.servlet.*;
import javax.servlet.http.*;

import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;

import java.io.*;
import java.util.*;

public class pdfServlet extends HttpServlet {

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("application/pdf"); // Code 1
		Document document = new Document();
		try {
			PdfWriter.getInstance(document, response.getOutputStream()); // Code
																			// 2
			document.open();

			document.add(new Paragraph("Hello world............"));
			document.close();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}

}

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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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">
<display-name>pdfviewer</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>pdfServlet</display-name>
<servlet-name>pdfServlet</servlet-name>
<servlet-class>pdfServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>pdfServlet</servlet-name>
<url-pattern>/hai</url-pattern>
</servlet-mapping>
</web-app>

output screenshot

         Download sourcecode

BACK

Filed in: Z-A Servlet codes

Comments are closed.