I've searched a lot but could not solve this problem. I am generating PDF files with iText. If i use FileOutputStream everything is fine but when i try to use ServletOutputStream the images does not appear in PDF files.
When I open the PDF file with text editor, i saw that there "???" so much. That means something is shaving the bytes. It is like trying to use binary files with JSP. But i am using JSF, Tomcat 6.0, Spring 3.0 and Richfaces.
Here is the code that generates PDF with ServletOutputStream and causes problem
public static void saveChartToPDF(JFreeChart chart, String fileName, HttpServletResponse response) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); document.addCreationDate(); document.setPageSize(PageSize.A4.rotate()); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(300, 300); Graphics2D g2 = tp.createGraphics(300, 300, new DefaultFontMapper()); Rectangle2D r2D = new Rectangle2D.Double(0, 0, 300, 300); chart.draw(g2, r2D, null); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close(); response.setContentType("application/pdf"); 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()); ServletOutputStream out = response.getOutputStream(); baos.writeTo(out); out.flush();
And here is the code works fine with FileOutputStream()
public static void saveChartToPDF(JFreeChart chart, String fileName, HttpServletResponse response) throws Exception { Document document = new Document(); document.addCreationDate(); document.setPageSize(PageSize.A4.rotate()); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("c:/test1.pdf")); document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(300, 300); Graphics2D g2 = tp.createGraphics(300, 300, new DefaultFontMapper()); Rectangle2D r2D = new Rectangle2D.Double(0, 0, 300, 300); chart.draw(g2, r2D, null); g2.dispose(); cb.addTemplate(tp, 0, 0); document.close();
I could not find why the bytes are being shaved.
Thanks a lot for your help,