Table of Contents (PDF creation, Printing existing PDF and Report generation -  using Smart JPrint )

Printing & Viewing an existing PDF document

PDF to PostScript, TIFF, JPEG, PNG Conversion

PDF Viewer Customization as Frame, Dialog, and plugin Component.

Printing & PDF generation

Programming tips

PDF generation and printing examples


 

Which classes to use?

Here is the map of the important classes with name and its functionality.

  • AtPdfStreamPrinter - Use this class for printing an existing PDF document by specifying a file from local file system, web location, and manipulated bytes from your program.
  • AtPDF2PostScriptPrinter - This class converts an existing PDF document into a PostScript content. You have the option to either save PDF as a PostScript file of get an InputStream of the PostScript content.
  • AtPdfConverter - Converts your existing PDF document to other file formats such as TIFF, JPEG, PNG and more.
  • AtPdfPreviewFrame - Loading and viewing an existing PDF document from local file system, web location, and PDF bytes in memory. The PDF viewer window allows you to print, save a copy, conver pages to PNG and JPEG, load a local file, load a file from HTTP url, view using thumbnails, zoom in and out, page rotation, and others.
  • AtPdfPreviewDialog - Shows a PDF viewer window as a dialog window instead of a frame window.
  • AtPdfViewPane - The basic PDF view pane component that can be used as a plugin Swing component to embed into your GUI application. The other two window classes actually embeding this Swing component into a window for showing a dialog and a frame.
  • AtPdfPrinter - generates PDF files from your J2EE output as using texts (RTF styled texts), icons, 2D Graphics; and the contents of the swing components such as JTable, JTextArea, JTextPane, JEditorPane etc.
  • AtBook - holds texts, icons, and 2D graphics before generating PDF file using the AtPdfPrinter's print() methods, or printing the output to a printer. Use its append() method to accumulate the texts, icons, and 2D graphics, table data (TableModel or JTable), Styled/Plain text from a Swing JTextComponent and more. Pass this object to a AtPdfPrinter for PDF generation or pass it to a AtGenericPrinter for printing to a printer.
  • AtGenericPrinter - is used for printing Java (J2EE and Swing) program output to a printer. It takes a AtBook object as the input.
  • AtTablePrinter - Prints Java JTable swing component to a printer.
  • AtDocumentPrinter - Prints Swing components such as JTextField, JTextArea, JEditorPane, JTextPane or other kind of custom JTextComponent content to a printer.
  • AtImageFactory - Produce JPEG, PNG output for each pages.
  • AtImagePrinter - Produce output as TIFF document output.
  • AtJava2PostScriptPrinter - Convert the report pages generated from the SmartJPrint report generation classes to other file formats such as TIFF, JPEG, PNG and more.
  • AtComponentPrinter - Use this class to produce output from virtually any java.awt.Component visible in a GUI. For special swing components such as JTextArea, JTextPane, JTextField, JTable use other printer classes most suitable for them.
  • AtPreviewFrame - Use this class for previewing the printable pages. You can get the pages as Pageable and then pass them as argument to this class for an explicit opening of a preview window. However, all the printing classes above has preview() methods that implicitly creates the report pages and then shows them into the preview widnow. Therefore, it is not necessary for you to open a preview window of your own.
  • Back to Top


    How do I test Smart JPrint power?

  • Try some of our online applets as tokens of SmartJPrint capabilities. If you do not have good connection or have Java plugin problem download it from main page and run its batch files (.bat and .sh) locally.
  • Existing PDF: It is your ultimate source for existing PDF document printing (silently and with user intervention) and viewing from local file sytem, web location and PDF content in byte array from your program memory.
  • Reporting tool: Ultimate Java report generation tool from any kind of Java application
  • PDF generation: Smart JPrint is not only prints but generates PDF document.
  • Convenient: When using Smart JPrint APIs, you have to write only 2 lines of code to Print and/or generate PDF. Look at the example source codes at the online demo page to know how simple it is to use JPrint.
  •  

    Back to Top


    Can I preview pages before PDF output or printing?

    Yes, you can always preview the output using the smart Jprint preview window. This preview window allow the user to see the pages before they can be printed or PDF generated from the preview window itself. All or selected pages from the preview window can be printed or sent for PDF generation.

     

    Back to Top


    Can I automatically print the output to a printer or Save As PDF?

    Yes, your Java program can automatically print your Java program output to a printer without showing any kind of printer selection, page setup window.

    When printing: Use the different print() methods from the appropriate printer class and pass false as the argument for avoid showing printer selection and page setup dialogs. In such case, Smart JPrint takes the first one from the discovered printers and sends the output to that printer.

    When PDF generating: Use the AtPdfPrinter class and pass a OutputStream to write the Java program output as PDF files. Also pass false for the show printer setup and page setup arguments.

     

    Back to Top


    Can I combine pages (object of Printable) from various sources for printing or PDF generate as a single document?

    Yes.
    This feature allows you to create Printable pages from various sources and put them together as a collection of pages (Pageable) that can be PDF generated as a single document, printed directly to a printer. For example, if you have a JTextArea, a JTable, and some pages from your Java/J2EE program, you can generate a PDF document by combining pages from all of these together. You can add custom pages from virtually any other sources in your Java program to the Smart JPrint PDF printer class to generate PDF as a single document.

    We have lots of example source code in the downloaded archive that will help you trying as a demo and quickly develop your own application following those samples. You can also find lots of online demo and example programs in our website.

    Back to Top


    Printing an existing PDF document

    Use must use the com.activetree.pdfprint.AtPdfStreamPrinter class for silently printing a PDF document from your server as well as GUI programs.

    Use this class for printing a PDF file either from local file system or from a web location. For those already holds the binary PDF content as byte[] array in memory, also got the opportunity to pass the binary PDF content directly into its APIs for printing silently to a printer or to the selected printer using the printer selection dialog.

    Back to Top


    Silent print existing PDF files from local file system

    You can construct a File object using the PDF file that is located in the local file system or file from a network drive. For example, if you have a Windows file in the directory called "c:\>documents\pdfs\sample.pdf" then use the following code segment for silent printing it to the default printer connected to the computer.

    PdfSilentPrintFromLocalFile.java

     import com.activetree.pdfprint.AtPdfStreamPrinter;
     import com.activetree.common.SmartJPrint;
    
     import javax.print.PrintService;
     import javax.print.PrintServiceLookup;
     import java.awt.print.PageFormat;
     import java.awt.print.Paper;
    
     public class PdfSilentPrintFromLocalFile {
       public static void main(String[] args) {
         String pdfFile = null;
         if (args != null && args.length >= 2) {
           SmartJPrint.setLicenseKey(args[0]);
           pdfFile = args[1];
         }
         else {
           System.out.println("Usage: java " + PdfSilentPrintFromLocalFile.class.getName() + " [licenseKey]  [pdfFile]");
           System.exit(0);
         }
         AtPdfStreamPrinter pdfPrinter = new AtPdfStreamPrinter();
         //Here you decide which Printer to print by iterating through the
         //appropriate PrintService[] received from PrinterJob.lookupPrintServices()
         //for demo we are using the default printer using the following:
         PrintService defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();
         //Assuming your default printer supports LETTER quality paper (612x792) paper size
         //if different create a new Paper instance and setPaper(newPaperInst) to the PageFormat next.
         PageFormat printerSupportedPageFormat = new PdfSilentPrintFromLocalFile().getDefaultPrinterPageFormat();
         //Generally, you need to fit the PDF pages into the printer supported paper.
         //Otherwise, you might loose a portion of the actual PDF content simply
         //because the printer paper is not a one-to-one match with the actual PDF page media size.
         boolean fitToPrinterPaper = true;
         try {
           pdfPrinter.print(pdfFile, printerSupportedPageFormat, defaultPrintService, fitToPrinterPaper);
         }catch(Throwable t) {
           t.printStackTrace();
         }
       }
    
       public PageFormat getDefaultPrinterPageFormat() {
         PageFormat printerSupportedPageFormat = new PageFormat();
         Paper printerSupportedPaper = new Paper();
         printerSupportedPaper.setSize(612, 792);
        //must to this to make use of the full paper.
         printerSupportedPaper.setImageableArea(0.0D, 0.0D,
                                                printerSupportedPaper.getWidth(),
                                                printerSupportedPaper.getHeight());
         printerSupportedPageFormat.setPaper(printerSupportedPaper);
         return printerSupportedPageFormat;
       }
     }
    
     

    Back to Top


    Silent print existing PDF files from World Wide Web (www) location

    This is also similar to printing a PDF file from local/network file system. You have to construct a URL object using the document Url based on HTTP protocol address. If have to make sure that you have internet access for let the Smart JPrint download the remote web document for printing to a local printer or to a network printer. For example, if you want to print "http://www.activetree.com/demo/PrintRTFdocuments.pdf" located in activetree.com website then construct an URL object using the web address. Get the pages of the document and pass it to your selected printer to print silently or to your user selected printer.

    PdfSilentPrintFromURL.java

    import com.activetree.pdfprint.AtPdfStreamPrinter;
    import com.activetree.common.SmartJPrint;
    
    import javax.print.PrintService;
    import javax.print.PrintServiceLookup;
    import java.awt.print.PageFormat;
    import java.awt.print.Paper;
    import java.net.URL;
    
    public class PdfSilentPrintFromURL {
      public static void main(String[] args) {
        String pdfUrl = null;
                    if (args != null && args.length >= 2) {
                            SmartJPrint.setLicenseKey(args[0]);
          pdfUrl = args[1];
                    }
                    else {
                            System.out.println("Usage: java " + PdfSilentPrintFromURL.class.getName() + " [licenseKey]  [pdfUrl]");
                            System.exit(0);
          //System.out.println("using default url: http://www.activetree.com/demo/SmartJPrint_ToPDFDemo1.pdf");
          //pdfFile = "http://www.activetree.com/demo/SmartJPrint_ToPDFDemo1.pdf";
                    }
    
        //Conver to an URL object.
        URL url = null;
        try {
          url = new URL(pdfUrl);
        }catch(Throwable t) {
          t.printStackTrace();
        }
    
        AtPdfStreamPrinter pdfPrinter = new AtPdfStreamPrinter();
        //Here you decide which Printer to print by iterating through the
        //appropriate PrintService[] received from PrinterJob.lookupPrintServices()
        //for demo we are using the default printer using the following:
        PrintService defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();
        //Assuming your default printer supports LETTER quality paper (612x792) paper size
        //if different create a new Paper instance and setPaper(newPaperInst) to the PageFormat next.
        PageFormat printerSupportedPageFormat = new PdfSilentPrintFromLocalFile().getDefaultPrinterPageFormat();
        //Generally, you need to fit the PDF pages into the printer supported paper.
        //Otherwise, you might loose a portion of the actual PDF content simply
        //because the printer paper is not a one-to-one match with the actual PDF page media size.
        boolean fitToPrinterPaper = true;
        try {
          pdfPrinter.print(url, printerSupportedPageFormat, defaultPrintService, fitToPrinterPaper);
        }catch(Throwable t) {
          t.printStackTrace();
        }
      }
    
      public PageFormat getDefaultPrinterPageFormat() {
        PageFormat printerSupportedPageFormat = new PageFormat();
        Paper printerSupportedPaper = new Paper();
        printerSupportedPaper.setSize(612, 792);
       //must to this to make use of the full paper.
        printerSupportedPaper.setImageableArea(0.0D, 0.0D,
                                               printerSupportedPaper.getWidth(),
                                               printerSupportedPaper.getHeight());
        printerSupportedPageFormat.setPaper(printerSupportedPaper);
        return printerSupportedPageFormat;
      }
    }
    
     

    Back to Top


    Silent print PDF bytes from your program memory

    Those in the middle of manipulating the PDF content in memory, or somehow got the PDF content in bytes is ready to print it using the AtPdfStreamPrinter class. With byte PDF data source you can print silently or using print setup dialogs as desired. For example, if you have byte[] of PDF content, get the pages of the content as Pageable and then print the pages to a selected printer as shown next.

    PDFPrintingFromBytes.java

    
    import com.activetree.pdfprint.AtPdfPreviewFrame;
    import com.activetree.common.SmartJPrint;
    
    import java.net.URL;
    import java.io.InputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    
    public class PDFPrintingFromBytes {
      public static void main(String[] args) {
        String pdfFile = null;
                    if (args != null && args.length >= 2) {
                            SmartJPrint.setLicenseKey(args[0]);
          pdfFile = args[1];
                    }	else {
                            System.out.println("Usage: java " + PDFPrintingFromBytes.class.getName() + " [licenseKey] [PDF File Name]");
                            System.exit(0);
                    }
    
        URL url = null;
        byte pdfBytes[] = null;
        try {
          File file = new File(pdfFile);
          try {
            url = file.toURL();
          }catch(Throwable tx) {
            tx.printStackTrace();
            return;
          }
          InputStream in = url.openStream();
          ByteArrayOutputStream out = new ByteArrayOutputStream();
          byte buf[] = new byte[5120];
          for (int bytesCount=0; (bytesCount = in.read(buf)) != -1; ) {
            out.write(buf, 0, bytesCount);
          }
          in.close();
          out.close();
          pdfBytes = out.toByteArray();
          System.out.println("Reading...PdfBytes from URL = [" + pdfBytes.length + "]");
        }catch(Throwable t) {
          t.printStackTrace();
        }
    
        AtPdfStreamPrinter pdfPrinter = new AtPdfStreamPrinter();
        //Here you decide which Printer to print by iterating through the
        //appropriate PrintService[] received from PrinterJob.lookupPrintServices()
        //for demo we are using the default printer using the following:
        PrintService defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();
        //Assuming your default printer supports LETTER quality paper (612x792) paper size
        //if different create a new Paper instance and setPaper(newPaperInst) to the PageFormat next.
        PageFormat printerSupportedPageFormat = new PDFPrintingFromBytes().getDefaultPrinterPageFormat();
        //Generally, you need to fit the PDF pages into the printer supported paper.
        //Otherwise, you might loose a portion of the actual PDF content simply
        //because the printer paper is not a one-to-one match with the actual PDF page media size.
        boolean fitToPrinterPaper = true;
        try {
          pdfPrinter.print(pdfBytes, printerSupportedPageFormat, defaultPrintService, fitToPrinterPaper);
        }catch(Throwable t) {
          t.printStackTrace();
        }
      }
    
      public PageFormat getDefaultPrinterPageFormat() {
        PageFormat printerSupportedPageFormat = new PageFormat();
        Paper printerSupportedPaper = new Paper();
        printerSupportedPaper.setSize(612, 792);
       //must to this to make use of the full paper.
        printerSupportedPaper.setImageableArea(0.0D, 0.0D,
                                               printerSupportedPaper.getWidth(),
                                               printerSupportedPaper.getHeight());
        printerSupportedPageFormat.setPaper(printerSupportedPaper);
        return printerSupportedPageFormat;
      }
    }
    
     

    Back to Top


    Viewing an existing PDF document

    There are ready to use classes for displaying the PDF document as a dialog or window.
  • AtPdfViewPane - This is the Swing container responsible for displying the PDF into its UI. Those interested in customizing the GUI controls can look at the HowToUsePDfViewPane example. It allows you to customize and add the PDF viewer into your own Java GUI container.
  • AtPdfPreviewFrame - This is a frame class that makes use of the AtPdfViewPane and display the PDF reader as a frame window.
  • AtPdfPreviewDialog - This is a dialog class for displaying the PDF reader as a dialog window.
  • Smart JPrint PDF viewer works like an internet browser for browsing PDF documents from your local file system, from a remote World Wide Web (WWW) location, and PDF byte content from your program memory. This class is good for viewing PDF documents from any kind of Java application, e.g. an applet runs from a web browser and an application that runs as standalone Java program from a command line.

    Usage?

  • View a PDF Document - Open the PDF document into this browser. It shows all pages as little thumbnails, bookmarks, and let you navigate to view pages one at a time.
  • Print a PDF File - Print an existing PDF file opened from localhost or from a remote WWW location.
  • Save PDF document as PNG and JPEG images - Each page of the PDF document can be saved as a PNG and JPEG image file.
  • How to use?

    Use any one of its constructor for displaying an existing PDF document if you already know the PDF location in the file system or in the web. Otherwise, show just the browser and let the user select the PDF it wants to browse.

  • Use its default constructor (constructor with no arguments) for displaying the browser window. Your user can use its menus, toolbar buttons and other controls for opening a PDF file from your localhost or from a network drive. User can type the Web (www) location of a PDF document for opening into this browser.
  • Open a File - by using its constructor that takes a File argument.
  • Open a Web PDF document - using its constructor that takes an URL as the argument.
  • Open from Byte Data - If you already have the PDF content as byte array (byte[]), then use its constructor that takes byte[] as the argument. From byte array, it constructs the pages and displays.
  • Back to Top


    Viewing an existing PDF document in a Frame Window

    Following is an example of how you can create or make use of this example to launch a PDF Reader window as a frame.

    PdfViewerFrame.java

     import com.activetree.pdfprint.AtPdfPreviewFrame;
     import com.activetree.common.SmartJPrint;
    
       public class PdfViewerFrame {
         public static void main(String[] args) {
    	     if (args != null && args.length >= 1) {
    		     SmartJPrint.setLicenseKey(args[0]);
    	     } else {
    		     System.out.println("Usage: java " + PdfViewer.class.getName() + " [licenseKey]");
    		     System.exit(0);
    	     }
           AtPdfPreviewFrame previewFrame = new AtPdfPreviewFrame();
           previewFrame.setVisible(true);
           URL pdfUrl = null;
           try {
             pdfUrl = new URL("http://www.activetree.com/demo/webdemo/PdfJSPDemo3.pdf");
           }catch(Throwable t) {}
           pdfViewer.showPdf(pdfUrl);
         }
       }
     
    

    Back to Top


    Viewing an existing PDF document in a Frame Window

    Following is an example of how you can create or make use of this example to launch a PDF Reader window as a dialog.

    PdfViewerDialog.java

    import com.activetree.pdfprint.AtPdfPreviewDialog;
     import com.activetree.common.SmartJPrint;
    
       public class PdfViewerDialog {
         public static void main(String[] args) {
    	     if (args != null && args.length >= 1) {
    		     SmartJPrint.setLicenseKey(args[0]);
    	     } else {
    		     System.out.println("Usage: java " + PdfViewer.class.getName() + " [licenseKey]");
    		     System.exit(0);
    	     }
           AtPdfPreviewDialog previewDialog = new AtPdfPreviewDialog();
           previewDialog.setVisible(true);
           URL pdfUrl = null;
           try {
             pdfUrl = new URL("http://www.activetree.com/demo/webdemo/PdfJSPDemo3.pdf");
           }catch(Throwable t) {}
           previewDialog.showPdf(pdfUrl);
         }
       }
    
    

    Back to Top


    Customizing the PDF view pane and add to your GUI application

    Following is an example of how you can create a custom PDF Viewer and add that to your Java GUI container.

    HowToUsePdfViewPane.java

    import com.activetree.pdfprint.*;
    import com.activetree.common.SmartJPrint;
    
    import javax.swing.*;
    import javax.swing.tree.DefaultMutableTreeNode;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.ActionEvent;
    import java.io.File;
    import java.net.URL;
    
    public class HowToUsePdfViewPane extends JFrame {
      private CustomPdfViewPane pdfViewPane;
    
      class CustomPdfViewPane extends AtPdfViewPane {
        public CustomPdfViewPane(boolean restoreUserPreferences) {
          super(restoreUserPreferences);
          super.setStatusBarVisible(false);
          super.setPageToolbarVisible(false);
          super.setFileToolbarVisible(false);
          super.setThumbnailsToolbarVisible(false);
          super.setBrowseToolbarVisible(false);
          super.setHelpButtonVisible(false);
          super.setPrintPageEntryFieldVisible(false);
          super.setRotateAntiClockwiseButtonVisible(false);
          super.setRotateClockwiseButton(false);
          super.setPNGButtonVisible(false);
          super.setJPEGButtonVisible(false);
          super.setPDFButtonVisible(false);
          super.setLocationBarVisible(false);
    
          //To let part of the left hand unility pane visible
          //super.setBookmarkPaneVisible(false);
          //super.setPagesPaneVisible(false);
    
          //for completely making the left pane invisible
          //super.setLeftUtilityPaneVisible(false);
        }
      }
    
      public HowToUsePdfViewPane() {
        this(true);
      }
    
      public HowToUsePdfViewPane(boolean restoreUserPreferences) {
        this.pdfViewPane = new CustomPdfViewPane(restoreUserPreferences);
        setupContentPane();
      }
    
      protected void setupContentPane() {
        setTitle("SmartJPrint PDF Reader");
        setIconImage(AtPdfPrintImageList.IMAGE_LIST.ACTIVETREE_ICON_SMALL.getImage());
    
        Container container = getContentPane();
        container.setLayout(new BorderLayout(0, 0));
        container.add(pdfViewPane, BorderLayout.CENTER);
    
        //set a default size for the window
        Rectangle userPreferredViewSize = pdfViewPane.getUserPreferredViewSize();
        Dimension defaultViewSize = pdfViewPane.getDefaultViewSize();
        System.out.println("user pref bounds=" + userPreferredViewSize);
        if (userPreferredViewSize != null) {
          setBounds(userPreferredViewSize);
        }else {
          setSize(defaultViewSize);
        }
    
        //Do not close the window by default
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    
        //Add a window closing listener so that a proper cleanup and shutdown is possible.
        addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent evt) {
            pdfViewPane.destroy();
            setVisible(false);
            dispose();
          }
        });
    
        ///add PDF action listener
        //Because may be only the VISIBLE page be printer instead of the whole document.
        pdfViewPane.addPdfActionListener(new AtPdfActionListener() {
          public void pdfActionPerformed(ActionEvent evt) throws AtPdfUserActionVetoException {
            if (evt.getActionCommand().equals(AtPdfViewPane.PRINT_CMD)) {
              //Do your single page printing here.
              pdfViewPane.printCurrentPage(1);  //print 1 copy of the page
              //pdfViewPane.printCurrentPage(true);
              System.out.println("vetoing user action...");
              throw new AtPdfUserActionVetoException();
            }else if (evt.getActionCommand().equals(AtPdfViewPane.BOOKMARK_SELECTION_CMD)) {
              AtPdfTOCNodeData bookmarkItem = (AtPdfTOCNodeData) evt.getSource();
              String title = bookmarkItem.getTitle();
              String pageNumber = bookmarkItem.getPageNo();
              System.out.println("Bookmark: (title=" + title +") (page# " + pageNumber +")");
              //do not veto so that the Smart JPrint will display the bookmark in the view.
            }else if (evt.getActionCommand().equals(AtPdfViewPane.THUMBNAIL_SELECTION_CMD)) {
              AtPdfThumbnailData selectedThumbnail = (AtPdfThumbnailData) evt.getSource();
              int pageIndex = selectedThumbnail.pageIndex;
              BufferedImage thumbnailIcon = selectedThumbnail.icon;
              System.out.println("Thumbnail selected: pageIndex=" + pageIndex + ", icon isNull? " + (thumbnailIcon == null));
              //do something and veto if necessary.
            }else {
              //Ok, let it do the default action defined in smart jprint lib.
            }
          }
        });
      }
    
      public void showPdf(final File pdfFile) {
        pdfViewPane.showPdf(pdfFile);
      }
    
      public void showPdf(final URL pdfUrl) {
        pdfViewPane.showPdf(pdfUrl);
      }
    
      public void showPdf(final byte[] pdfData) {
        pdfViewPane.showPdf(pdfData);
      }
    
      public void showPageIndex(int pageIndex) {
        pdfViewPane.showPageIndex(pageIndex);
      }
    
      public void showFirstPage() {
        pdfViewPane.showFirst();
      }
    
      public void showNextPage() {
        int displayedPageIdx = pdfViewPane.getDisplayedPageIndex();
        int pageCount = pdfViewPane.getPageCount();
        if (displayedPageIdx == (pageCount-1)) {//last page is already displayed  can not go beyond last.
          return;
        }
        pdfViewPane.showNext();
      }
    
      public void showPreviousPage() {
        int displayedPageIdx = pdfViewPane.getDisplayedPageIndex();
        if (displayedPageIdx == 0) {
          //return becs. no more pages before this one.
          return;
        }
        pdfViewPane.showPrevious();
      }
    
      public void showLastPage() {
        pdfViewPane.showLast();
      }
    
      public void setPages(AtStreamPdfPage[] pages) {
        pdfViewPane.setPages(pages);
      }
    
      public AtPdfAbstractPage[] getPages() {
        return pdfViewPane.getPages();
      }
    
      public void loadDocument(File pdfFile) {
        pdfViewPane.loadDocument(pdfFile);
      }
    
      public void setBookmark(DefaultMutableTreeNode bookmark) {
        pdfViewPane.setBookmark(bookmark);
      }
    
      //////////////////////////////////////////////////
      public static void main(String[] args) {
        File pdfFile = null;
        if (args.length >= 2) {
          SmartJPrint.setLicenseKey(args[0]);
          pdfFile = new File(args[1]);
          if (!pdfFile.exists()) {
            System.out.println("PDF document does not exist: " + args[1]);
            System.exit(1);
          }
        }else {
          System.out.println("Usage: java program licenseKey pdfFile");
          System.exit(0);
        }
    
        //pass false for ignoring view setting in previous run.
        HowToUsePdfViewPane pdfFrame = new HowToUsePdfViewPane(true);
    
        //Use this segment for great performance, and if you are NOT showing
        //page thumbnails using setPagesPaneVisible(false), or entire left
        //utility pane is invisible through a call to setLeftUtilityPaneVisible(false).
    //    AtPdfStreamPrinter pdfPrinter = new AtPdfStreamPrinter();
    //    AtStreamPdfPage[] pdfDocPages = null;
    //    int pageCount = 0;
    //    try {
    //      Pageable pdfPages = pdfPrinter.getPageable(pdfFile);
    //      if (pdfPages != null) {
    //        pageCount = pdfPages.getNumberOfPages();
    //      }
    //      for (int i=0; pdfPages != null && i < pdfPages.getNumberOfPages(); i++) {
    //        if (pdfDocPages == null) {
    //          pdfDocPages = new AtStreamPdfPage[pdfPages.getNumberOfPages()];
    //        }
    //        pdfDocPages[i] = (AtStreamPdfPage) pdfPages.getPrintable(i);
    //      }
    //      pdfFrame.setPages(pdfDocPages);
    //      DefaultMutableTreeNode bookmark = pdfPrinter.getBookmark();
    //      pdfFrame.setBookmark(bookmark);
    //    }catch(Throwable t) {
    //      t.printStackTrace();
    //    }
    
        //TODO: Use this segment if you want to show the pages as little thumbnails
        pdfFrame.loadDocument(pdfFile);
        AtPdfAbstractPage[] pages = pdfFrame.getPages();
        int pageCount = 0;
        if (pages != null) {
          pageCount = pages.length;
        }
    
        System.out.println("Page count=" + pageCount);
        if (pageCount >= 4) {
          pdfFrame.showPageIndex(3); //page-4
        }else {
          pdfFrame.showFirstPage();
        }
        pdfFrame.setVisible(true);
      }
    }
    
    

    Back to Top


    Running PDF Reader as an applet from a browser

    The example shown next can be used for running the PDF reader from a web browser.

    PDFViewerApplet.java

    import com.activetree.common.SmartJPrint;
    import com.activetree.pdfprint.AtPdfPreviewFrame;
    
    import javax.swing.*;
    import java.net.URL;
    
    public class PDFViewerApplet extends JApplet {
      public PDFViewerApplet() {
      }
    
      public void init() {
        String licenseKey = getParameter("LICENSE_KEY");
        SmartJPrint.setLicenseKey(licenseKey);
        postInit();
      }
    
      public void postInit() {
        AtPdfPreviewFrame pdfViewer = new AtPdfPreviewFrame();
        pdfViewer.setVisible(true);
        URL pdfUrl = null;
        try {
          //change to your default PDF URL
          pdfUrl = new URL("http://www.activetree.com/demo/webdemo/PdfJSPDemo2.pdf");
        }catch(Throwable t) {}
        pdfViewer.showPdf(pdfUrl);
      }
    
      public static void main(String[] args) {
        String licenseKey = null;
        if (args != null && args.length >= 1) {
          licenseKey = args[0];
        }else {
          System.out.println("Usage: " + PDFViewerApplet.class.getName() +" [LICENSE_KEY]");
        }
        SmartJPrint.setLicenseKey(licenseKey);  //change to set your license key.
        PDFViewerApplet pdfViewer = new PDFViewerApplet();
        pdfViewer.postInit();
      }
    }
    
    

    Back to Top


    PostScript Conversion of Java Report Pages

    From SmartJPrint release 1.5.8 onward you can convert the generated report pages as a PostScript document. Newly provided com.activetree.print.postscript.AtJava2PostScriptPrinter class has methods to either save the report as a PostScript file or get a InputStream of the converted PostScript conent. Use either of the methods appropriate for you. For computer with higher memory can use the getPostScriptOutput() for faster processing as it generates the postscript in memory and then returns the InputStream of the generated content. Other one, directly saves the PostScript output to the passed OutputStream.
  • public InputStream getPostScriptOutput(AtAbstractPage[] pages)
  • public void saveAsPostScriptOutput(AtAbstractPage[] pages, OutputStream psStream)

  • An Example
    Following is an example that converts the SmartJPrint generated report pages to a PostScript file. PostScript files can be directly sent to a PostScript supported printer for printing.

    import demo.activetree.print.PrintFrame;
    import demo.activetree.print.DemoHeaderFooterRenderer;
    
    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    import java.awt.event.ActionEvent;
    import java.awt.print.Pageable;
    import java.io.InputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    
    import com.activetree.print.PageHeaderFooterListener;
    import com.activetree.print.PageNoPainter;
    import com.activetree.print.AtAbstractPage;
    import com.activetree.print.postscript.AtJava2PostScriptPrinter;
    import com.activetree.common.SmartJPrint;
    
    public class Java2PostScriptPrinterDemo1 extends PrintFrame {
    	private JTable table = null;
    
    	public Java2PostScriptPrinterDemo1() {
    		super();
    		frame.setTitle("Smart JPrint - Print JTable");
    		table = getTable();
    		setPrintableComponent(table);
        //change the text for the print button
        print.setText("Generate PostScript");
        preview.setVisible(false);
        printPdf.setVisible(false);
    	}
    
    	public JTable getJTable() {
    		return table;
    	}
    
    	public void actionPerformed(ActionEvent evt) {
    		PageHeaderFooterListener l = new DemoHeaderFooterRenderer("Employee Information - Manufacturing Division");
    		tablePrinter.setPageHeaderFooterListener(l);
    		if (evt.getActionCommand().equals("Print")) {
    			//tablePrinter.print(table, PageNoPainter.PAGE_NONE, false);
          Pageable allPages = tablePrinter.getPageable(table, PageNoPainter.LOWER_CENTER);
          AtAbstractPage[] pages = new AtAbstractPage[allPages.getNumberOfPages()];
          for (int i=0; i < allPages.getNumberOfPages(); i++) {
            AtAbstractPage aPage = (AtAbstractPage) allPages.getPrintable(i);
            pages[i] = aPage;
          }
    
          //Print to a file
          String psOutFile = "./smartjprint_2_postscript2.ps";
          try {
            FileOutputStream psOutStream = new FileOutputStream(psOutFile);
            AtJava2PostScriptPrinter psPrinter = new AtJava2PostScriptPrinter();
            psPrinter.saveAsPostScriptOutput(pages, psOutStream);
          }catch(Throwable t) {
            t.printStackTrace();
          }
    
          //todo:
          //OR Do this for either saving to a file or to send to a PS printer.
    
    //      AtJava2PostScriptPrinter psPrinter = new AtJava2PostScriptPrinter();
    //      InputStream psStream = null;
    //      try {
    //        psStream = psPrinter.getPostScriptOutput(pages);
    //      }catch(Throwable t) {
    //        t.printStackTrace();
    //      }
    //      //Save to a file OR send it to a PS printer such as HP LeserJet
    //      //save as a file.
    //      saveAsPostScript(psStream, "./smartjprint_2_postscript1.ps");
    //      //print to a PS printer
    //      //System.exec(...);
    		}
    	}
    
      public void saveAsPostScript(InputStream psStream, String fileName) {
          File psFile = new File(fileName);
          FileOutputStream out = null;
          try {
            out = new FileOutputStream(psFile);
            byte buf[] = new byte[5120];
            for (int bytesCount=0; (bytesCount = psStream.read(buf)) != -1; ) {
              out.write(buf, 0, bytesCount);
            }
            psStream.close();
            out.close();
          }catch(Throwable t) {
            t.printStackTrace();
          }
      }
    
      //////////////////////////////////////////////////////////////////////
    
    	JTable getTable() {
    		String[] cols = {"EmpNo", "Employee Name", "SSN", "Date Of Birth",
    		                 "Home Phone", "Work Phone", "Street Address",
    		                 "Apt/House No", "City", "State", "Zip Code"};
    		Object[][] data = new Object[100][cols.length];
    
    		//Create same data for the table.
    		int empNo = 1000;
    		String name = "Employee Name - ";
    		String ssn = "SSN - ";
    		String dob = "Date - ";
    		String homePhone = "Home Phone - ";
    		String workPhone = "Work Phone - 000";
    		String stAddr = "Street Address - ";
    		String houseNo = "Apt/House No # ";
    		String city = "City Name - ";
    		String state = "State Name - ";
    		String zipcode = "Zip Code - ";
    		for (int row=0; row < data.length; row++) {
    			data[row][0] = String.valueOf(empNo+row);
    			data[row][1] = name + row;
    			data[row][2] = ssn + row;
    			data[row][3] = dob + row;
    			data[row][4] = homePhone + row;
    			data[row][5] = workPhone + row;
    			data[row][6] = stAddr + row;
    			data[row][7] = houseNo + row;
    			data[row][8] = city + row;
    			data[row][9] = state + row;
    			data[row][10] = zipcode + row;
    
    			if (row == 2) {
    				data[row][1] = null;
    				data[row][2] = null;
    				data[row][3] = null;
    			}
    		}
    
    		DefaultTableModel tableModel = new DefaultTableModel(data, cols) {
    			public boolean isCellEditable(int rowIndex, int columnIndex) {
    				return false;
    			}
    		};
    		JTable table = new JTable(tableModel);
    		return table;
    	}
    
    	public static void main(String[] args) {
    		if (args != null && args.length >= 1) {
    			SmartJPrint.setLicenseKey(args[0]);
    		}
    		else {
    			System.out.println("Usage: java " + Java2PostScriptPrinterDemo1.class.getName() + " licenseKey");
    			System.exit(0);
    		}
    		PrintFrame demo = new Java2PostScriptPrinterDemo1();
    		demo.postInit();
    		demo.setVisible(true);
    	}
    }
    

    Back to Top


    PDF to PostScript conversion

    SmartJPrint lets you directly print the PDF content to a printer. However, for some reason if you wish can convert the PDF document to a PostScript file. The com.activetree.pdfprint.AtPDF2PostScriptPrinter class has following methods for the conversion. The only difference with the AtJava2PostScriptPrinter is that one takes AtAbstractPage[] and another takes AtPdfAbstractPage[] as the method argument.
  • public InputStream getPostScriptOutput(AtPdfAbstractPage[] pages)
  • public void saveAsPostScriptOutput(AtPdfAbstractPage[] pages, OutputStream psStream)
  • An Example

    import com.activetree.common.SmartJPrint;
    import com.activetree.pdfprint.AtPdfStreamPrinter;
    import com.activetree.pdfprint.AtPdfAbstractPage;
    import com.activetree.pdfprint.AtPDF2PostScriptPrinter;
    
    import java.awt.print.Pageable;
    import java.io.File;
    import java.io.FileOutputStream;
    
    public class Pdf2PostScriptDemo {
      public static void main(String[] args) {
        String pdfFile = null;
    		if (args != null && args.length >= 2) {
    			SmartJPrint.setLicenseKey(args[0]);
          pdfFile = args[1];
    		}
    		else {
    			System.out.println("Usage: java " + SilentPrintPDFFile.class.getName() + "   ");
    			System.exit(0);
    		}
        try {
          File pdfDoc = new File(pdfFile);
    
          AtPdfStreamPrinter pdfStreamPrinter = new AtPdfStreamPrinter();
          Pageable allPages = pdfStreamPrinter.getPageable(pdfDoc);
    
          AtPdfAbstractPage[] pages = new AtPdfAbstractPage[allPages.getNumberOfPages()];
          for (int i=0; i < allPages.getNumberOfPages(); i++) {
            AtPdfAbstractPage aPage = (AtPdfAbstractPage) allPages.getPrintable(i);
            pages[i] = aPage;
          }
    
          //Print to a file
          String psOutFile = "./pdf_2_postscript1.ps";
          try {
            FileOutputStream psOutStream = new FileOutputStream(psOutFile);
            AtPDF2PostScriptPrinter psPrinter = new AtPDF2PostScriptPrinter();
            psPrinter.saveAsPostScriptOutput(pages, psOutStream);
          }catch(Throwable t) {
            t.printStackTrace();
          }
        }catch(Throwable t) {
          t.printStackTrace();
        }
      }
    }
    
    

    Back to Top


    PDF to TIFF

    Smart JPrint provides AtPdfConverter class for converting an existing PDF document to a TIFF document. This class has following methods related to TIFF conversion of a PDF document.
  • saveAsTIFF(AtPdfAbstractPage[] allPages, java.io.OutputStream outputStream, boolean compress)
  • saveAsTIFF(AtPdfAbstractPage[] allPages, java.lang.String outputFileName, boolean compress)
  • An Example for PDF to TIFF

    
    import com.activetree.common.SmartJPrint;
    import com.activetree.pdfprint.AtPdfStreamPrinter;
    import com.activetree.pdfprint.AtPdfAbstractPage;
    import com.activetree.pdfprint.AtPdfConverter;
    
    import java.awt.print.Pageable;
    import java.io.File;
    
    public class Pdf2TiffDemo {
      public static void main(String[] args) {
        String pdfInputFile = null;
        String tiffOutputFile = null;
        String licenseKey = null;
        if (args.length >= 3) {
          licenseKey = args[0];
          pdfInputFile = args[1];
          tiffOutputFile = args[2];
        }else {
          System.out.println("Usage: program licenseKey pdfInputFile tiffOutputFile");
          System.exit(0);
        }
        SmartJPrint.setLicenseKey(licenseKey);
    
        //get the pdf pages
        AtPdfStreamPrinter pdfPrinter = new AtPdfStreamPrinter();
        AtPdfAbstractPage[] pdfPages = null;
        try {
          File pdfFile = new File(pdfInputFile);
          Pageable pages = pdfPrinter.getPageable(pdfFile);
          pdfPages = new AtPdfAbstractPage[pages.getNumberOfPages()];
          for (int i=0; pages != null && i < pages.getNumberOfPages(); i++) {
            pdfPages[i] = (AtPdfAbstractPage) pages.getPrintable(i);
          }
        }catch(Throwable t) {
          t.printStackTrace();
        }
    
        //Now convert to TIFF
        try {
          AtPdfConverter.saveAsTIFF(pdfPages, tiffOutputFile, true);
        }catch(Throwable t) {
          t.printStackTrace();
        }
        System.out.println("A TIFF document is produced at: " + tiffOutputFile);
      }
    }
    
    
    

    Back to Top


    PDF to JPEG

    The AtPdfConverter class has number of factory methods for converting your existing PDF pages to JPEG images using the following methods:
  • saveAsJPEG(AtPdfAbstractPage page, javax.imageio.stream.ImageOutputStream outputStream, float qualityFactor)
  • saveAsJPEG(AtPdfAbstractPage page, java.lang.String outputFileName, float qualityFactor)
  • An Example for PDF to JPEG

    
    import com.activetree.common.SmartJPrint;
    import com.activetree.pdfprint.AtPdfStreamPrinter;
    import com.activetree.pdfprint.AtPdfAbstractPage;
    import com.activetree.pdfprint.AtPdfConverter;
    
    import java.io.File;
    import java.awt.print.Pageable;
    
    public class Pdf2JpegDemo {
      public static void main(String[] args) {
        String pdfInputFile = null;
        String jpegOutputFile = null;
        String licenseKey = null;
        if (args.length >= 3) {
          licenseKey = args[0];
          pdfInputFile = args[1];
          jpegOutputFile = args[2];
        }else {
          System.out.println("Usage: program licenseKey pdfInputFile jpegOutputFilePrefix");
          System.exit(0);
        }
        SmartJPrint.setLicenseKey(licenseKey);
    
        //get the pdf pages
        AtPdfStreamPrinter pdfPrinter = new AtPdfStreamPrinter();
        try {
          File pdfFile = new File(pdfInputFile);
          Pageable pages = pdfPrinter.getPageable(pdfFile);
          for (int i=0; pages != null && i < pages.getNumberOfPages(); i++) {
            AtPdfAbstractPage aPdfPage = (AtPdfAbstractPage) pages.getPrintable(i);
            float quality_factor = 1.0f;
            AtPdfConverter.saveAsJPEG(aPdfPage, jpegOutputFile + "_" + (i+1) + ".jpg", quality_factor);
          }
        }catch(Throwable t) {
          t.printStackTrace();
        }
        System.out.println("JPEG for each page is produced at: " + jpegOutputFile);
      }
    }
    
    
    

    Back to Top


    PDF to PNG

    Ue the following methods from the AtPdfConverter to convert your existing PDF pages to PNG images:
  • saveAsPNG(AtPdfAbstractPage page, java.io.OutputStream outputStream)
  • saveAsPNG(AtPdfAbstractPage page, java.lang.String outputFileName)
  • An Example for PDF to PNG

    
    import com.activetree.common.SmartJPrint;
    import com.activetree.pdfprint.AtPdfStreamPrinter;
    import com.activetree.pdfprint.AtPdfAbstractPage;
    import com.activetree.pdfprint.AtPdfConverter;
    
    import java.io.File;
    import java.awt.print.Pageable;
    
    public class Pdf2PngDemo {
      public static void main(String[] args) {
        String pdfInputFile = null;
        String pngOutputFile = null;
        String licenseKey = null;
        if (args.length >= 3) {
          licenseKey = args[0];
          pdfInputFile = args[1];
          pngOutputFile = args[2];
        }else {
          System.out.println("Usage: program licenseKey pdfInputFile pngOutputFilePrefix");
          System.exit(0);
        }
        SmartJPrint.setLicenseKey(licenseKey);
    
        //get the pdf pages
        AtPdfStreamPrinter pdfPrinter = new AtPdfStreamPrinter();
        try {
          File pdfFile = new File(pdfInputFile);
          Pageable pages = pdfPrinter.getPageable(pdfFile);
          for (int i=0; pages != null && i < pages.getNumberOfPages(); i++) {
            AtPdfAbstractPage aPdfPage = (AtPdfAbstractPage) pages.getPrintable(i);
            AtPdfConverter.saveAsPNG(aPdfPage, pngOutputFile + "_" + (i+1) + ".png");
          }
        }catch(Throwable t) {
          t.printStackTrace();
        }
        System.out.println("PNG for each page is produced at: " + pngOutputFile);
      }
    }
    
    
    

    Back to Top


    PDF viewer classes

    SmartJPrint provides you number of readymade PDF viewer Swing classes. You have the choice to plugin the PDF viewer pane class into your GUI or display the PDF documents using the SmartJPrint provided frame and dialog classes. Following classes is made available for viewing an existing PDF document and/or PDF content byte array from your program memory.
  • AtPdfPreviewFrame - A PDF viewer frame window
  • AtPdfPreviewDialog - A PDF viewer dialog window
  • AtPdfViewPane - A PDF viewer plugable Swing Component
  • Back to Top


    PDF Viewer Frame Window - AtPdfPreviewFrame

    This class makes use of the AtPdfViewPane PDF viewer component and plugs it into a JFrame window to let the PDF viewer show up as a Frame window.

    An Example of using AtPdfPreviewFrame

    
    import com.activetree.pdfprint.AtPdfPreviewFrame;
    import com.activetree.common.SmartJPrint;
    
    public class PdfViewerFrame {
      public static void main(String[] args) {
    		if (args != null && args.length >= 1) {
    			SmartJPrint.setLicenseKey(args[0]);
    		}
    		else {
    			System.out.println("Usage: java " + PdfViewer.class.getName() + " ");
    			System.exit(0);
    		}
        AtPdfPreviewFrame previewFrame = new AtPdfPreviewFrame();
        previewFrame.setVisible(true);
      }
    }
    
    
    

    Back to Top


    PDF Viewer Dialog Window - AtPdfPreviewDialog

    This class makes use of the AtPdfViewPane PDF viewer component and plugs it into a JDialog window for showing PDF viewer as a dialog.

    An Example of using AtPdfPreviewDialog

    
    import com.activetree.pdfprint.AtPdfPreviewDialog;
    import com.activetree.common.SmartJPrint;
    
    import java.awt.*;
    
    public class PdfViewerDialog {
      public static void main(String[] args) {
    		if (args != null && args.length >= 1) {
    			SmartJPrint.setLicenseKey(args[0]);
    		}
    		else {
    			System.out.println("Usage: java " + PdfViewer.class.getName() + " ");
    			System.exit(0);
    		}
        AtPdfPreviewDialog previewFrame = new AtPdfPreviewDialog((Frame)null);
        previewFrame.setVisible(true);
      }
    }
    
    

    Back to Top


    PDF View Pane Swing component- AtPdfViewPane

    This is the class that has everything you need to display the PDF viewer. This is a javax.swing.JPanel can be plugged in into your existing GUI.

    An Example of using AtPdfViewPane

    
    import com.activetree.pdfprint.AtPdfViewPane; 
    import com.activetree.pdfprint.AtPdfPrintResource; 
    import com.activetree.pdfprint.AtPdfPrintImageList; 
    import com.activetree.utils.AtDebug; 
    
    import javax.swing.*; 
    import java.awt.*; 
    import java.awt.event.WindowEvent; 
    import java.awt.event.WindowAdapter; 
    import java.io.File; 
    import java.net.URL; 
    
    public class HowToUsePdfViewPane extends JFrame { 
      private AtPdfViewPane pdfViewPane; 
    
      public HowToUsePdfViewPane() { 
        this(true); 
      } 
    
      public HowToUsePdfViewPane(boolean restoreUserPreferences) { 
        this.pdfViewPane = new AtPdfViewPane(restoreUserPreferences); 
        setupContentPane(); 
        setTitle(AtPdfPrintResource.PRINT_RESOURCE.getText("SMARTJPRINT_PDF_VIEWER")); 
        setIconImage(AtPdfPrintImageList.IMAGE_LIST.ACTIVETREE_ICON_SMALL.getImage()); 
        setJMenuBar(pdfViewPane.getMenuBar()); 
      } 
    
      protected void setupContentPane() { 
        Container container = getContentPane(); 
        container.setLayout(new BorderLayout(0, 0)); 
        container.add(pdfViewPane, BorderLayout.CENTER); 
    
        //set a default size for the window 
        Rectangle userPreferredViewSize = pdfViewPane.getUserPreferredViewSize(); 
        Dimension defaultViewSize = pdfViewPane.getDefaultViewSize(); 
        AtDebug.debug("user pref bounds=" + userPreferredViewSize); 
        if (userPreferredViewSize != null) { 
          setBounds(userPreferredViewSize); 
        }else { 
          setSize(defaultViewSize); 
        } 
    
        //Do not close the window by default 
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); 
    
        //Add a window closing listener so that a proper cleanup and shutdown is possible. 
        addWindowListener(new WindowAdapter() { 
          public void windowClosing(WindowEvent evt) { 
            pdfViewPane.destry(); 
            setVisible(false); 
            dispose(); 
          } 
        }); 
      } 
    
      public void showPdf(final File pdfFile) { 
        pdfViewPane.showPdf(pdfFile); 
      } 
    
      public void showPdf(final URL pdfUrl) { 
        pdfViewPane.showPdf(pdfUrl); 
      } 
    
      public void showPdf(final byte[] pdfData) { 
        pdfViewPane.showPdf(pdfData); 
      } 
    } 
    
    

    Back to Top


    Generating PDF documents from J2EE and GUI Swing programs

    The AtPdfPrinter is the core PDF generation class. Use its print() methods to either pass a AtBook instance or a Swing component such as:

  • JTable
  • JTextArea - paint text viewing component.
  • JEditorPane - HTML viewing component
  • JTextPane - RTF viewing component
  • JTextComponent - any custom component created from this one.
  • AtBook class is used to accumulate text, icon, and 2D graphics from your J2EE/GUI programs using its very simple to use methods.

  • write(String)
  • write(ImageIcon)
  • write(AtStringElement)
  • write(AtIconElement)
  • write(AtNewlineElement)
  • write(AtLineElement)
  • Back to Top


    Generating PDF from J2EE programs

    It is very easy to generate Java (usually J2EE) program output to a PDF file using the Smart JPrint classes. You have to create a AtBook and the add your Java program output into this class. Finally, pass the AtBook instance into one of the print() methods in the AtPdfPrinter class shown next as an example. See more examples and demo.

    private AtPdfPrinter pdfPrinter = new AtPdfPrinter();
    private AtBook book = new AtBook();

    AtStringElement elm = new AtStringElement("Generate PDF Documents using \"Smart JPrint\"\n\n", titleFont);
    elm.setForeground(titleColor);
    book.write(elm);
    book.write("Smart JPrint APIs are 100% pure Java APIs and takes care of any kind of PDF " +
    "generation and printing needs. SmartJ printing APIs lets you ");
    elm = new AtStringElement("automaticaly format texts, icons, 2D Graphics as output from " +
    "your J2EE and Swing programs to generate PDF, print, and preview " +
    "the output pages in a wanderful preview UI.");
    elm.setFont(new Font("Helvetica", Font.ITALIC, 12));
    book.write(elm);
    book.write("\n\n");

    book.write(new AtNewlineElement());
    elm = new AtStringElement("Generate PDF from your J2EE Server Applications\n\n");
    elm.setFont(subTitleFont);
    elm.setForeground(subTitleColor);
    book.write(elm);

    book.write(new AtStringElement("Deploy the SmartJPrint APIs to generate PDF files from your J2EE server. " +
    "Let your J2EE program write styled text, icons, and 2D graphics " +
    "using the SmartJ printing APIs. " +
    "You can then have options to generate a \"Adobe Acrobat\" readable " +
    "PDF document as a file, or print the output to a printer. " +
    "Design your PDF forms using the text, icons, and 2D graphics. " +
    "Look at the examples to find out how simple it is to do all of these from " +
    "your Java program.\n\n"));

    OutputStream pdfOutputStream = new PrintStream(new FileOutputStream("./smartjprint.pdf"));
    pdfPrinter.print(book, pdfOutputStream, PageNoPainter.LOWER_CENTER, false);

    Back to Top


    Generating PDF from Swing components

    When printing the above mentioned swing components, it is just couple of lines of code for writing as a PDF file. Here is an example that prints a JTable component by breaking the rows and columns into multiple pages.

    JTable table;
    //populate the table (does not matter if it is currently visible or not)
    .... ....
    OutputStream pdfOutputStream = new PrintStream(new FileOutputStream("./smartjprint.pdf"));
    AtTablePrinter pdfPrinter = new AtTablePrinter();
    pdfPrinter.print(table, pdfOutputStream, PageNoPainter.LOWER_CENTER, false);

    Back to Top


    Showing the Printer Discovery and Page Setup Dialog

    When using the AtDocumentPrinter and the AtTablePrinter objects, you might or might not show the 'printer discovery' and 'page setup' dialogs to the user. Depending whether you want to show or not to show the discovery dialogs, you have choose from the overloaded print methods. The foollowing print method takes 2 arguments and shows a printer discovery dialog and the page setup dialog to the user.

    docPrinter.print(compToPrint, PageNoPainter.UPPER_RIGHT);

    However, the following print method gives you more control over a lot of things. It allows you to specify a set of printer properties as a HashPrintRequestAttributeSet object.

    docPrinter.preview(table, PageNoPainter.LOWER_CENTER, false);

    Or use the next print method to print with a 4'th argument.

    HashPrintRequestAttributeSet pAttrs = new HashPrintRequestAttributeSet();      
    docPrinter.print(compToPrint, PageNoPainter.UPPER_RIGHT, false, pAttrs);

    The third argument in above two cases is used for whether or not to show the print discovery and page setup dialog to the user. If a value "false" is passed, no print doscovery and page setup dialog is displayed to the user. Otherwise   "true" shows a printer discovery dialog and a page setup dialog to the user. The last argument is used by the API to discover a list of printer that has the printing capabilities as specified in the pAttrs list.

    Back to Top


    Discovering a printer with specific printing attributes

    A printer discovery dialog can be shown for the user to select from a list of printers available where the output might be sent for printing. You can specify a set of printing attributes as a key/value pait in a HashPrintRequestAttributeSet object and pass the printer objects print method.

            HashPrintRequestAttributeSet pAttrs = new HashPrintRequestAttributeSet();
            pAttrs.add(MediaSizeName.ISO_A4); //ISO-A4 page size.
            pAttrs.add(Finishings.BIND); //document needs binding.
            pAttrs.add(Sides.DUPLEX);

       docPrinter.print(compToPrint, PageNoPainter.UPPER_RIGHT, false, pAttrs);

    The above code segment shows how to specify printing properties to the print method in the AtDocumentPrinter and AtTablePrinting objects. For example, if none of the printers supports DUPLEX, then there is not going to be any printer selectable for printing the output. It is therefore, suggested to use the print method that takes only first two arguments and discovers all of the printers available.

    Back to Top


    Previewing/Printing the pages

    For printing the pages you must call the any of the print() methods discussed already.

    For previewing the output the SmartJ Print API allows you to show a preview frame where al the pages are displayed for you to have a feel of it. In the PREVIEW frame window, you can look at all the pages one at a time. It allows the user to go to a page number. Moreover, the preview frame allows the user to print the pages selectively to a printer.

    JTable table;
         ....
    AtTablePrinter tablePrinter = new AtTablePrinter();
    tablePrinter.preview(table, PageNoPainter.LOWER_CENTER, false);

    The above code segment is previewing the content of a JTable using the AtTablePrinter object. You can also use the AtDocumentPrinter object to preview the contenxt of ant JTextComponent swing components the same way. First argument here is a JTable that needs to be previewed. The second argument is indicating about where to print the page number on each page. The third argument cause the API not to show the printer discivery and page setup dialog to the user.

    Back to Top


    Printing page number to a predefined location on the pages

    You might have already noticed that the second argument to the print() and the preview() method is for specifying where to print the page number on the pages to be printed. By default the page number is printed on the lower center of a page using the default location constants PageNoPainter.LOWER_CENTER. If you want to change the page number printing location, might use one of the following constants from the PageNoPainter interface.

        PageNoPainter.PAGE_NONE - when you do not want to print a page number on the pages.
        PageNoPainter.LOWER_CENTER - prints the page number at the lower center on a page.
        PageNoPainter.LOWER_RIGHT - prints the page number at the lower right hand corner on a page.
        PageNoPainter.UPPER_CENTER - print the page number at the upper center on a page.
        PageNoPainter.UPPER_RIGHT - used for printing page number on upper right corner on a page.

     

    Back to Top


    Producing header and footer in each page

    Add a PageHeaderFooterListener to the printer class to receive a callback on the listener's setPageHeaderAndFooter(PageHeaderFooterRenderer headerFooterRenderer) method. The PageHeaderFooterRenderer interface allows you to then use its APIs to get and set header and footer. It's getPageNumber() will let you know the current page number so that an appropriate footer and header can be decided.

    Following example shows how you can set header and footer to each output pages.

    AtGenericPrinter j2eePrinter = new AtGenericPrinter();
    AtBook book = new AtBook();
    //populate the book with text, icons, 2D graphics.
    printerClass.setPageHeaderFooterListener(new PageHeaderFooterListener() {
      int pageCount = 0;
      public void setPageHeaderAndFooter(PageHeaderFooterRenderer r) {
        //System.out.println("setPageHeaderAndFooter()...totalPages=" + r.getTotalPageCount());
        AtHeaderFooterElement header
           = new AtHeaderFooterElement(null,  new Font("Times New Roman", Font.BOLD, 20),  Color.decode("#333366"),  SystemColor.white, false, AtHeaderFooterElement.LEFT);
         AtHeaderFooterElement footer
            = new AtHeaderFooterElement("Page " + r.getPageNumber() +"/" + r.getTotalPageCount(), new Font("Arial", Font.PLAIN, 10), Color.decode("#000033"),   SystemColor.white,  false, AtHeaderFooterElement.CENTER);
        if (r.getPageNumber() == 1) {
          header.setStr("Employee Information - Manufacturing Division");
        }
        r.setHeader(header);
        r.setFooter(footer);
      }
    });
    
    

    When printing header and footer it also prints page number if PageNumberPainter.PAGE_NONE is not passed as the argument. Therefore, depending on what you produce as header and footer enable/disable page number printing.

     

    Back to Top


    Programmatically performing zoom in and out

    It is tremendous advantage of using the Smart JPrint APIs that allows you to zoom the output so that you can reduce or increase number of pages drastically. Zoom on the content can be done programatically as well as from its preview window. Zoom if changes causes the Font of the output text to also change with the same proportion. If the content element is an icon, the zoom is also applied to them for resizing. Usually, prople wants to output the same content using less number of pages. For example, a normal output if takes 10 pages, the zoom out might get the output in just as less as 2 pages or as big as 50 pages or more. The preview window automatically does the compression and expansion automatically for you if the a JPrint preview window is displayed.

    Following code segment shows how you can perform zoom on any kind of content you are printing or generating PDF document. Each time you apply zoom using the printerClass.setZoom(double percent) call its getPageable() to test how many pages in the pageable. If further zoom is necessary continue this process in a look until you got the desired number of pages.

    AtGenericPrinter j2eePrinter= new AtGenericPrinter();
    AtBook book = new AtBook();
    //populate the book instance here.
    
    j2eePrinter.setBook(book);
    Pageable pageable = j2eePrinter.getPageable();
    if (pageable.getNumberOfPages() >= 5)  { //just as an example
      j2eePrinter.setZoom(50);
    }
    j2eePrinter.print(book);
    
    

     

    Back to Top


    Drawing a custom border around each JTable cell output

    Smart JPrint by default allows you to draw a border around each cell when you print or PDF generate a JTable swing component using the AtTablePrinter class. The default cell border is 1 pixel thick and the color of the border is the grid color of the JTable.

    In some cases, you might be interested to mark a output JTable cell with a custom cell border. For example, all cell values that are larger than certain value needs to be marked with a thick border and with a red color. You can do so, by setting a AtBorderRenderer to the AtTablePrinter class using its setCellBorderRenderer(AtBorderRenderer borderRenderer) method. Each time a cell border is painted, the drawBorder() interface method is called by the table output renderer program. Inside the drawBorder method you can paint the border using the bounding rectangle of the table cell.

    AtTablePrinter tablePrinter = new AtTablePrinter();
    JTable tableToPrint;
    //populate the JTable.
    tablePrinter.setCellBorderRenderer(new AtBorderRenderer() {
      public void drawBorder(JTable table, Object cellValue, int row, int col, boolean isHeaderCell, Graphics g, Rectangle bbox) {
        Graphics2D g2d = (Graphics2D)g;
        if (!isHeaderCell) {
        g2d.setColor(table.getGridColor());
        g2d.draw(bbox);
        } else {
           g2d.setColor(SystemColor.blue.darker().darker());
           g2d.drawRect(bbox.x, bbox.y, bbox.width, bbox.height-1);
        }
      }
    });
    
    //preview or print
    j2eePrinter.preview(tableToPrint, PageNoPainter.PAGE_NONE, true, frame);
    
    

     

    Back to Top


    Send JPrint generated PDF output to a browser client

    Using JPrint APIs, you can dynamically generate PDF output documents and send it to the bowser client for automically loading into the AcroRead for viewing. The downloaded archive has the sample JSP/Servlet examples that you can follow for your application. You can look at some of the JSP/Servlet examples online.

    Back to Top


    Can I get JSP/Servlet examples that is using Smart JPrint?

    Smart JPrint can be used anywhere in any platform for Java applications. The downloaded archive has JSP/Servlet examples that you can follow for your application. You can look at some of the JSP/Servlet examples online.

    Download the EAR (jprint_webdemo.ear) that has JSP and Servlets working examples.

    What these demo programs does?

    The sample JSP/Servlets dynamically generates A PDF document from the J2EE server and then either shows the PDF to the bowser by opeing it in the browser window, or prompts the user for "SaveAs..." as a PDF document.

    How to deploy the EAR file

    Unzip it under web server's (e.g. Tomcat) "webapps" directory using Java jar or WinZip utility.

    Changes needed after you have unzipped the EAR archive?

  • From both .jsp and .java files replace the LICENSE_KEY with your license key from the SmartJPrint.setLicenseKey("XYZ") statement.
  • Replace the smartjprint_x.y.z.jar with your version of the same jar file in the "lib" directory
  • Recompile the .java files and copy the .class files in the same location where the .java and .class files are located.
  • Restart the web server.
  • How to call the JSP and Servlets

    Open (http://[webhost:port]/smartjprint/index.html) page from a browser. Execute the JSP/Servlet programs using the links in this web page. You can also look at the web.xml under the WEB-INF to understand the servlet mapping.

    Back to Top


    How to print to a user selected printer from your JSP/Servlet/J2EE programs?

    Each time someone is calling your servlet, you have to decide what data you have to print or PDF generate? The client program (usually a browser form) can feed the entire data to your servlet/JSP/Java program or you have to generate the outoput as applicable based on certain user input your program receives.

    In order to let the printing can happen at any printer in the network that are recognized by the server, your servlet/JSP/Java program has to set the network printer to the Smart JPrint printing class before you call its print() methods.

    Follow these steps:

  • Discover all your printers in the network.
  • DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
    PrintRequestAttributeSet pAttrs = new HashPrintRequestAttributeSet();
    PrintService services[] = PrintServiceLookup.lookupPrintServices(flavor,
    pAttrs);
    
  • Display all the printers in the HTML form in the browser or the appropriate client program that is calling this server program.
  • String printerNamesToDisplayToClient[] = new String[services.length];
    for (int i=0; services != null && i < services.length; i++) {
      printerNamesToDisplayToClient[i] = services[i].getName();
    }
    
    //Display to the client for selecting the printer they wants to print the output.
    //May be you can display in the HTML form or some kind of GUI for user to select one.
    
  • Now based on user printer selection, your servet has to find the appropriate PrintService from the services[] array.
  • //Let us say you got the match with idx=1
    PrintService printerToPrint = services[1];
    
  • Set the printer to the Smart JPrint class and print
  • AtGenericPrinter genericPrinter = new AtGenericPrinter();
    genericPrinter.setDefaultPrintService(printerToPrint);
    
    AtBook contentToPrint = new AtBook();
    //Add all that user wants to print to the printer into the AtBook object and print it.
    genericPrinter.print(contentToPrint);
    
    //DONE. There might be syntax with this code segments, chage it as appropriate.
    

    You can always set the default printer where a document can be printed, if there is no user selected printer to be used. The Smart JPrint printer classes sends the output to a default printer connected to the server, if you explicitly do not set a printer.

     

    Back to Top


    How to specify number of copies?

    Smart JPrint lets you print or PDF generate output with a number of copies. Each printer class has the setCopies(int copies) method to let you input the number of copies for output. When generating PDF document, all of the copies goes to the same document. When print to a printer, the number of pages printed is (copies x number of pages in the Pageable).

    AtGenericPrinter printerClass = new AtGenericPrinter();
    AtBook book = new AtBook();
    //populate book.
    printerClass.setCopies(2);
    printerClass.print(book);
    

     

    Back to Top


    Changing preview window size?

    Smart JPrint can show the user a preview window so that the pages can be viewed before sending the output to a printer or generate a PDF document. The preview window size can be controlled from your Java program. Use the setPreviewPaneSize(Dimension newSize) method in the printer class to set the custom preview window size.

    AtDocumentPrinter printerClass = new AtDocumentPrinter();
    JEditorPane editor;
    printerClass.setPreviewPaneSize(new Dimension(790, 900));
    printerClass.preview(editor);
    

     

    Back to Top


    Adding tab, new line, and page break to the J2EE output

    Adding TAB

    It is very simple to use the AtBook class to add lines of text. You can add line break using the \n character as you do for standard output generation from Java System.out.println() methods. You can add a TAB character \t that will put 8 white spaces when rendering the output.

    The example next, has a "\t" (TAB) at the beginning to indent the paragraphs. You can insert a tab character at any position in your string.

    Adding page break

    A page break can be added using the AtPageBreak object or by using the PAGE_BREAK constant defined in the AtElement class.

    AtBook book = new AtBook();
    book.write(new AtStringElement("How to page break?", titleFont, titleColor));
    book.write("\n\n\tBefore this paragraph, there is a page break added. So don't get surprized if " +
    "this heading is always shown at the beginning of a new page leaving empty " +
    "spaces in the previous page. Typically in a J2EE program, you can add lines " +
    		           "of text and put a page break at any position.");
    
    //Try page break
    book.write(AtElement.PAGE_BREAK);
    book.write("\n\n\tA page break can be added using the AtPageBreak object or by " +
      "using the PAGE_BREAK constant defined in the AtElement class.");
    book.write("\n\nAs an example, both of the above two paragraphs has a \"\\t\" (TAB) at the beginning " +
    "to indent the paragraphs. You can insert a tab character at any position " +
    		           "in your string.");
    
    

     

    Back to Top


    How to change or remove preview window buttons?

    In order to change the preview window button properties such as its icon, tooltip, making them visible/invisible, enable/disable, get the AtPreviewFrame reference from the printer class you have created. Get the refernece to one or more of the buttons from the preview window and appropriate mehtods to chage them.

    AtDocumentPrinter docPrinter = new AtDocumentPrinter();
    Component currWindow;
    JTextArea textDocumentEditor;
    //populate the JTextArea.
    docPrinter.preview(textDocumentEditor, PageNoPainter.LOWER_CENTER, false, currWindow);
    
    //
    AtPreviewFrame previewWindow = docPrinter.getPreviewWindow();
    previewWindow.setPreviewButtonVisible(AtPreviewFrame.PDF_BUTTON, false);
    previewWindow.setPreviewButtonTooltipText(AtPreviewFrame.PRINT_BUTTON, "Print selected pages");
    previewWindow.setPreviewButtonImage(AtPreviewFrame.PRINT_BUTTON, myIconImage);
    previewWindow.setPreviewButtonEnabled(AtPreviewFrame.GO_BUTTON, false);
    ....      ....
    
    

     

    Back to Top


    Printing JTable contents using AtTablePrinter class

    It is only couple of lines of code to use the AtTablePrinter class for printing a JTable content. It breaks the rows and columns into multiple pages. If there are large number of columns in the table, page break happens column wise (vertically) as well. How many rows can be printed on a page is decided by the font of the rows and columns in the JTable. Similarly, how many columns can be accomodated in a page is decided by the maximum width of the data elements of the columns and the available width of the print media.

    Create an AtTablePrinter object

    In your class use the next code segment for having handle to the table printer object.

        private AtTablePrinter printer = new AtTablePrinter();

    The constructor do not take any arguments. Once an object is created it can be reused for printing multiple JTable by calling its overloaded print() methods.

    Specify the printing properties for the JTable

    The default setup in the AtTablePrinter object prints the table cells

    However, if you can always change these printing properties by calling the following methods.

    Printing border around the cells

    setDrawCellBorder(boolean cellBorder)   - Draws a cell border around each cell value.

    Repeat header information on each page

    setRepeatHeader(boolean repeatHeader) - Flag indicates that the header information (column names) must be repeated on each page when broken into number of pages.

    Printing header information in bold font

    setHeaderBold(boolean headerBold) - Indicates, if the argument is true then the header information is printed with bold face font. The false argument indicates the header will be printed with a normal font.

    Example: setting header, cell border and repeating header

    The following code segment prints the JTable content where there is no cell border is drawn around each cell value, header information (column  names) are not repeated on each page other than the very first set of pages (more than one page if splitted vertically). The header information is printed with bold face font.

    private AtTablePrinter printer = new AtTablePrinter();

    printer.setDrawCellBorder(false);
    printer.setRepeatHeader(false);
    printer.setHeaderBold(true);

    Print it

    Simply call one of the many print methods in the AtTablePrinter class. Following is the simplest print() method prints the content to a printer.

    JTable table;
    ....            
    printer.print(table, PageNoPainter.LOWER_CENTER);

    The second argument is the location where the page bumber to be printed.

    Back to Top


    Things to consider when printing JTable with custom cell renderer

    Your JTable might display text data in its cells or use custom cell renderers of any kind for different columns and cells. Smart JPrint is smart enough to print both types of cells by breaking the table rows and columns into multiple pages automatically.

    However, there are some issues you must know when you try to print a JTable with any kind of custom cell renderers. The usual problem can be faced is that the exact size of the cell renderer component can not be known. For example, if you are using a JLabel renderer that usually truncates the String with "..." at its end if the column width is not sufficient enough to display the complete String. When Smart JPrint tries to print such cell renderers, the width/height of the cell retruned by the renderer perhaps incorrect. As a result, when printed, the output might look smaller or larger than the expected cell size.

    The "Smart JPrint" address this problem by allowing you to implement a PrintableCell interface for your custom cell renderer. The PrintableCell interface has two methods:

  • int getCellWidth()
  • int getCellHeight()
  • and
  • void draw(Graphics g)


  • The first two APIs is used in order to always return a correct width and height irrespective of the current cell width and height seen in the UI. The Smart JPrint prints the cell correctly even if user has resized the columns to a minimum width or made it wider than the normal width. The draw(Graphics) method is used by the JPrint to draw the cell objects when printing.

    To see how you can implement the PrintableCell interface, look at the PrintCustomCellTableDemo3.java

    Back to Top


    How to remove, change, enable/disable the buttons in the preview window?

    Just after the call to the preview() method of the printing classes, change the button icons, hide, chage tooltip etc. using the methods defined in the AtPreviewFrame class shown next:

    printer.preview(thingToPrint, PageNoPainter.LOWER_CENTER, true);
    AtPreviewFrame previewFrame = printer.getPreviewWindow();
    previewFrame.setPreviewButtonVisible(AtPreviewFrame.PDF_BUTTON, false);
    previewFrame.setPreviewButtonTooltipText(AtPreviewFrame.PRINT_BUTTON, "Print the pages");
    previewFrame.setPreviewButtonImage(AtPreviewFrame.PRINT_BUTTON, );
    previewFrame.setPreviewButtonEnabled(AtPreviewFrame.GO_BUTTON, false);

    The above code segment does the following after getting the preview frame reference.

  • sets the preview window default PDF button invisible.
  • changes the default tooltip text for the default 'Print' button.
  • changes the icon of the default print button.
  • disables the go button that allows the user to type a page number and press it to show that page.
  • Back to Top


    Print JTextPane, JEditorPane, and JTextArea contents using AtDocumentPrinter

    When printing any of the JTextField, JTextArea, JTextPane, and JEditorPane components, you can pass the component directly to the print() or the preview() methods in the AtDocumentPrinter object.

    Create an AtDocumentPrinter object

    AtDocumentPrinter docPrinter = new AtDocumentPrinter();

    The constructor has no arguments to pass. The print method takes the JTextComponent (any of its derived class such as JTextField, JTextArea, JTextPane, JEditorPane etc.) as the first argument, and the page number location as the second argument.

    Printing

    JTextComponent textComponent = new JTextPane();
    ....
    docPrinter.print(textComponent, PageNoPainter.LOWER_RIGHT);

    Pass the JTextComponent reference to the print method for printing. It uses the JTextComponent Document model for getting the data elements, its fonts, styles and more before rendering to the printer.

    Previewing

    Preview is similar to the print method call. All you do is to call the AtDocumentPrinter's preview method and pass the same arguments. In addition, it takes a third argument boolean true or false indicating whether you want to show the setup dialog for the user to specify the page margins, and page orientation etc.

    docPrinter.preview(textComponent, PageNoPainter.LOWER_RIGHT, true);

    If the third argument is "true" then a page setup dialog is displayed for the user to setup the page margins and decide the media orientation. The "false" argument will cause no page setup dialog to show up.

    Back to Top