1 16 17 package org.springframework.web.servlet.view.document; 18 19 import java.io.ByteArrayOutputStream ; 20 import java.io.OutputStream ; 21 import java.util.Map ; 22 23 import javax.servlet.ServletOutputStream ; 24 import javax.servlet.http.HttpServletRequest ; 25 import javax.servlet.http.HttpServletResponse ; 26 27 import com.lowagie.text.Document; 28 import com.lowagie.text.DocumentException; 29 import com.lowagie.text.PageSize; 30 import com.lowagie.text.pdf.PdfWriter; 31 32 import org.springframework.web.servlet.view.AbstractView; 33 34 47 public abstract class AbstractPdfView extends AbstractView { 48 49 private static final int OUTPUT_BYTE_ARRAY_INITIAL_SIZE = 4096; 50 51 52 57 public AbstractPdfView() { 58 setContentType("application/pdf"); 59 } 60 61 62 protected final void renderMergedOutputModel( 63 Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { 64 65 68 73 76 ByteArrayOutputStream baos = new ByteArrayOutputStream (OUTPUT_BYTE_ARRAY_INITIAL_SIZE); 78 Document document = newDocument(); 79 PdfWriter writer = newWriter(document, baos); 80 81 prepareWriter(model, writer, request); 83 buildPdfMetadata(model, document, request); 84 85 document.open(); 87 buildPdfDocument(model, document, writer, request, response); 88 document.close(); 89 90 response.setContentType(getContentType()); 92 response.setContentLength(baos.size()); 93 94 ServletOutputStream out = response.getOutputStream(); 96 baos.writeTo(out); 97 out.flush(); 98 } 99 100 107 protected Document newDocument() { 108 return new Document(PageSize.A4); 109 } 110 111 118 protected PdfWriter newWriter(Document document, OutputStream os) throws DocumentException { 119 return PdfWriter.getInstance(document, os); 120 } 121 122 137 protected void prepareWriter(Map model, PdfWriter writer, HttpServletRequest request) 138 throws DocumentException { 139 140 writer.setViewerPreferences(getViewerPreferences()); 141 } 142 143 153 protected int getViewerPreferences() { 154 return PdfWriter.AllowPrinting | PdfWriter.PageLayoutSinglePage; 155 } 156 157 175 protected void buildPdfMetadata(Map model, Document document, HttpServletRequest request) { 176 } 177 178 194 protected abstract void buildPdfDocument( 195 Map model, Document document, PdfWriter writer, 196 HttpServletRequest request, HttpServletResponse response) 197 throws Exception ; 198 199 } 200 | Popular Tags |