Example usage for com.lowagie.text Document newPage

List of usage examples for com.lowagie.text Document newPage

Introduction

In this page you can find the example usage for com.lowagie.text Document newPage.

Prototype


public boolean newPage() 

Source Link

Document

Signals that an new page has to be started.

Usage

From source file:s2s.luna.reports.Stampa_documento.java

License:GNU General Public License

@SuppressWarnings("CallToThreadDumpStack")
private boolean addPDF(String titolo, byte[] fileContent, Document document, PdfWriter writer) {
    try {//from   w  ww .  j av a2  s.  c  o  m
        // Inizializzo il contenitore del pdf da importare.
        PdfContentByte cb = writer.getDirectContent();

        // Inizializzo la variabile dove appogger (una alla volta)
        // le pagine del pdf da importare.
        PdfImportedPage page;

        // Apro in lettura il pdf da importare.
        PdfReader pdfReader = new PdfReader(fileContent);

        // Ne determino il numero di pagine totali.
        int pdfPageNumber = pdfReader.getNumberOfPages();

        // Inzializzo il contatore delle pagine.
        int pageOfCurrentReaderPDF = 1;

        // Per ogni pagina...
        while (pageOfCurrentReaderPDF <= pdfPageNumber) {
            // Creo una nuova pagina vuota sul pdf di destinazione.
            document.newPage();
            // Estraggo la pagina dal pdf da importare.
            page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
            // Coverto la pagina in un immagine.
            Image pageImg = Image.getInstance(page);
            // Aggiungo la pagina estratta al pdf di destinazione, ruotandola se necessario.
            PdfPTable table = new PdfPTable(1);
            PdfPCell defaultCell = table.getDefaultCell();
            defaultCell.setRotation(-pdfReader.getPageRotation(pageOfCurrentReaderPDF));
            defaultCell.setBorder(Rectangle.NO_BORDER);
            table.addCell(pageImg);
            document.add(table);
            // Incremento il contatore delle pagine
            pageOfCurrentReaderPDF++;
        }
        return true;
    } catch (Exception ex) {
        // Eccezione silenziosa.
        // Gestisce il caso in cui si verifica un errore non previsto
        ex.printStackTrace();
        return false;
    }
}

From source file:se.idega.idegaweb.commune.school.business.StudentAddressLabelsWriter.java

License:Open Source License

/**
 * Creates PDF address labels for the specified school classes.
 *///w ww .  j a va2 s  .c  o  m
protected MemoryFileBuffer getPDFBuffer(IWApplicationContext iwac, Collection receivers) throws Exception {
    this.business = getSchoolCommuneBusiness(iwac);
    this.userBusiness = getCommuneUserBusiness(iwac);

    IWResourceBundle iwrb = iwac.getIWMainApplication().getBundle(CommuneBlock.IW_BUNDLE_IDENTIFIER)
            .getResourceBundle(iwac.getApplicationSettings().getApplicationLocale());

    MemoryFileBuffer buffer = new MemoryFileBuffer();
    MemoryOutputStream mos = new MemoryOutputStream(buffer);

    Document document = new Document(PageSize.A4, 50, 50, 50, 50);
    PdfWriter writer = PdfWriter.getInstance(document, mos);

    document.addTitle("Student address labels");
    document.addAuthor("Idega Reports");
    document.addSubject("Student address labels");
    document.open();

    this.font = new Font(Font.HELVETICA, 9, Font.BOLD);

    int studentCount = 0;

    Iterator iter = receivers.iterator();
    while (iter.hasNext()) {
        if (studentCount > 0 && studentCount % NR_OF_ADDRESSES_PER_PAGE == 0) {
            document.newPage();
        }

        addAddress(writer, iwrb, (MailReceiver) iter.next(), studentCount++);
    }

    if (studentCount == 0) {
        throw new Exception("No students.");
    }

    document.close();

    writer.setPdfVersion(PdfWriter.VERSION_1_2);
    buffer.setMimeType(MIME_PDF);
    return buffer;
}

