IText - how do I create a multipage PDF?

Can anyone tell me how to modify the code below so that if Component c has more content than one A4 page, all content is output to a multipage PDF.
Thanks
import java.io.FileOutputStream;
import java.io.IOException;
import java.awt.*;
import com.lowagie.text.Document;
import com.lowagie.text.*;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
public class PrintPDF {
     Component c = null;
     String documentName = null;
     public PrintPDF(Component c, String name){
          this.c = c;
          this.documentName = name + ".pdf";
          Document document = new Document(PageSize.A4,36,36,36,36);
          try {
               PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream documentName));
               document.open();
               PdfContentByte cb = writer.getDirectContent();
               PdfTemplate tp = cb.createTemplate(500, 500);
               Graphics2D g2 = tp.createGraphics(500, 500);
               c.paint(g2);
               g2.dispose();
               cb.addTemplate(tp, 30, 300);
          } catch (Exception e) {
               System.err.println(e.getMessage());
          document.close();
}

Here is the working code for multiple page PDF for a JComponent
import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JToolBar;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.FileOutputStream;
public class MultiplePagePdf extends JPanel implements Printable
    private JTable table;
    public MultiplePagePdf()
        table = new JTable(100, 10)
            public Object getValueAt(int row, int column)
                return String.valueOf(row + ", " + column);
        JToolBar tb = new JToolBar();
        JButton printButton = new JButton("Print Table");
        printButton.addActionListener(new ActionListener()
            public void actionPerformed(ActionEvent e)
                PrinterJob printJob = PrinterJob.getPrinterJob();
                if (printJob.printDialog()) {
                    try {
                        printJob.setPrintable(MultiplePagePdf.this);
                        printJob.print();
                    } catch (PrinterException ex) {
                        ex.printStackTrace();
        tb.add(printButton);
        tb.addSeparator();
        JButton saveButton = new JButton("Save Table");
        saveButton.addActionListener(new ActionListener()
            public void actionPerformed(ActionEvent e)
                saveAsPdf();
        tb.add(saveButton);
        tb.addSeparator();
        setLayout(new BorderLayout());
        add(tb, BorderLayout.NORTH);
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);
     *  this method is copied from http://java.sun.com/developer/onlineTraining/Programming/JDCBook/advprint.html
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException
        Graphics2D g2 = (Graphics2D) g;
        g2.setColor(Color.black);
        int fontHeight = g2.getFontMetrics().getHeight();
        int fontDesent = g2.getFontMetrics().getDescent();
        //leave room for page number
        double pageHeight = pageFormat.getImageableHeight() - fontHeight;
        double pageWidth = pageFormat.getImageableWidth();
        double tableWidth = (double) table.getColumnModel().getTotalColumnWidth();
        double scale = 1;
        if (tableWidth >= pageWidth) {
            scale = pageWidth / tableWidth;
        double headerHeightOnPage = table.getTableHeader().getHeight() * scale;
        double tableWidthOnPage = tableWidth * scale;
        double oneRowHeight = table.getRowHeight() * scale;
        int numRowsOnAPage = (int) ((pageHeight - headerHeightOnPage) / oneRowHeight);
        double pageHeightForTable = oneRowHeight * numRowsOnAPage;
        int totalNumPages = (int) Math.ceil(((double) table.getRowCount()) / numRowsOnAPage);
        if (pageIndex >= totalNumPages) {
            return NO_SUCH_PAGE;
        g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
        //bottom center
        String pageNumber = "Page: " + (pageIndex + 1) + " of " + totalNumPages;
        int width = g2.getFontMetrics().stringWidth(pageNumber);
        g2.drawString(pageNumber, (int) (pageWidth - width) / 2, (int) (pageHeight + fontHeight - fontDesent));
        // Paint the header at the top
        g2.translate(0f, 0f);
        g2.translate(0f, -headerHeightOnPage);
        g2.setClip(0, 0,
                (int) Math.ceil(tableWidthOnPage),
                (int) Math.ceil(headerHeightOnPage));
        g2.scale(scale, scale);
        table.getTableHeader().paint(g2);
        g2.scale(1 / scale, 1 / scale);
        g2.translate(0f, headerHeightOnPage);
        g2.translate(0f, -pageIndex * pageHeightForTable);
        //If this piece of the table is smaller
        //than the size available,
        //clip to the appropriate bounds.
        if (pageIndex + 1 == totalNumPages) {
            int lastRowPrinted = numRowsOnAPage * pageIndex;
            int numRowsLeft = table.getRowCount()
                    - lastRowPrinted;
            g2.setClip(0,
                    (int) (pageHeightForTable * pageIndex),
                    (int) Math.ceil(tableWidthOnPage),
                    (int) Math.ceil(oneRowHeight *
                            numRowsLeft));
        //else clip to the entire area available.
        else {
            g2.setClip(0,
                    (int) (pageHeightForTable * pageIndex),
                    (int) Math.ceil(tableWidthOnPage),
                    (int) Math.ceil(pageHeightForTable));
        g2.scale(scale, scale);
        table.paint(g2);
        return Printable.PAGE_EXISTS;
     * This is where the table is saved as pdf
    private void saveAsPdf()
        Document document = new Document();
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("/tmp/table.pdf"));
            document.open();
            PdfContentByte cb = writer.getDirectContent();
            PrinterJob printJob = PrinterJob.getPrinterJob();
            PageFormat pageFormat = printJob.defaultPage();
            printJob.cancel();
            float width = ((float) pageFormat.getWidth());
            float height = ((float) pageFormat.getHeight());
            PdfTemplate tp;
            Graphics2D g2;
            // Assuming that the number of pages would be 3, You can calculate this same way it is calculated
            // in print (Graphics g, PageFormat pageFormat, int pageIndex) method
            int numberOfPages = 3;
            for (int i = 0; i < numberOfPages; i++) {
                tp = cb.createTemplate(width, height);
                g2 = tp.createGraphicsShapes(width, height);
                this.print(g2, pageFormat, i);
                g2.dispose();
                cb.addTemplate(tp, 0, 0);
                document.newPage();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        document.close();
    public static void main(String[] args)
        JFrame frame = new JFrame("Multiple page pdf");
        frame.getContentPane().add(new MultiplePagePdf());
        frame.pack();
        frame.setVisible(true);
}Edited by: ms_rahman on Feb 24, 2008 4:09 PM

Similar Messages

  • Creating a multipage pdf in photoshop CS4

    I've just upgraded from CS1 to CS4, and previously you could create a multipage PDF easily under the File>Automate menu. So how do you do that in CS4? The feature has been moved somewhere. I dont want two seperate A4's I want to learn how to create one document consisting of 2 pages.
    Thanks
    AC

    I most certainly would like to see the output to multi-page pdf feature re-included back into the file menu. For generic brochure type jobs, through to concept art presentations, and (Game) design documents, I really appreciated having that feature. It worked. Smooth.
    Bridge on the other hand, is shovelware. It lasts 3-4 seconds before locking up indefinately, and its a product of Adobe's ability to make fancy applications that dont really do anything useful, its NOT my workflow, and nor do I want it to be. I don't see the point in starting up another application, to do something that was always done well, from 2 maybe 3 clicks in the file menu.
    I really dont expect to swallow the cost of upgrades to find that I've had essential tools removed, and substituted for the joke that is "Bridge".
    Isn't this obvious? If its not broken don't fix it.
    AC

  • How do I create an interactive PDF file with variable data

    We would like to basically do a 'mail merge' of our list of customers with an interactive PDF file (including videos, menus, etc - not just form fill out and web links) to create a single PDF file that contains multiple mail pieces ... one for each customer ... with each mail piece being customized for that customer.  Customizations would include different greetings (Dear Bob, Dear Dana, etc), as well as different charts based on data unique to the customer, different photographs, etc.
    I've seen that InDesign and Acrobat Professional can be used to create an interactive PDF (such as from http://tv.adobe.com/watch/ask-the-adobe-ones/14-calling-rufus-about-interactive-pdf-making).  However I don't understand how I can insert data from a database, csv file, excel file etc into the PDF file so that each page, or each set of pages, within the PDF can be customized.
    Can anyone point me to a tool to use for this?
    Thanks,
    Bob Kendall

    For that kind of volume and unattended operation, you want InDesign Server – which is the server/high volume edition of INDD.
    From: Adobe Forums <[email protected]<mailto:[email protected]>>
    Reply-To: "[email protected]<mailto:[email protected]>" <[email protected]<mailto:[email protected]>>
    Date: Thu, 3 Nov 2011 06:58:07 -0700
    To: Leonard Rosenthol <[email protected]<mailto:[email protected]>>
    Subject: How do I create an interactive PDF file with variable data
    Re: How do I create an interactive PDF file with variable data
    created by Ti26E31DSxxx<http://forums.adobe.com/people/Ti26E31DSxxx> in PDF Language and Specifications - View the full discussion<http://forums.adobe.com/message/4005459#4005459

  • How can you create a writable PDF document from a PPT presentation ?

    How can you create a writable PDF document from a PPT presentation ? Upper part with the image , lower part with a free space in order to take notes for students during presentation or course.
    Thanks.
    B

    You can make a PDF file out of you notes and handouts but using the Adobe PDF printer.
    Open your PowerPoint Document then go to “File” “Print”
    Select ‘Adobe PDF” Printer
    Under slides, select which way you want to print. Note it will not print to a printer but to a PDF file.
    After then go into printer Properties and Setup PDF properties, do the following: (see second image below)
    Default: PDF/A 1-b
    Adobe Security: none (change as needed)
    Adobe Output folder: Prompt for Adobe file name
    Adobe Page size: Letter (change as needed)
    Check the following check boxes
    View Adobe PDf Results,
    Add Document Information,
    Rely on system fonts only,
    Delete Log files for successful jobs.
    Select OK
    A pop will ask you where you want to save the document. The file extension should be PDF. After giving the file name select okay and the file should popup as a PDF. Down side is if you want to speaker notes included then you will have to do another file, like wise with just screen shots then combine into one PDF document.
    I used Acrobat IX Pro. So to do this you need Acrobat IX or X Pro.
    Hope this will help.
    Tiger26

  • How do I create a single PDF Portfolio from an Outlook 2011 email with multiple non-pdf attachments?

    How do I create a single PDF Portfolio from an Outlook 2011 email with multiple non-pdf attachments?
    Email has 3 attachments--some are not pdf. I'd like all three converted into pdf files along with the email itself, and all appear in the email's pdf portfolio.

    I would also like an answer to this question. 
    I am trying to convert an Outlook email to a PDF, then all attachment are appended to the PDF as pages instead of attachments. 

  • How Can i Make A Multipage Pdf in Cs5

    Hi i was using Photoshop Cs3 in work  and they upgraded all the photoshop versions to CS5 . Now i can't find where i can create a multipage pdf. I was using the pdf tool so often it's important for me. I'm stuck thanks for the helps.
    Jeffrey Cole
    www.coookguzel.com

    Output to PDF from Bridge.

  • I have a Mac and Acrobat Pro, how do I create an interactive PDF file?

    I have  a Mac and Acrobat Pro, how do I create an interactive PDF File?

    Hi 528!!,
    Here's some information about adding multimedia to your PDF files: Acrobat Help | Multimedia and 3D models
    Please let us know how it goes!
    Best,
    Sara

  • How do I open a multipage pdf in Illlustrator cs6

    Hopefull someone can help me to stop banging my head against a brick wall....
    How do I open a multipage pdf in Illlustrator cs6?
    many, many thanks

    Thanks TSN
    It's not a complicated pdf, just 15 pages of it. If I have to individually open each page to alter one word on each, it probably takes the profit margin out of the job.
    It seems such a basic thing to be able to do, there have been many posts on the internet looking for a solution, yet they won't do it. Why has it not been included?
    Can I open multiple pages in InDesign? I never use it but if it's easier...
    G

  • How can I generate a multipage PDF of a tab in a Numbers document?

    I am using Numbers for iPad to write down meeting minutes and spread them as PDF documents.
    One Numbers document contains for one project for every meeting one tab with the minutes.
    Formerly Numbers generated for long tabs several pages. Like in the print dialogue. Now this
    isn't possibel anymore.
    Is there any way to generate a multipage PDF of a long tab in a Numbers document?

    Dear Spanky D. Rascal
    Yes I want to generate a PDF from the iPad. Formerly it was possible to generate a multipage PDF directly from Numbers with the "open in" dialogue. That was very easy eventhough it wasn't possible to choose just one tab for PDFing.
    I have several PDF / Printing Apps on the iPad like Quick Print, Printer Pro or PDF it All. I didn't succeed in creating a multipage PDF with one of these.
    On the Mac version it ist still possible to create multipage PDFs with the printing dialogue for instance. But
    I want to do it with the iPad.
    And finally: I am using version 2.1 (1129)

  • How do I create a new PDF file?

    How do I create a PDF file? All I'm trying to do is open a blank file to start creating a pdf.....

    Hi rainbowi62203236,
    You can use either Adobe PDF Pack or Acrobat to create a PDF file. If you don't have Acrobat, please feel free to give it a try. You can download a 30-day trial from http://www.adobe.com/products/acrobat.html.
    Best,
    Sara

  • Creating a multipage PDF that prints 2 booklets side by side?

    Hi I am a designer with NO pre-press experience and I need some help!
    I am trying to print a booklet that is set at 8.5 x 7 as a 2 up document on 8.5 x14 paper. My problem is that I don't want the booklets to print consecutive pages (right now they would print 1,2 3,4 5,6 etc.) I want them to print side by side so that when the sheets are cut we would have 2 completed and collated books.
    I know that I could just duplicate each page and print that, but I am wondering if there is a quicker way to make this happen? We have over 100 different multipage PDFs to print so I'm looking for a lean way to get this done.
    Is this possible? Do I need to purchase pagination software?

    When I need to do this I generally make a file set up as a single page (8.5 x 7, in this case) for easy design, then create a second, non-facing doc at two-up size (8.5 x 14) and place the pages from the first file int the second tow times so I have two copies per page. I use the Multi-page importer script for this: InDesignSecrets » Blog Archive » Zanelli Releases MultiPageImporter for Importing both PDF and INDD Files

  • How do I create a continuous PDF from another application?

    I need help creating a continuous PDF from a Quark Xpress document.
    I was able to achieve this on Photoshop once before (couple months back)
    and now I cannot remember how I did it.

    I think you made a wrong turn somewhere. This is the photoshop Elements forum. If you're asking about full photoshop, you need to go to the relevant forum here:
    http://forums.adobe.com/community/photoshop/photoshop_windows
    http://forums.adobe.com/community/photoshop/photoshop_macintosh
    Good luck!

  • How do I create a paginated pdf from Indd?

    Hello,
    Can somebody please tell me how to create a paginated pdf from Indesign CC? it used to be so simple to "print a booklet" as a ps, and then distill it. Now I can't seem to do that anymore

    You don't really need to create a paginated PDF if you're sending to a printers to output for you - they should be doing that portion!
    If you need a print out for yourself then Print Booklet should be fine.
    If you need a PDF of it you should be able to get Acrobat from your CC subscription and then that should add the PDF as a printer in your Printer list.
    It's not ideal to "print to pdf" and I don't recommend it as a workflow.
    Instead -  you can use File>Export and choose the right PDF settings for you.
    In Acrobat - you can choose to print a booklet.

  • How do you create a reviseable .pdf?

    I have been directed to file a "revisable .pdf" in a court case (I'm an attorney, not a defendant!).  Can someone please explain how to create a revisable .pdf?

    That depends. What do you mean by "revisable"?
    Typically, you cannot revise or edit pdf files using Adobe Reader but you can create form fields using Adobe Acrobat that people can fill in and change. Is that what you mean?

  • How do I create an accessible PDF for Thesaurus with many chapters, from InDesign CS 5.5 and Acrobat

    Hi folks,
    I have redesigned a Thesaurus (controlled vocabulary for an Agency's archives) in InDesign CS 5.5. I am now preparing an accessible PDF from the many files (using a Book created in InDesign). The front cover, front matter and back cover are not part of the Book, to keep the page numbering simple.
    The Book includes two main sections, an Alphabetical display and a Hierarchical display of terms and their relations. I created chapters per alphabet listings, i.e. Alphabetical Display A, B, C, etc. So there are over 50 chapters, including cover, front matter, etc.
    I've successfully made the front cover and front matter PDFs after viewing videos here: http://tv.adobe.com/watch/accessibility-adobe/preparing-indesign-files-for-accessibility/ and downloading and using this recommended Action for Acrobat: InDesign CS5_5 Accessibility Touchup.sequ
    Several questions specific to this project don't seem to be addressed in the videos, however.
    First, I'd like to know if I can create an accessible PDF using the Book function > Export Book to PDF. Or do I need to make a PDF per chapter? The book has over 50 chapters (by alphabet, twice), so creating them one by one will take a lot more time, but I'll do it if that's the best practice.
    After creating the PDFs, if I use (in Acrobat): Create > Combine Files into PDF to make one full PDF (over 600 pages BTW), will the final PDF retain accessibility settings? Do I need to run the Accessibility Report again for the combined PDF?
    I used InTools.com Power Headers plugin to add a page header that automatically shows the new first term used per page. So, one chapter (with Chapter Title as H1) will have a different page header (which will be H2) per page, however the text flows through the whole chapter. I don't see where to add the page headers to the Article Window in InDesign. Do I add in this order: H1, H2, text (for whole chapter), H2, H2, H2, etc. Will I need to work on the PDF in Acrobat, where pages will be shown, in order to get the correct H2 with the correct text on the page? Am I missing something?
    Will I have any issues with Bookmarks that requires a specific workflow?
    I think that's about it, though I might run into more questions as I progress through the project.
    Thanks, Marilyn

    I understand why you need updated running headers in your book. To a sighted reader these serve as a guide to where you are and help you find things quickly.  In addition, if you are exporting your data to XML or HTML from the tagged PDF it would also be important to have these in the proper location. 
    But for accessibility purposes, it doesn't have to be there because the screen reader reads everything in linear order, line by line.  No one is looking at the page.  A user listening to the screen reader read the page is going to hear this heading, just before the actual word itself. So they will hear the first word on the page twice.  It's not the end of the world if it's there, but such headings are not necessary for accessibility unless they are not repetitive and contain information that is not otherwise available.
    So I would say, fine if you need them or want them there, it's just one word. 
    I think you should try exporting your book to PDF (or even just a chapter of the book) and look at the tags panel in Acrobat to see if you are getting the result you want.  I can't tell you exactly what you should do to get those results, you are using a plug-in I don't have. 
    I can tell you I didn't have to add the headers to any article at all, they just automatically export if the other articles in the file are added and you don't select the header style option "not for export as XML."
    You may not experience the same results with your plug-in, but I think it will probably work the same way. 
    Give it a try and best of luck.

Maybe you are looking for

  • After updating to 8.1 unable to play audio via bluetooth devices!

    While ysing windows 8, i had no such problem. but after i updated it, i am unable to play music via bluetooth devices. sometimes it gives error message "DRIVER ERROR", while other time it gives no error message while it doesn't work. What should i do

  • Aging Query with Project

    Hi all Is it possible to change the current BP Project to show INV1.Project instead? USE [SBODemoSG] GO /****** Object:  StoredProcedure [dbo].[ARAgingByCustomerNameLC]    Script Date: 08/06/2014 14:03:49 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENT

  • HTML snippet not working

    I have multiple sites that I've created with iWeb and have used the program for years. However, in an attempt to update one of my sites I encountered a road block. I was trying to embed html from my Vimeo site using the html snippet function but the

  • How do i claim free mountain lion

    How do I download the free app for my new mac?

  • Save as quicktime file so quicktime player can be used after right-click

    Hey, I'm adding short .aiff's to a site for people to right click and save. -I'm making the .aiff using logic express. -Bouncing to desktop. -Changing file to "open using quicktime player" which makes the file look like a quicktime file with the big