1 16 package org.springframework.web.servlet.view.document; 17 18 import java.io.ByteArrayOutputStream ; 19 import java.util.HashMap ; 20 import java.util.Map ; 21 22 import javax.servlet.http.HttpServletRequest ; 23 import javax.servlet.http.HttpServletResponse ; 24 25 import com.lowagie.text.Document; 26 import com.lowagie.text.PageSize; 27 import com.lowagie.text.Paragraph; 28 import com.lowagie.text.pdf.PdfWriter; 29 import junit.framework.TestCase; 30 31 import org.springframework.mock.web.MockHttpServletRequest; 32 import org.springframework.mock.web.MockHttpServletResponse; 33 34 38 public class PdfViewTests extends TestCase { 39 40 public void testPdf() throws Exception { 41 final String text = "this should be in the PDF"; 42 43 MockHttpServletRequest request = new MockHttpServletRequest(); 44 MockHttpServletResponse response = new MockHttpServletResponse(); 45 46 AbstractPdfView pdfView = new AbstractPdfView() { 47 protected void buildPdfDocument(Map model, Document document, PdfWriter writer, 48 HttpServletRequest request, HttpServletResponse response) throws Exception { 49 document.add(new Paragraph(text)); 50 } 51 }; 52 53 pdfView.render(new HashMap (), request, response); 54 byte[] pdfContent = response.getContentAsByteArray(); 55 56 assertEquals("correct response content type", "application/pdf", response.getContentType()); 57 assertEquals("correct response content length", pdfContent.length, response.getContentLength()); 58 59 Document document = new Document(PageSize.A4); 61 ByteArrayOutputStream baos = new ByteArrayOutputStream (); 62 PdfWriter writer = PdfWriter.getInstance(document, baos); 63 writer.setViewerPreferences(PdfWriter.AllowPrinting | PdfWriter.PageLayoutSinglePage); 64 document.open(); 65 document.add(new Paragraph(text)); 66 document.close(); 67 byte[] baosContent = baos.toByteArray(); 68 69 assertEquals("correct size", pdfContent.length, baosContent.length); 70 71 int diffCount = 0; 72 for (int i = 0; i < pdfContent.length; i++) { 73 if (pdfContent[i] != baosContent[i]) { 74 diffCount++; 75 } 76 } 77 78 assertTrue("difference only in encryption", diffCount < 70); 79 } 80 81 } 82 | Popular Tags |