Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java EE (J2EE) и Spring > открыть pdf в браузере


Автор: alder 12.5.2006, 11:42
создаю с помощью fop pdf, результат сохраняю на диске, а как можно сделать следующее: после того как сформировал pdf открыть его (не сохраняя его на диск) в браузере? 

Автор: w1nd 12.5.2006, 22:03
Легко - только вам понадобится web-сервер. 

Автор: onsh76 14.5.2006, 02:04
Впихни байтстрим pdf файла в ServletOutput :

Код

...
ByteArrayOutputStream pdfStream = null;
            try{
                // get pdf file as byte stream
                pdfStream = getOutputSream();
                response.setContentType("application/pdf");
                response.setCharacterEncoding("UTF-8");
                response.setContentLength(pdfStream.size());
                ServletOutputStream out = response.getOutputStream();
                pdfStream.writeTo(out);
                out.flush(); 
            }catch(Exception e){
                logger.error("Failed to stream pdf report on client. Caused by: ", e);
            }finally{
                try{
                   if (pdfStream != null){
                       pdfStream.close();    
                   }
                }catch(IOException ioe){
                    logger.error("Failed to close pdf reporting stream. Caused by: ", ioe);
                }
            }
...

Выдрал вот из того, что применял в проекте. Метод getOutputSream() возвращает тебе пдф файл ввиде байтстрима... Если чего-то не ясно - спрашивай... 

Автор: alder 15.5.2006, 09:44
имеется веб приложение (Spring + Tomcat)
почитал предыдущий пост и сделал следующее 

Код

public class XLogReport extends AbstractController {


    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {

        ModelAndView mav = new ModelAndView();
        final XProjectData prjData = new XProjectData();
        final Vector logCollection = new Vector();
        final String directory;

        directory = request.getParameter("dir");
        prjData.setDateFrom(request.getParameter("datefrom"));
        prjData.setDateTo(request.getParameter("dateto"));
        prjData.setProjectName(request.getParameter("projectName"));

        LogReportEntry[] entryList = ServiceAccess.getLogReportEntry(prjData.getProjectName(), directory, prjData.getDateTo(), prjData.getDateFrom());

        Document doc = DomXml.createXmlDocument(entryList);

        ByteArrayOutputStream pdfStream = null;
            try{
                // get pdf file as byte stream
                File xslt = new File("log2fo.xsl");
                pdfStream = XML2PDF(doc, xslt);
                response.setContentType("application/pdf");
                response.setCharacterEncoding("UTF-8");
                response.setContentLength(pdfStream.size());
                ServletOutputStream out = response.getOutputStream();
                pdfStream.writeTo(out);
                out.flush();
            }catch(Exception e){
                logger.error("Failed to stream pdf report on client. Caused by: ", e);
            }finally{
                try{
                   if (pdfStream != null){
                       pdfStream.close();
                   }
                }catch(IOException ioe){
                    logger.error("Failed to close pdf reporting stream. Caused by: ", ioe);
                }
            }

        return mav;
    }

    public ByteArrayOutputStream XML2PDF(Document xml, File xslt)
                throws IOException, FOPException, TransformerException {
        //Construct driver
        Driver driver = new Driver();

        //Setup logger
        Logger logger = new ConsoleLogger(ConsoleLogger.LEVEL_INFO);
        driver.setLogger(logger);
        MessageHandler.setScreenLogger(logger);

        //Setup Renderer (output format)
        driver.setRenderer(Driver.RENDER_PDF);

        //Setup output
        //OutputStream out = new java.io.FileOutputStream(pdf);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            driver.setOutputStream(out);

            //Setup XSLT
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer(new StreamSource(xslt));

            //Setup input for XSLT transformation
            Source src = new StreamSource(new StringReader(xml.asXML()));

            //Resulting SAX events (the generated FO) must be piped through to FOP
            Result res = new SAXResult(driver.getContentHandler());

            //Start XSLT transformation and FOP processing
            transformer.transform(src, res);
        } finally {
            out.close();
        }

        return out;
    }
}


компиляется, запускаю... но страница пустая.... может не правильно путь в к файл xsl указываю 
Код

File xslt = new File("log2fo.xsl");

как правильно указать путь к этому файлу который лежит на Tomcat'e???

