September 04, 2010, 04:11:31 AM *
Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
  Home Help Media Affiliates Login Register  
Pages: [1]   Go Down
  Print  
Author Topic: Create a multipage PDF using iText  (Read 790 times)
0 Members and 1 Guest are viewing this topic.
G. Ritardo
Member
*
*

Reputation: 0
Offline Offline
Posts: 53
Referrals: 0

Awards
« on: May 21, 2009, 09:22:21 AM »

Code
GeSHi (java):
  1. import com.lowagie.text.Document;
  2. import com.lowagie.text.pdf.PdfContentByte;
  3. import com.lowagie.text.pdf.PdfTemplate;
  4. import com.lowagie.text.pdf.PdfWriter;
  5.  
  6. import javax.swing.JButton;
  7. import javax.swing.JFrame;
  8. import javax.swing.JPanel;
  9. import javax.swing.JScrollPane;
  10. import javax.swing.JTable;
  11. import javax.swing.JToolBar;
  12. import java.awt.BorderLayout;
  13. import java.awt.Color;
  14. import java.awt.Graphics;
  15. import java.awt.Graphics2D;
  16. import java.awt.event.ActionEvent;
  17. import java.awt.event.ActionListener;
  18. import java.awt.print.PageFormat;
  19. import java.awt.print.Printable;
  20. import java.awt.print.PrinterException;
  21. import java.awt.print.PrinterJob;
  22. import java.io.FileOutputStream;
  23.  
  24. public class MultiplePagePdf extends JPanel implements Printable
  25. {
  26.    private JTable table;
  27.  
  28.    public MultiplePagePdf()
  29.    {
  30.        table = new JTable(100, 10)
  31.        {
  32.            public Object getValueAt(int row, int column)
  33.            {
  34.                return String.valueOf(row + ", " + column);
  35.            }
  36.        };
  37.  
  38.        JToolBar tb = new JToolBar();
  39.        JButton printButton = new JButton("Print Table");
  40.        printButton.addActionListener(new ActionListener()
  41.        {
  42.            public void actionPerformed(ActionEvent e)
  43.            {
  44.                PrinterJob printJob = PrinterJob.getPrinterJob();
  45.                if (printJob.printDialog()) {
  46.                    try {
  47.                        printJob.setPrintable(MultiplePagePdf.this);
  48.                        printJob.print();
  49.                    } catch (PrinterException ex) {
  50.                        ex.printStackTrace();
  51.                    }
  52.                }
  53.            }
  54.        });
  55.  
  56.        tb.add(printButton);
  57.        tb.addSeparator();
  58.  
  59.        JButton saveButton = new JButton("Save Table");
  60.        saveButton.addActionListener(new ActionListener()
  61.        {
  62.            public void actionPerformed(ActionEvent e)
  63.            {
  64.                saveAsPdf();
  65.  
  66.            }
  67.  
  68.        });
  69.  
  70.        tb.add(saveButton);
  71.        tb.addSeparator();
  72.  
  73.  
  74.        setLayout(new BorderLayout());
  75.        add(tb, BorderLayout.NORTH);
  76.        JScrollPane scrollPane = new JScrollPane(table);
  77.        add(scrollPane, BorderLayout.CENTER);
  78.  
  79.    }
  80.  
  81.    /**
  82.      *  this method is copied from http://java.sun.com/developer/onlineTraining/Programming/JDCBook/advprint.html
  83.      */
  84.    public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException
  85.    {
  86.        Graphics2D g2 = (Graphics2D) g;
  87.        g2.setColor(Color.black);
  88.  
  89.        int fontHeight = g2.getFontMetrics().getHeight();
  90.        int fontDesent = g2.getFontMetrics().getDescent();
  91.  
  92.        //leave room for page number
  93.        double pageHeight = pageFormat.getImageableHeight() - fontHeight;
  94.        double pageWidth = pageFormat.getImageableWidth();
  95.        double tableWidth = (double) table.getColumnModel().getTotalColumnWidth();
  96.        double scale = 1;
  97.        if (tableWidth >= pageWidth) {
  98.            scale = pageWidth / tableWidth;
  99.        }
  100.  
  101.        double headerHeightOnPage = table.getTableHeader().getHeight() * scale;
  102.        double tableWidthOnPage = tableWidth * scale;
  103.  
  104.        double oneRowHeight = table.getRowHeight() * scale;
  105.        int numRowsOnAPage = (int) ((pageHeight - headerHeightOnPage) / oneRowHeight);
  106.        double pageHeightForTable = oneRowHeight * numRowsOnAPage;
  107.        int totalNumPages = (int) Math.ceil(((double) table.getRowCount()) / numRowsOnAPage);
  108.        if (pageIndex >= totalNumPages) {
  109.            return NO_SUCH_PAGE;
  110.        }
  111.  
  112.        g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
  113.        //bottom center
  114.        String pageNumber = "Page: " + (pageIndex + 1) + " of " + totalNumPages;
  115.        int width = g2.getFontMetrics().stringWidth(pageNumber);
  116.        g2.drawString(pageNumber, (int) (pageWidth - width) / 2, (int) (pageHeight + fontHeight - fontDesent));
  117. //
  118.        // Paint the header at the top
  119.        g2.translate(0f, 0f);
  120.        g2.translate(0f, -headerHeightOnPage);
  121.        g2.setClip(0, 0,
  122.                (int) Math.ceil(tableWidthOnPage),
  123.                (int) Math.ceil(headerHeightOnPage));
  124.        g2.scale(scale, scale);
  125.        table.getTableHeader().paint(g2);
  126.  
  127.        g2.scale(1 / scale, 1 / scale);
  128.        g2.translate(0f, headerHeightOnPage);
  129.        g2.translate(0f, -pageIndex * pageHeightForTable);
  130.  
  131.        //If this piece of the table is smaller
  132.        //than the size available,
  133.        //clip to the appropriate bounds.
  134.        if (pageIndex + 1 == totalNumPages) {
  135.            int lastRowPrinted = numRowsOnAPage * pageIndex;
  136.            int numRowsLeft = table.getRowCount()
  137.                    - lastRowPrinted;
  138.            g2.setClip(0,
  139.                    (int) (pageHeightForTable * pageIndex),
  140.                    (int) Math.ceil(tableWidthOnPage),
  141.                    (int) Math.ceil(oneRowHeight *
  142.                            numRowsLeft));
  143.        }
  144.        //else clip to the entire area available.
  145.        else {
  146.            g2.setClip(0,
  147.                    (int) (pageHeightForTable * pageIndex),
  148.                    (int) Math.ceil(tableWidthOnPage),
  149.                    (int) Math.ceil(pageHeightForTable));
  150.        }
  151.  
  152.        g2.scale(scale, scale);
  153.        table.paint(g2);
  154.  
  155.        return Printable.PAGE_EXISTS;
  156.    }
  157.  
  158.    /**
  159.      * This is where the table is saved as pdf
  160.      */
  161.    private void saveAsPdf()
  162.    {
  163.        Document document = new Document();
  164.        try {
  165.  
  166.            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("/tmp/table.pdf"));
  167.            document.open();
  168.            PdfContentByte cb = writer.getDirectContent();
  169.            PrinterJob printJob = PrinterJob.getPrinterJob();
  170.            PageFormat pageFormat = printJob.defaultPage();
  171.            printJob.cancel();
  172.  
  173.            float width = ((float) pageFormat.getWidth());
  174.            float height = ((float) pageFormat.getHeight());
  175.  
  176.            PdfTemplate tp;
  177.            Graphics2D g2;
  178.            // Assuming that the number of pages would be 3, You can calculate this same way it is calculated
  179.            // in print (Graphics g, PageFormat pageFormat, int pageIndex) method
  180.            int numberOfPages = 3;
  181.            for (int i = 0; i < numberOfPages; i++) {
  182.                tp = cb.createTemplate(width, height);
  183.                g2 = tp.createGraphicsShapes(width, height);
  184.                this.print(g2, pageFormat, i);
  185.                g2.dispose();
  186.                cb.addTemplate(tp, 0, 0);
  187.                document.newPage();
  188.            }
  189.  
  190.        } catch (Exception e) {
  191.            System.err.println(e.getMessage());
  192.        }
  193.        document.close();
  194.    }
  195.  
  196.  
  197.    public static void main(String[] args)
  198.    {
  199.        JFrame frame = new JFrame("Multiple page pdf");
  200.        frame.getContentPane().add(new MultiplePagePdf());
  201.        frame.pack();
  202.        frame.setVisible(true);
  203.    }
  204.  
  205. }
  206.  
Created by GeSHI 1.0.7.20
Logged
My Contributions

Onzin > Email address of gaylords


Founder of www.Retardation-Foundation.com :: A community for retarded people!? Powered by admin Gaylord Ritardo.
Javaforums.net :: a community about Java software development.
« on: May 21, 2009, 09:22:21 AM »

Your Ad Here
 Logged
Pages: [1]   Go Up
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.10 | SMF © 2006-2009, Simple Machines LLC
TinyPortal v0.9.8 © Bloc
Valid XHTML 1.0! Valid CSS!
Page created in 0.358 seconds with 33 queries.

Google visited last this page Yesterday at 06:57:59 PM