Tuesday, October 29, 2013

writePDFToResponse

 private void writePDFToResponse(HttpServletResponse response, PdfPTable pdfTable, PdfPTable resTable, String fileName) throws IOException, DocumentException {
        Document document = new Document(PageSize.A4.rotate());
        document.setPageSize(PageSize.A4);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfWriter.getInstance(document, baos);
        document.open();
        document.add(pdfTable);
        document.add(resTable);
        document.close();

        response.setCharacterEncoding("UTF-8");
        String content = new String("application/pdf".getBytes(),"UTF-8");
        response.setContentType(content);
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control","must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Pragma", "public");
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".pdf");
        response.setContentLength(baos.size());

        System.out.print(response.getCharacterEncoding());

        ServletOutputStream out = response.getOutputStream();
        baos.writeTo(out);
        out.flush();
    }

No comments:

Post a Comment