или ошибка не в этом? 

Автор: tux 15.5.2006, 09:52
А что в логе Томката говорится? Раз на странице пусто, значит должно быть какое-то исключение.  

Автор: alder 15.5.2006, 11:14
в логе томката ничего такого подозрительного нету

Код

2006-05-15 15:12:55 StandardContext[/balancer]org.apache.webapp.balancer.BalancerFilter: init(): ruleChain: [org.apache.webapp.balancer.RuleChain: [org.apache.webapp.balancer.rules.URLStringMatchRule: Target string: News / Redirect URL: http://www.cnn.com], [org.apache.webapp.balancer.rules.RequestParameterRule: Target param name: paramName / Target param value: paramValue / Redirect URL: http://www.yahoo.com], [org.apache.webapp.balancer.rules.AcceptEverythingRule: Redirect URL: http://jakarta.apache.org]]
2006-05-15 15:12:55 StandardContext[/jsp-examples]ContextListener: contextInitialized()
2006-05-15 15:12:55 StandardContext[/jsp-examples]SessionListener: contextInitialized()
2006-05-15 15:12:55 StandardContext[/servlets-examples]ContextListener: contextInitialized()
2006-05-15 15:12:55 StandardContext[/servlets-examples]SessionListener: contextInitialized()
2006-05-15 15:12:58 StandardContext[/calc]Loading WebApplicationContext for Spring FrameworkServlet 'springServlet'
2006-05-15 15:12:59 StandardContext[/scm2]Loading WebApplicationContext for Spring FrameworkServlet 'springServlet'
2006-05-15 15:13:37 StandardContext[/jsp-examples]ContextListener: attributeReplaced('org.apache.catalina.WELCOME_FILES', '[Ljava.lang.String;@18ff27')
2006-05-15 15:13:37 StandardContext[/jsp-examples]ContextListener: attributeReplaced('org.apache.catalina.WELCOME_FILES', '[Ljava.lang.String;@1177115')
2006-05-15 15:13:37 StandardContext[/jsp-examples]ContextListener: attributeReplaced('org.apache.catalina.WELCOME_FILES', '[Ljava.lang.String;@150a0')
2006-05-15 15:13:37 StandardContext[/jsp-examples]SessionListener: contextDestroyed()
2006-05-15 15:13:37 StandardContext[/jsp-examples]ContextListener: contextDestroyed()
2006-05-15 15:13:38 StandardContext[/calc]Closing WebApplicationContext of Spring FrameworkServlet 'springServlet'
2006-05-15 15:13:38 StandardContext[/servlets-examples]ContextListener: attributeReplaced('org.apache.catalina.WELCOME_FILES', '[Ljava.lang.String;@1aca5e2')
2006-05-15 15:13:38 StandardContext[/servlets-examples]ContextListener: attributeReplaced('org.apache.catalina.WELCOME_FILES', '[Ljava.lang.String;@1be9a50')
2006-05-15 15:13:38 StandardContext[/servlets-examples]ContextListener: attributeReplaced('org.apache.catalina.WELCOME_FILES', '[Ljava.lang.String;@8518d4')
2006-05-15 15:13:38 StandardContext[/servlets-examples]SessionListener: contextDestroyed()
2006-05-15 15:13:38 StandardContext[/servlets-examples]ContextListener: contextDestroyed()
2006-05-15 15:13:38 StandardContext[/scm2]Closing WebApplicationContext of Spring FrameworkServlet 'springServlet'
 

Автор: alder 15.5.2006, 11:35
все разобрался, спасибо за помощь, ошибка была с путями, не находил файл log2fo.xsl 

Автор: alder 16.5.2006, 08:47
еще вопрос появился по открытию pdf. Я пользуюсь firefox и в нем все замечательно pdf замечательно отображается, и решил проверить как будет работать в експлорере открываю, он мне предлагает нексколько вариантов открыть, сохранить... если выбираю открыть то он мне открывает pdf как html и естественно там всякая кракозябра, если выбираю соххранить то он мне его сохраняет как html.... ак можно победить эту проблему в эксплорере?

Добавлено @ 08:58 
исправил... оказывалось что надо было открывать эту страницу не как html а как pdf и тогда эксплорер все отобразит 

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)