classroom.filmfestival_c.Movies25.java Source code

Java tutorial

Introduction

Here is the source code for classroom.filmfestival_c.Movies25.java

Source

/*
 * This example was written by Bruno Lowagie, author of the book
 * 'iText in Action' by Manning Publications (ISBN: 1932394796).
 * You can use this example as inspiration for your own applications.
 * The following license applies:
 * http://www.1t3xt.com/about/copyright/index.php?page=MIT
 */

package classroom.filmfestival_c;

import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Set;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.Utilities;
import com.lowagie.text.html.simpleparser.HTMLWorker;
import com.lowagie.text.html.simpleparser.StyleSheet;
import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.ColumnText;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfSmartCopy;
import com.lowagie.text.pdf.PdfStamper;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.PushbuttonField;
import com.lowagie.text.pdf.TextField;

import database.MySessionFactory;
import database.festivaldatabase.DirectorName;
import database.festivaldatabase.FilmTitle;

public class Movies25 {

    public static final String BACKGROUND = "resources/classroom/filmfestival/movie_overview.pdf";
    public static final String TEMPLATE = "results/classroom/filmfestival/movies25_template.pdf";
    public static final String RESULT = "results/classroom/filmfestival/movies25.pdf";
    public static final Logger LOGGER = Logger.getLogger(Movies25.class.getName());

