Facing new challenges everyday

Gerando PDFs de forma simples usando JSF

October 30th, 2006

Esse trecho de código abaixo permite usar uma view customizada do JSF que permite criar PDFs convertendo código XHTML para XML-FO:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public class PDFViewRoot extends UIViewRoot {
   
  public final static String COMPONENTY_TYPE = "studioweb.PFDView";
   
  public PDFViewRoot() {
 
  }
   
  public void encodeAll(FacesContext context) throws IOException
  {
       
    UIViewRoot root = context.getViewRoot();
    String renderKitId = root.getRenderKitId();
    RenderKitFactory renderFactory =
                (RenderKitFactory)FactoryFinder
                .getFactory(FactoryFinder.RENDER_KIT_FACTORY);
       
    RenderKit renderKit = renderFactory.
       getRenderKit(context, renderKitId);
    StringWriter stringWriter = new StringWriter();
    ResponseWriter responseWriter =
                renderKit.createResponseWriter(stringWriter,
                "text/html", "UTF-8");
       
    context.setResponseWriter(responseWriter);
    super.encodeAll(context);
    responseWriter.flush();
       
    String contentType = (String) getAttributes()
      .get("contentType");
   
    String filename = (String) getAttributes()
      .get("xsl");
       
    HttpServletResponse response = (HttpServletResponse)
      context.getExternalContext().getResponse();
       
    try {
      ByteArrayOutputStream out = convertFaceletsResponse(
         stringWriter, filename);
           
      response.setContentLength(out.size());
      response.setHeader("Pragma", "No-cache");
      response.setDateHeader("Expires", 0);
      response.setHeader("Cache-Control", "no-cache");
      response.setContentType(contentType);
      response.setHeader("Content-Disposition",
         "filename=\"listino.pdf\"");
           
      response.getOutputStream().write(out.toByteArray());
      response.getOutputStream().flush();
      out.close();
    } catch(Exception ex) {
      throw new ServiceException(ex);
    }
  }
}

Esse código é de autoria de um colega da Itália.

DZoneGoogle BookmarksFacebookEvernoteLinkedInDeliciousShare

1 Comment »

  1. Luiz says

    Olá Rogério,

    Sempre achei que isso seria possível, mas nunca parei para botar a mão na massa. Fui testar mas falta o método convertFaceletsResponse. O que ele faz?

    November 14th, 2006 | #

Leave a comment

:mrgreen: :neutral: :twisted: :shock: :smile: :???: :cool: :evil: :grin: :oops: :razz: :roll: :wink: :cry: :eek: :lol: :mad: :sad:
*

RSS feed for these comments. | TrackBack URI

Visitors Around the World

Polls

How Is My Site?

View Results

Loading ... Loading ...

Categories

Meta

Links

hosted by easy2use.net