jOpenDocument


A pure Java library for OASIS Open Document files manipulation



Display and print a spreadsheet

This section shows how to display and print a spreadsheet. Everything is done in Java and does not require any external application.

Developpers having used OpenOffice.org and UNO to do this job will be happy to find here a faster and easier approach to display and print document.

 

There a 2 ways to print a spreadsheet. You can allow the user to print directly from the built-in viewer or manage the entire process programmaticaly.

First method: add the print fonctionnality to the viewer



  // Load the spreadsheet.
  final OpenDocument doc = new OpenDocument();
  doc.loadFrom("template/invoice.ods");

  // Show time !
  final JFrame mainFrame = new JFrame("Viewer");
  DefaultDocumentPrinter printer = new DefaultDocumentPrinter();
    
  ODSViewerPanel viewerPanel = new ODSViewerPanel(doc, printer, true);

  mainFrame.setContentPane(viewerPanel);
  mainFrame.pack();
  mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  mainFrame.setLocation(1010);
  mainFrame.setVisible(true);
Java2html

A print button appears in the toolbar:

The DefaultDocumentPrinter is very basic on only try to fit the document on the printed page.
You can easily change this behaviour by implementing the DocumentPrinter interface.

Second method: use the DocumentPrinter



  // Load the spreadsheet.
  final OpenDocument doc = new OpenDocument();
  doc.loadFrom("template/invoice.ods");

  // Print !
  DefaultDocumentPrinter printer = new DefaultDocumentPrinter();
  printer.print(doc);
Java2html

The DefaultDocumentPrinter will open a print dialog. If you preffer to print without user interaction, just look a the ODTPrinter class and remove the call to printJob.printDialog(). If you are familiar with the Java printing API, you will be able to create quickly your own DocumentPrinter.