    public static final String POSTER = "poster";
    public static final String TEXT = "text";
    public static final String YEAR = "year";

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        createTemplate();
        Session session = (Session) MySessionFactory.currentSession();
        Query q = session.createQuery("from FilmTitle order by title");
        java.util.List<FilmTitle> results = q.list();
        try {
            Document document = new Document();
            PdfSmartCopy copy = new PdfSmartCopy(document, new FileOutputStream(RESULT));
            document.open();

            PdfReader reader;
            PdfStamper stamper = null;
            ByteArrayOutputStream baos = null;
            AcroFields form = null;
            int count = 0;
            for (FilmTitle movie : results) {
                if (count == 0) {
                    baos = new ByteArrayOutputStream();
                    reader = new PdfReader(BACKGROUND);
                    stamper = new PdfStamper(reader, baos);
                    stamper.setFormFlattening(true);
                    form = stamper.getAcroFields();
                }
                count++;
                byte[] pdf = createPdf(movie);
                reader = new PdfReader(pdf);
                PdfImportedPage page = stamper.getImportedPage(reader, 1);
                PushbuttonField bt = form.getNewPushbuttonFromField("movie_" + count);
                bt.setLayout(PushbuttonField.LAYOUT_ICON_ONLY);
                bt.setProportionalIcon(true);
                bt.setTemplate(page);
                form.replacePushbuttonField("movie_" + count, bt.getField());
                if (count == 16) {
                    stamper.close();
                    reader = new PdfReader(baos.toByteArray());
                    copy.addPage(copy.getImportedPage(reader, 1));
                    count = 0;
                }
            }
            if (count > 0) {
                stamper.close();
                reader = new PdfReader(baos.toByteArray());
                copy.addPage(copy.getImportedPage(reader, 1));
                count = 0;
            }
            document.close();
        } catch (IOException ioe) {
            LOGGER.error("IOException: ", ioe);
        } catch (DocumentException de) {
            LOGGER.error("DocumentException: ", de);
        }
    }

    public static byte[] createPdf(FilmTitle movie) throws IOException, DocumentException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfReader reader = new PdfReader(TEMPLATE);
        PdfStamper stamper = new PdfStamper(reader, baos);
        AcroFields form = stamper.getAcroFields();

        File file = new File("resources/classroom/filmposters/" + movie.getFilmId() + ".jpg");
        if (file.exists()) {
            PushbuttonField bt = form.getNewPushbuttonFromField(POSTER);
            bt.setLayout(PushbuttonField.LAYOUT_ICON_ONLY);
            bt.setProportionalIcon(true);
            bt.setImage(Image.getInstance(file.getPath()));
            form.replacePushbuttonField(POSTER, bt.getField());
        }

        String s = createHtml(movie);
        PdfContentByte canvas = stamper.getOverContent(1);
        float size = 12;
        float[] f = form.getFieldPositions(TEXT);
        while (addText(s, canvas, f, size, true) && size > 6) {
            size -= 0.2;
        }
        addText(s, canvas, f, size, false);

        form.setField(YEAR, String.valueOf(movie.getYear()));

        stamper.setFormFlattening(true);
        stamper.close();
        return baos.toByteArray();
    }

    @SuppressWarnings("unchecked")
    public static String createHtml(FilmTitle movie) {
        StringBuffer buf = new StringBuffer("<p><strong>\"");
        buf.append(movie.getTitle());
        buf.append("\"</strong> ");
        if (movie.getATitle().length() > 0) {
            buf.append(" aka \"");
            buf.append(movie.getATitle());
            buf.append("\" ");
        }
        Set<DirectorName> directors = movie.getDirectorNames();
        if (directors.size() > 0) {
            buf.append("directed by ");
            for (DirectorName director : directors) {
                buf.append("<i>");
                buf.append(director.getName());
                buf.append("</i>, ");
            }
        }
        buf.append("runtime: ");
        buf.append(movie.getDuration());
        buf.append(" minutes.</p>");
        System.out.println(buf.toString());
        return buf.toString();
    }

    @SuppressWarnings("unchecked")
    public static boolean addText(String s, PdfContentByte canvas, float[] f, float size, boolean simulate)
            throws DocumentException, IOException {
        StyleSheet styles = new StyleSheet();
        styles.loadTagStyle("p", "size", size + "px");
        styles.loadTagStyle("p", "align", "justify");
        styles.loadTagStyle("p", "hyphenation", "en_us");
        ArrayList<Element> objects = HTMLWorker.parseToList(new StringReader(s), styles, null);
        ColumnText ct = new ColumnText(canvas);
        ct.setAlignment(Element.ALIGN_JUSTIFIED);
        ct.setLeading(size * 1.2f);
        ct.setSimpleColumn(f[1] + 2, f[2] + 2, f[3] - 2, f[4]);
        for (Element element : objects) {
            ct.addElement(element);
        }
        return ColumnText.hasMoreText(ct.go(simulate));
    }

    public static void createTemplate() {
        // our template will be 35 x 50 mm
        Document document = new Document(
                new Rectangle(Utilities.millimetersToPoints(35), Utilities.millimetersToPoints(50)));
        try {
            // step 2
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(TEMPLATE));
            writer.setViewerPreferences(PdfWriter.PageLayoutSinglePage);
            // step 3
            document.open();
            // step 4

            // space reserved for the film poster
            PushbuttonField foto = new PushbuttonField(writer,
                    new Rectangle(Utilities.millimetersToPoints(0), Utilities.millimetersToPoints(25),
                            Utilities.millimetersToPoints(35), Utilities.millimetersToPoints(50)),
                    POSTER);
            foto.setBackgroundColor(Color.BLUE);
            writer.addAnnotation(foto.getField());

            // space reserved for the text
            TextField tekst = new TextField(writer,
                    new Rectangle(Utilities.millimetersToPoints(0), Utilities.millimetersToPoints(7),
                            Utilities.millimetersToPoints(35), Utilities.millimetersToPoints(25)),
                    TEXT);
            tekst.setOptions(TextField.MULTILINE);
            writer.addAnnotation(tekst.getTextField());

            // space reserved for the year
            TextField prijs = new TextField(writer,
                    new Rectangle(Utilities.millimetersToPoints(0), Utilities.millimetersToPoints(0),
                            Utilities.millimetersToPoints(35), Utilities.millimetersToPoints(7)),
                    YEAR);
            prijs.setAlignment(Element.ALIGN_CENTER);
            prijs.setBackgroundColor(Color.BLUE);
            prijs.setTextColor(Color.WHITE);
            writer.addAnnotation(prijs.getTextField());
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        // step 5
        document.close();
    }
}