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
| package com.x.test.web;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.PageSize;
import com.lowagie.text.html.SAXmyHtmlHandler;
import com.lowagie.text.pdf.PdfWriter;
/**
* <b>.</b><br>
* .
* @author Nicolas Martineau
* @since 5 juil. 2004
*/
public class Imprime extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
/* ... do stuff in Servlet */
//PrintWriter out = response.getWriter();
response.setContentType("application/pdf");
BufferedHttpResponseWrapper wrapper = new BufferedHttpResponseWrapper(response);
ServletContext context = request.getSession().getServletContext();
String url = response.encodeRedirectURL("/MiseEnPage.jsp");
//System.out.println("code html:" + response.getOutputStream());
RequestDispatcher dispatcher = context.getRequestDispatcher(url);
/* must use include. With forward the RequestDispatcher seems to hold an
internal state
which prevents to do a forward after this to return to the webclient
*/
dispatcher.include(request, wrapper);
Document document = new Document(PageSize.A4, 80, 50, 30, 65);
try {
//PdfWriter.getInstance(document, new FileOutputStream("f:/test.pdf"));
PdfWriter.getInstance(document, response.getOutputStream());
// step 3: we create a parser and set the document handler
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
// step 4: we parse the document
parser.parse(wrapper.getInputStream(), new SAXmyHtmlHandler(document));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} |
Partager