package sample; import jaxcent.*; import java.io.*; import com.lowagie.text.*; import com.lowagie.text.pdf.*; /** * Jaxcent PDF creation sample using the iText Java PDF-building API. * Note that "session" must be enabled for the page, because the Jaxcent URL * stores the PDF bytes in the session. */ public class PdfSample extends jaxcent.JaxcentPage { HtmlButton build = new HtmlButton( this, "build" ) { public void onClick( java.util.Map data ) { onBuild( data ); } }; HtmlInlineFrame ifr = null; // If displaying using IFRAME public void onBuild( java.util.Map data ) { try { // Retrieve name and "new window" values. String name = (String) data.get( "name" ); if ( name == null || name.trim().equals( "" )) name = "Unknown Visitor"; String show = (String) data.get( "show" ); // build PDF document. byte[] pdfBytes = buildPdfDocument( name ); // Make a Jaxcent URL that stores the bytes in the session, and returns them. String url = makeContentURL( "application/pdf", pdfBytes, "sample.pdf" ); if ( ifr != null ) { // If there was an earlier inline display, remove it. ifr.deleteElement(); } // If inline display, create an HTML IFrame and display in that. if ( show.equals( "inline" )) { ifr = new HtmlInlineFrame( this, SearchType.createNew, "IFRAME" ); ifr.setHeight( "300px" ); ifr.setWidth( "90%" ); ifr.setScrolling( "auto" ); ifr.setSrc( url ); // Note: For Internet Explorer, src must be set before iframe is inserted in document. ifr.insertAtEnd(); } else if ( show.equals( "window" )) { navigate( url ); } else { // Insert a Para in the document containing the link to the new document. HtmlPara p = new HtmlPara( this, SearchType.createNew, "P", "" ); p.insertAtEnd(); HtmlAnchor a = new HtmlAnchor( this, SearchType.createNew, "A", "Click to view PDF Document" ); a.insertAtBeginning( p ); a.setHref( url ); // Make the link point to the Jaxcent URL for the PDF if ( show.equals( "linknew" )) a.setTarget( "_blank" ); } } catch (Exception ex) { ex.printStackTrace(); } } // Build PDF document, return bytes. byte[] buildPdfDocument( String visitorName ) throws DocumentException { // Build PDF document, and retrieve its byte content ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); Document doc = new Document(); PdfWriter docWriter = PdfWriter.getInstance(doc, baosPDF); doc.open(); doc.add( new Paragraph( "Dear " + visitorName )); doc.add( new Paragraph( "This sample PDF was created for you at " + new java.util.Date())); doc.add( new Paragraph( "The technique demonstrated in this sample can be used for PDF and other types of generated documentation." )); doc.close(); docWriter.close(); return baosPDF.toByteArray(); } }