From source file:servlets.InvioServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    servletContext = getServletContext();

    HttpSession session = request.getSession(true);
    int idpre = Integer.parseInt(request.getParameter("idpre"));
    System.out.println(idpre);//from w  w w.  j  a v  a 2  s .  c  o m
    Prenotazione preno = null;
    try {
        preno = manager.getPrenotazione(idpre);
    } catch (SQLException ex) {
        Logger.getLogger(InvioServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    //int id=preno.getId_prenotazione();
    double prezzo_pagato = preno.getId_prezzo();
    int posto = preno.getId_posto();
    int spettacolo = preno.getId_spettacolo();
    Date data = preno.getData_ora_prenotazione();
    String email;
    email = preno.getEmail();
    Date data_spettacolo = preno.getData_ora_spettacolo();
    String film = preno.getTitolo();

    //creo il pdf per la prenotazione
    Document document = new Document();
    try {
        PdfWriter.getInstance(document, new FileOutputStream(servletContext.getRealPath("/") + "ticket.pdf"));
        System.out.println("Creazione file riuscita");
    } catch (DocumentException ex) {
        request.setAttribute("errorMessage", "Errore nella generazione del pdf dei biglietti. "
                + "I tuoi biglietti sono comunque stati salvati,  necessario contattare l'admin");
        RequestDispatcher rd = request.getRequestDispatcher("/errorPage.jsp");
        rd.forward(request, response);
    }
    document.open();

    //creo il paragrafo per il tiolo della pagina
    Paragraph p = new Paragraph("Biglietto n " + idpre);
    p.setAlignment(Element.ALIGN_CENTER);
    try {
        document.add(p);
        System.out.println("Scrittura file riuscita");
    } catch (DocumentException ex) {
        request.setAttribute("errorMessage", "Errore nella generazione del pdf dei biglietti.");
        RequestDispatcher rd = request.getRequestDispatcher("/errorPage.jsp");
        rd.forward(request, response);
    }

    //creo il paragrafo per i dati del biglietto
    p = new Paragraph("");
    p.setAlignment(Element.ALIGN_LEFT);
    p.add("Biglietto: " + idpre + "\n");
    p.add("Utente: " + email + "\n");
    p.add("Prezzo pagato: " + prezzo_pagato + "\n");
    p.add("Numero posto: " + posto + "\n");
    p.add("Spettacolo: " + spettacolo + "\n");
    p.add("Data: " + data + "\n");
    p.add("Data spettacolo: " + data_spettacolo + "\n");
    p.add("Film: " + film + "\n");

    try {
        document.add(p);
        System.out.println("Scrittura file riuscita");
    } catch (DocumentException ex) {
        request.setAttribute("errorMessage", "Errore nella generazione del pdf dei biglietti. "
                + "I tuoi biglietti sono comunque stati salvati,  necessario contattare l'admin");
        RequestDispatcher rd = request.getRequestDispatcher("/errorPage.jsp");
        rd.forward(request, response);
    }

    //creo il qrcode e lo aggiungo alla pagina
    Image image = null;
    File file;
    p = new Paragraph("");
    file = QRCode
            .from("utente:" + email + "\n" + "prezzo:" + prezzo_pagato + "\n" + "numero posto:" + posto + "\n"
                    + "spettacolo:" + spettacolo + "\n" + "data prenotazione:" + data + "\n"
                    + "data spettacolo:" + data_spettacolo + "\n" + "film:" + film)
            .to(ImageType.JPG).withSize(100, 100).file();
    try {
        image = Image.getInstance(file.getAbsolutePath());
    } catch (BadElementException | MalformedURLException ex) {
        // Logger.getLogger(SendTicket.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println(file.toString());
    try {
        document.add(image);
    } catch (DocumentException ex) {
        request.setAttribute("errorMessage", "Errore nella generazione del pdf dei biglietti. "
                + "I tuoi biglietti sono comunque stati salvati,  necessario contattare l'admin");
        RequestDispatcher rd = request.getRequestDispatcher("/errorPage.jsp");
        rd.forward(request, response);
    }

    try {
        document.add(p);
        document.newPage();
        System.out.println("Scrittura file riuscita");
    } catch (DocumentException ex) {
        request.setAttribute("errorMessage", "Errore nella generazione del pdf dei biglietti. "
                + "I tuoi biglietti sono comunque stati salvati,  necessario contattare l'admin");
        RequestDispatcher rd = request.getRequestDispatcher("/errorPage.jsp");
        rd.forward(request, response);
    }

    document.close();

    try {
        //invio la mail per la conferma della prenotazione con allegato il pdf
        Email.ticketEmail("smtp.gmail.com", "587", "cinemangiare@gmail.com", "Cinemangiaredb", email,
                "Conferma acquisto biglietti",
                "Gentile cliente," + "\n" + "le confermiamo la prenotazione presso il nostro cinema." + "\n"
                        + "In allegato trover il file pdf da stampare contenente i biglietti",
                servletContext.getRealPath("/") + "ticket.pdf");
    } catch (MessagingException ex) {
        request.setAttribute("errorMessage", "Errore nella generazione del pdf dei biglietti. "
                + "I tuoi biglietti sono comunque stati salvati,  necessario contattare l'admin");
        RequestDispatcher rd = request.getRequestDispatcher("/errorPage.jsp");
        rd.forward(request, response);
    }

    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/final.jsp");
    dispatcher.forward(request, response);
}

From source file:servlets.PrenotazioneServlet.java

private void invioBiglietto(ArrayList<Integer> id_prenotazione)
        throws DocumentException, FileNotFoundException {

    servletContext = getServletContext();

    ArrayList<Double> prezzo_pagato = new ArrayList<>();
    ArrayList<Integer> posto = new ArrayList<>();
    ArrayList<Integer> spettacolo = new ArrayList<>();
    ArrayList<Date> data = new ArrayList<>();
    ArrayList<String> emails = new ArrayList<>();
    ArrayList<String> titolo = new ArrayList<>();
    ArrayList<Date> data_spettacolo = new ArrayList<>();
    ArrayList<Integer> sala = new ArrayList<>();

    Prenotazione preno = null;//  w w  w . jav  a2  s.  com

    try {
        for (int i = 0; i < id_prenotazione.size(); i++) {
            preno = manager.getPrenotazione(id_prenotazione.get(i));
            System.out.println(id_prenotazione.get(i));

            prezzo_pagato.add(preno.getId_prezzo());
            posto.add(preno.getId_posto() - ((preno.getSala() - 1) * 50));
            spettacolo.add(preno.getId_spettacolo());
            data.add(preno.getData_ora_prenotazione());
            emails.add(preno.getEmail());
            titolo.add(preno.getTitolo());
            data_spettacolo.add(preno.getData_ora_spettacolo());
            sala.add(preno.getSala());
        }

    } catch (SQLException ex) {
        Logger.getLogger(InvioServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    //int id=preno.getId_prenotazione();
    //creo il pdf per la prenotazione
    Document document = new Document();

    PdfWriter.getInstance(document, new FileOutputStream(servletContext.getRealPath("/") + "ticket.pdf"));
    System.out.println("Creazione file riuscita");

    document.open();

    //creo il paragrafo per il tiolo della pagina      
    for (int i = 0; i < id_prenotazione.size(); i++) {
        Paragraph p = new Paragraph("Biglietto n " + id_prenotazione.get(i));

        p.setAlignment(Element.ALIGN_CENTER);

        try {
            document.add(p);
            System.out.println("Scrittura file riuscita");
        } catch (DocumentException ex) {

        }

        //creo il paragrafo per i dati del biglietto
        p = new Paragraph("");
        p.setAlignment(Element.ALIGN_LEFT);
        p.add("Biglietto: " + id_prenotazione.get(i) + "\n");
        p.add("Utente: " + emails.get(i) + "\n");
        p.add("Prezzo pagato: " + prezzo_pagato.get(i) + "\n");
        p.add("Numero posto: " + posto.get(i) + "\n");
        p.add("Spettacolo: " + spettacolo.get(i) + "\n");
        p.add("Data: " + data.get(i) + "\n");
        p.add("Film: " + titolo.get(i) + "\n");
        p.add("Data spettacolo: " + data_spettacolo.get(i) + "\n");
        p.add("Sala: " + sala.get(i) + "\n");

        System.out.println("INFO INFO INFO" + id_prenotazione.get(i) + " " + emails.get(i) + " "
                + prezzo_pagato.get(i) + " " + posto.get(i) + " " + spettacolo.get(i) + " " + data.get(i) + " "
                + "FINE FINE FINE");

        try {
            document.add(p);
            System.out.println("Scrittura file riuscita");
        } catch (DocumentException ex) {

        }
    }
    //creo il qrcode e lo aggiungo alla pagina
    Image image = null;
    File file;
    Paragraph p = new Paragraph("");
    file = QRCode.from("Email:" + email + "\n" + "Prezzo:" + prezzo_pagato + "\n" + "Numero posto:" + posto
            + "\n" + "Spettacolo:" + spettacolo.get(0) + "\n" + "Data:" + data.get(0) + "\n" + "Film: "
            + titolo.get(0) + "\n" + "Data spettacolo: " + data_spettacolo.get(0) + "\n" + "Sala: "
            + sala.get(0)).to(ImageType.JPG).withSize(300, 300).file();
    try {
        image = Image.getInstance(file.getAbsolutePath());
    } catch (BadElementException | MalformedURLException ex) {
        // Logger.getLogger(SendTicket.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(PrenotazioneServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println(file.toString());
    try {
        document.add(image);
    } catch (DocumentException ex) {

    }

    try {
        document.add(p);
        document.newPage();
        System.out.println("Scrittura file riuscita");
    } catch (DocumentException ex) {

    }

    document.close();

    try {

        //invio la mail per la conferma della prenotazione con allegato il pdf
        Email.ticketEmail("smtp.gmail.com", "587", "cinemangiare@gmail.com", "Cinemangiaredb", email,
                "Conferma acquisto biglietti",
                "Gentile cliente," + "\n" + "le confermiamo la prenotazione presso il nostro cinema." + "\n"
                        + "In allegato trover il file pdf da stampare contenente i biglietti",
                servletContext.getRealPath("/") + "ticket.pdf");
    } catch (Exception ex) {
        System.out.println("logan");
    }
}

From source file:songscribe.publisher.publisheractions.ExportPDFAction.java

License:Open Source License

public void actionPerformed(ActionEvent e) {
    if (publisher.isBookNull()) {
        return;/*w w w.ja  va2s  .c o m*/
    }

    if (pfd.showDialog()) {
        File saveFile = pfd.getFile();

        if (!saveFile.getName().toLowerCase().endsWith(".pdf")) {
            saveFile = new File(saveFile.getAbsolutePath() + ".pdf");
        }

        if (saveFile.exists()) {
            int answ = JOptionPane.showConfirmDialog(publisher,
                    "The file " + saveFile.getName() + " already exists. Do you want to overwrite it?",
                    publisher.PROG_NAME, JOptionPane.YES_NO_OPTION);
            if (answ == JOptionPane.NO_OPTION) {
                return;
            }
        }

        float resolution = 72f / MusicSheet.RESOLUTION;
        Book book = publisher.getBook();
        Document document = new Document(new com.lowagie.text.Rectangle(book.getPageSize().x * resolution,
                book.getPageSize().y * resolution, book.getPageSize().width * resolution,
                book.getPageSize().height * resolution), 0, 0, 0, 0);

        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(saveFile));
            document.addCreator(publisher.PROG_NAME);
            document.open();
            PdfContentByte cb = writer.getDirectContent();

            for (ListIterator<Page> it = book.pageIterator(); it.hasNext();) {
                Graphics2D g2 = cb.createGraphicsShapes(book.getPageSize().width * resolution,
                        book.getPageSize().height * resolution);
                g2.scale(resolution, resolution);
                it.next().paint(g2, it.nextIndex() - 1, false, 0, book.getPageSize().height);
                g2.dispose();

                if (it.hasNext()) {
                    document.newPage();
                }
            }

            document.close();
            Utilities.openExportFile(publisher, saveFile);
        } catch (DocumentException e1) {
            publisher.showErrorMessage("An unexprected error occured and could not export into PDF.");
            logger.error("PDF save", e1);
        } catch (FileNotFoundException e1) {
            publisher.showErrorMessage(MainFrame.COULD_NOT_SAVE_MESSAGE);
            logger.error("PDF save", e1);
        }
    }
}

From source file:textdisplay.TagFilter.java

License:Educational Community License

public void replaceTagsWithPDFEncoding(String[] tags, styles[] tagStyles, OutputStream os)
        throws DocumentException {
    //   FileWriter w = null;

    try {//  w ww .  j av a 2  s  . c  o  m
        BaseFont bf = BaseFont.createFont("/usr/Junicode.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        Document doc = new Document();
        PdfWriter p = PdfWriter.getInstance(doc, os);
        doc.open();
        Paragraph para = new Paragraph();
        para.setFont(new Font(bf, 12, Font.NORMAL));
        //doc.add(para);
        Font italic = new Font(bf, 12, Font.ITALIC);
        Font bold = new Font(bf, 12, Font.BOLD);
        Font underlined = new Font(bf, 12, Font.UNDERLINE);

        StringBuilder chunkBuffer = new StringBuilder(""); //holds the next bit of content that will be added to the pdf as a chunk
        styles chunkStyle = null; //the style to be applied to chunkBuffer when it gets added to the document
        String chunkTag = "";
        Stack<String> wrappingTags = new Stack();
        Stack<styles> wrappingStyles = new Stack();
        String content = text;
        Boolean inTag = false; //is this inside a tag, meaning between the < and >
        String tagTextBuffer = ""; //the text of the tag, including name and any parameters
        Boolean beingTagged = false; //Is the parser currently reading character data that is surrounded by a tag that demands styling
        for (int charCounter = 0; charCounter < this.text.length(); charCounter++) {

            if (text.charAt(charCounter) == '>') {
                inTag = false;
                //if this was a self closing tag, dont do anything
                if (tagTextBuffer.contains("/>")) {
                    tagTextBuffer = "";
                } else {
                    //this is a closing tag, save the chunk and pop the tag and style off of the stack
                    if (tagTextBuffer.startsWith("/")) {
                        if (chunkStyle != null)
                            System.out.print(" closing tag " + tagTextBuffer + " with style "
                                    + chunkStyle.name() + "\n");
                        else
                            System.out.print(" closing tag " + tagTextBuffer + " with style null" + "\n");
                        if (chunkStyle == styles.paragraph)
                            chunkBuffer = new StringBuilder("\n" + chunkBuffer);
                        Chunk c = new Chunk(chunkBuffer.toString());
                        styleChunk(c, chunkStyle);

                        if (chunkStyle != styles.remove)
                            para.add(c);
                        chunkBuffer = new StringBuilder("");
                        chunkStyle = null;
                        chunkTag = "";
                        if (!wrappingStyles.empty()) {
                            chunkStyle = wrappingStyles.pop();
                            chunkTag = wrappingTags.pop();
                        }
                        tagTextBuffer = "";

                    } else {
                        //this is the closing bracket of an opening tag
                        String tagName = tagTextBuffer.split(" ")[0];
                        System.out.print("tag is " + tagName + "\n");
                        for (int i = 0; i < tags.length; i++) {

                            if (tags[i].compareTo(tagName) == 0) {
                                // this is a tag that is suposed to be styled in the pdf
                                if (chunkStyle != null) {
                                    //this tag is nested in a tag that was already applying styling. Add this chunk to the pdf and put the tag/style
                                    //for the previous tag on the stack, so when this new tag ends, the previous styling will resume.
                                    if (chunkStyle == styles.paragraph)
                                        chunkBuffer = new StringBuilder("\n" + chunkBuffer);
                                    Chunk c = new Chunk(chunkBuffer.toString());
                                    styleChunk(c, chunkStyle);
                                    if (chunkStyle != styles.remove)
                                        para.add(c);
                                    wrappingStyles.add(chunkStyle);
                                    wrappingTags.add(chunkTag);
                                    chunkTag = tagName;
                                    chunkStyle = tagStyles[i];
                                    chunkBuffer = new StringBuilder("");
                                } else {
                                    Chunk c = new Chunk(chunkBuffer.toString());
                                    para.add(c);
                                    chunkTag = tagName;
                                    chunkStyle = tagStyles[i];
                                    chunkBuffer = new StringBuilder("");
                                }
                            }
                        }
                        tagTextBuffer = "";
                    }
                }
            }
            if (inTag) {
                tagTextBuffer += text.charAt(charCounter);
            }
            if (text.charAt(charCounter) == '<') {
                if (inTag) {
                    //if we hit another < before hitting a > this was not a tag, so add the tagTextBuffer to the chunk. It was simply conent.
                    chunkBuffer.append(tagTextBuffer);
                    tagTextBuffer = "";
                }
                inTag = true;
            }
            if (!inTag && text.charAt(charCounter) != '>') {
                chunkBuffer.append(text.charAt(charCounter));
            }
        }
        Chunk c = new Chunk(chunkBuffer.toString());
        para.add(c);
        doc.newPage();
        doc.add(para);
        doc.newPage();
        doc.close();
    } catch (IOException ex) {
        Logger.getLogger(TagFilter.class.getName()).log(Level.SEVERE, null, ex);
    } finally {

    }

}

From source file:tufts.vue.PresentationNotes.java

License:Educational Community License

public static void createMapAsPDF(File file, LWMap map) {
    // step 1: creation of a document-object
    Document document = new Document(PageSize.LETTER.rotate());

    try {//w  w w .  ja va 2  s.com
        GUI.activateWaitCursor();
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file            
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        writer.setDefaultColorspace(PdfName.DEFAULTRGB, null);
        // writer.setStrictImageSequence(true);
        // step 3: we open the document

        document.open();

        PdfContentByte cb = writer.getDirectContent();
        //  cb.setFontAndSize(arg0, arg1)
        PdfTemplate tp = cb.createTemplate(document.getPageSize().getWidth() - 70,
                document.getPageSize().getHeight() - 70);
        // tp.createGraphicsShapes(arg0, arg1) 

        PdfGraphics2D g2d = (PdfGraphics2D) tp.createGraphics(document.getPageSize().getWidth() - 70,
                document.getPageSize().getHeight() - 70, getFontMapper(), false, 60.0f);

        Dimension page = new Dimension((int) document.getPageSize().getWidth() - 70,
                (int) document.getPageSize().getHeight() - 70);
        // compute zoom & offset for visible map components
        Point2D.Float offset = new Point2D.Float();
        offset.x = 35;
        offset.y = 35;
        // center vertically only if landscape mode
        //if (format.getOrientation() == PageFormat.LANDSCAPE)
        //TODO: allow horizontal centering, but not vertical centering (handle in computeZoomFit)
        Rectangle2D bounds = map.getBounds();
        double scale = ZoomTool.computeZoomFit(page, 5, bounds, offset, true);
        //  System.out.println(scale  + " zoom factor...");
        // set up the DrawContext
        DrawContext dc = new DrawContext(g2d, scale, -offset.x, -offset.y, null, // frame would be the PageFormat offset & size rectangle
                map, false); // todo: absolute links shouldn't be spec'd here

        //    dc.setAntiAlias(true);
        dc.setMapDrawing();
        //   dc.setPDFRender(true);
        //dc.setPrioritizeQuality(false); // why was this low quality?
        dc.setPrintQuality();
        //dc.setAntiAlias(false); // why was this turned off?  was it redundant?

        dc.setClipOptimized(true);
        //   dc.setDraftQuality(true);
        //  dc.setRawDrawing();
        //dc.setClipOptimized(false);

        dc.setInteractive(false);
        dc.setDrawPathways(false);

        // VUE.getActiveMap().draw(dc);
        LWPathway.setShowSlides(false);
        map.drawZero(dc);
        LWPathway.setShowSlides(true);
        g2d.dispose();
        //  document.add(new Paragraph(new Chunk().setAnchor("http://www.cnn.com")));
        cb.addTemplate(tp, 0, 0);
        document.newPage();

    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    } finally {
        GUI.clearWaitCursor();
    }

    // step 5: we close the document
    document.close();
}

From source file:tufts.vue.PresentationNotes.java

License:Educational Community License

public static void createPresentationSlidesDeck(File file) {
    // step 1: creation of a document-object
    final Document document = new Document(PageSize.LETTER.rotate());

    try {//from w  ww  .  j av  a 2 s .  c o  m
        GUI.activateWaitCursor();
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file            
        final PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        writer.setDefaultColorspace(PdfName.DEFAULTRGB, null);
        writer.setStrictImageSequence(true);
        // step 3: we open the document

        document.open();

        final float pageWidth = document.getPageSize().getWidth();
        final float pageHeight = document.getPageSize().getHeight();
        final float fillWidth = pageWidth - 70;
        final float fillHeight = pageHeight - 70;

        if (DEBUG.Enabled) {
            System.out.println("\n---------------------------------");
            System.out.println("PDF DOCUMENT: pageSize " + document.getPageSize());
            System.out.println("fillWidth=" + fillWidth + " fillHeight=" + fillHeight);
        }
        int currentIndex = VUE.getActivePathway().getIndex();
        VUE.getActivePathway().setIndex(-1);
        for (LWPathway.Entry entry : VUE.getActivePathway().getEntries()) {

            if (DEBUG.Enabled)
                Log.debug("\n\nHANDLING DECK ENTRY " + entry);
            final LWSlide slide = entry.produceSlide();
            final LWComponent toDraw = (slide == null ? entry.node : slide);

            final PdfTemplate template = PdfTemplate.createTemplate(writer, fillWidth, fillHeight);
            final PdfGraphics2D graphics = (PdfGraphics2D) template.createGraphics(fillWidth, fillHeight,
                    getFontMapper(), false, 60.0f);
            final DrawContext dc = new DrawContext(graphics, 1.0);
            //                 //final DrawContext dc = new DrawContext(graphics, scale);
            //final DrawContext dc = new DrawContext(graphics, toDraw); // ideally, should use this
            dc.setClipOptimized(false);
            dc.setInteractive(false); // should be un-needed
            dc.setPrintQuality();

            // We set dc.focused to the node, which is needed for portals so they know to render contents in their clip-region.
            // Normally a portal knows to do this because it's the focal (dc.focal), but in this case, the dc.focal could,
            // at best, be the slide.  The current code actually uses NO focal in creating the DrawContext above,
            // and I'm not changing that just now as that would require lots of regression testing of printing.  SMF 6/24/10
            dc.focused = entry.node;

            if (DEBUG.Enabled) {
                Log.debug("DRAWING INTO " + dc + " g=" + graphics + " clip="
                        + tufts.Util.fmt(graphics.getClip()));
                if (DEBUG.PDF) {
                    dc.g.setColor(Color.green);
                    dc.g.fillRect(-Short.MAX_VALUE / 2, -Short.MAX_VALUE / 2, Short.MAX_VALUE, Short.MAX_VALUE);
                }
            }

            try {
                if (DEBUG.Enabled)
                    dc.clearDebug();
                toDraw.drawFit(dc, 0);
            } catch (Throwable t) {
                Log.error("exception drawing " + toDraw, t);
            }

            try {

                if (DEBUG.Enabled)
                    Log.debug("painted " + DrawContext.getDebug() + " to " + dc);

                if (DEBUG.PDF) {
                    final String dcDesc = dc.toString()
                            + String.format(" scale=%.1f%%", dc.g.getTransform().getScaleX() * 100);
                    dc.setRawDrawing();
                    dc.g.setColor(Color.red);
                    dc.g.setFont(VueConstants.FixedSmallFont);
                    dc.g.drawString(dcDesc, 10, fillHeight - 27);
                    dc.g.drawString(entry.toString(), 10, fillHeight - 16);
                    dc.g.drawString(toDraw.toString(), 10, fillHeight - 5);
                }

                // the graphics dispose appears to be very important -- we've seen completely intermittant
                // problems with generating many page PDF documents, which would be well explained by
                // java or internal itext buffers running out of memory.
                graphics.dispose();

                document.add(Image.getInstance(template));
                document.newPage();
            } catch (Throwable t) {
                Log.error("exception finishing " + toDraw + " in " + dc, t);
            }
        }
        VUE.getActivePathway().setIndex(currentIndex);
        if (DEBUG.Enabled)
            Log.debug("PROCESSED ALL ENTRIES");

    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    } finally {
        GUI.clearWaitCursor();
    }

    // step 5: we close the document
    document.close();
}

From source file:tufts.vue.PresentationNotes.java

License:Educational Community License

public static void createPresentationNotes8PerPage(File file) {
    //page size notes:
    //martin-top,left,right,bottom = 36
    //widht :612/*from w  ww  .  j  a v a 2 s.  c om*/
    //height : 792
    //usable space 540 x 720
    // step 1: creation of a document-object
    Document document = new Document(PageSize.LETTER);

    try {
        GUI.activateWaitCursor();
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file            
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        //  writer.setDefaultColorspace(PdfName.DEFAULTRGB, null);
        // writer.setStrictImageSequence(true);

        // step 3: we open the document
        document.open();

        // PdfPTable table;
        // PdfPCell cell;            
        int entryCount = 0;
        int entryOnPage = 0;
        int currentIndex = VUE.getActivePathway().getIndex();

        VUE.getActivePathway().setIndex(-1);

        for (LWPathway.Entry entry : VUE.getActivePathway().getEntries()) {

            final LWSlide slide = entry.produceSlide();
            final LWComponent toDraw = (slide == null ? entry.node : slide);

            entryCount++;
            //String label = entry.getLabel();
            PdfContentByte cb = writer.getDirectContent();
            //cb.cr
            PdfTemplate tp = cb.createTemplate(SlideSizeX, SlideSizeY);
            Point2D.Float offset = new Point2D.Float();

            Rectangle2D bounds = null;

            bounds = slide.getBounds();

            Dimension page = null;

            page = new Dimension(SlideSizeX, 172);

            //PdfTemplate tp = cb.createTemplate(document.getPageSize().width()-80, document.getPageSize().height()-80);
            double scale = ZoomTool.computeZoomFit(page, 5, bounds, offset, true);
            PdfGraphics2D g2d = (PdfGraphics2D) tp.createGraphics(SlideSizeX, SlideSizeY, getFontMapper(),
                    false, 60.0f);
            DrawContext dc = new DrawContext(g2d, scale, -offset.x, -offset.y, null, // frame would be the PageFormat offset & size rectangle
                    entry.isMapView() ? entry.getFocal() : slide, false); // todo: absolute links shouldn't be spec'd here

            dc.setClipOptimized(false);
            dc.setPrintQuality();
            //slide.drawZero(dc);
            toDraw.drawFit(dc, 0);

            g2d.dispose();
            //document.add(Image.getInstance(tp));

            if (entryOnPage == 0) {
                drawSequenceNumber(writer, 36, 739, entryCount);
                cb.addTemplate(tp, 56, 583);
            }
            if (entryOnPage == 1) {
                drawSequenceNumber(writer, 296, 739, entryCount);
                cb.addTemplate(tp, 306, 583);
            }
            if (entryOnPage == 2) {
                drawSequenceNumber(writer, 36, 559, entryCount);
                cb.addTemplate(tp, 56, 403);
            }
            if (entryOnPage == 3) {
                drawSequenceNumber(writer, 296, 559, entryCount);
                cb.addTemplate(tp, 306, 403);
            }
            if (entryOnPage == 4) {
                drawSequenceNumber(writer, 36, 375, entryCount);
                cb.addTemplate(tp, 56, 219);
            }
            if (entryOnPage == 5) {
                drawSequenceNumber(writer, 296, 375, entryCount);
                cb.addTemplate(tp, 306, 219);
            }
            if (entryOnPage == 6) {
                drawSequenceNumber(writer, 36, 192, entryCount);
                cb.addTemplate(tp, 56, 36);
                //cb.addTemplate(drawLines(writer),296,18);
            }
            if (entryOnPage == 7) {
                drawSequenceNumber(writer, 296, 192, entryCount);
                cb.addTemplate(tp, 306, 36);
            }

            entryOnPage++;
            if (entryCount % 8 == 0) {
                document.newPage();
                entryOnPage = 0;
            }
        }
        VUE.getActivePathway().setIndex(currentIndex);
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    } finally {
        GUI.clearWaitCursor();
    }

    // step 5: we close the document
    document.close();
}

From source file:tufts.vue.PresentationNotes.java

License:Educational Community License

public static void createAudienceNotes(File file) {
    //page size notes:
    //martin-top,left,right,bottom = 36
    //widht :612//from   w  ww.  j ava 2 s. c o  m
    //height : 792
    //usable space 540 x 720
    // step 1: creation of a document-object
    Document document = new Document(PageSize.LETTER);

    try {
        GUI.activateWaitCursor();
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file            
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        //  writer.setDefaultColorspace(PdfName.DEFAULTRGB, null);
        // writer.setStrictImageSequence(true);

        // step 3: we open the document
        document.open();

        // PdfPTable table;
        // PdfPCell cell;            
        int entryCount = 0;
        int entryOnPage = 0;
        int currentIndex = VUE.getActivePathway().getIndex();

        VUE.getActivePathway().setIndex(-1);

        for (LWPathway.Entry entry : VUE.getActivePathway().getEntries()) {

            final LWSlide slide = entry.produceSlide();
            final LWComponent toDraw = (slide == null ? entry.node : slide);

            entryCount++;
            //String label = entry.getLabel();
            PdfContentByte cb = writer.getDirectContent();
            //cb.cr
            PdfTemplate tp = cb.createTemplate(SlideSizeX, SlideSizeY);
            Point2D.Float offset = new Point2D.Float();
            // center vertically only if landscape mode
            //if (format.getOrientation() == PageFormat.LANDSCAPE)
            //TODO: allow horizontal centering, but not vertical centering (handle in computeZoomFit)

            Rectangle2D bounds = null;

            bounds = slide.getBounds();

            Dimension page = null;

            page = new Dimension(SlideSizeX, 172);

            //PdfTemplate tp = cb.createTemplate(document.getPageSize().width()-80, document.getPageSize().height()-80);
            double scale = ZoomTool.computeZoomFit(page, 5, bounds, offset, true);
            PdfGraphics2D g2d = (PdfGraphics2D) tp.createGraphics(SlideSizeX, SlideSizeY, getFontMapper(),
                    false, 60.0f);
            DrawContext dc = new DrawContext(g2d, scale, -offset.x, -offset.y, null, // frame would be the PageFormat offset & size rectangle
                    entry.isMapView() ? entry.getFocal() : slide, false); // todo: absolute links shouldn't be spec'd here

            dc.setClipOptimized(false);
            dc.setPrintQuality();

            toDraw.drawFit(dc, 0);

            g2d.dispose();
            //document.add(Image.getInstance(tp));

            if (entryOnPage == 0) {
                drawSequenceNumber(writer, 36, 739, entryCount);
                cb.addTemplate(tp, 56, 583);
                cb.addTemplate(drawLines(writer), 296, 565);

            }
            if (entryOnPage == 1) {
                drawSequenceNumber(writer, 36, 559, entryCount);
                cb.addTemplate(tp, 56, 403);
                cb.addTemplate(drawLines(writer), 296, 385);
            }
            if (entryOnPage == 2) {
                drawSequenceNumber(writer, 36, 375, entryCount);
                cb.addTemplate(tp, 56, 219);
                cb.addTemplate(drawLines(writer), 296, 201);
            }
            if (entryOnPage == 3) {
                drawSequenceNumber(writer, 36, 192, entryCount);
                cb.addTemplate(tp, 56, 36);
                cb.addTemplate(drawLines(writer), 296, 18);
            }

            entryOnPage++;
            if (entryCount % 4 == 0) {
                document.newPage();
                entryOnPage = 0;
            }
        }
        VUE.getActivePathway().setIndex(currentIndex);
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    } finally {
        GUI.clearWaitCursor();
    }

    // step 5: we close the document
    document.close();
}