Example usage for com.lowagie.text Rectangle Rectangle

List of usage examples for com.lowagie.text Rectangle Rectangle

Introduction

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

Prototype

public Rectangle(float urx, float ury) 

Source Link

Document

Constructs a Rectangle -object starting from the origin (0, 0).

Usage

From source file:org.projectlibre.export.ImageExport.java

License:Common Public License

public static void export(final GraphPageable pageable, Component parentComponent) throws IOException {
    final File file = chooseFile(pageable.getRenderer().getProject().getName(), parentComponent);
    final JobQueue jobQueue = SessionFactory.getInstance().getJobQueue();
    Job job = new Job(jobQueue, "Image Export", "Exporting Image...", true, parentComponent);
    job.addRunnable(new JobRunnable("Image Export", 1.0f) {
        public Object run() throws Exception {
            boolean pdf = true;
            if (file.getName().endsWith(".png"))
                pdf = false;//from w w w .j  a  va 2  s.  c om
            Document document = null;
            PdfWriter writer = null;
            if (pdf) {
                document = new Document();
                writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            } else {

            }
            pageable.update();
            int pageCount = pageable.getNumberOfPages();

            if (pageCount > 0) {
                ViewPrintable printable = pageable.getSafePrintable();
                ExtendedPageFormat pageFormat = pageable.getSafePageFormat();
                double width = pageFormat.getWidth();
                double height = pageFormat.getHeight();
                float startIncrement = 0.1f;
                float endIncrement = 0.0f;
                float progressIncrement = (1.0f - startIncrement - endIncrement) / pageCount;
                for (int p = 0; p < pageCount; p++) {
                    setProgress(startIncrement + p * progressIncrement);
                    if (pdf) {
                        document.setPageSize(new Rectangle((float) width, (float) height));
                        if (p == 0)
                            document.open();
                        else
                            document.newPage();
                        Graphics2D g = writer.getDirectContent().createGraphics((float) width, (float) height);
                        printable.print(g, p);
                        g.dispose();
                    } else {
                        BufferedImage bi = new BufferedImage((int) width, (int) height,
                                BufferedImage.TYPE_INT_ARGB);

                        Graphics2D g2 = (Graphics2D) bi.createGraphics();
                        g2.setBackground(Color.WHITE);
                        printable.print(g2, p);
                        g2.dispose();
                        ImageIO.write(bi, "png", new FileOutputStream(file));
                        break;
                    }
                }
                if (pdf)
                    document.close();
            }
            setProgress(1.0f);
            return null;
        }
    });
    jobQueue.schedule(job);
}

From source file:org.projectlibre.export.PDFExport.java

License:Common Public License

public static void export(final GraphPageable pageable, Component parentComponent) throws IOException {
    final File file = chooseFile(pageable.getRenderer().getProject().getName(), parentComponent);
    final JobQueue jobQueue = SessionFactory.getInstance().getJobQueue();
    Job job = new Job(jobQueue, "PDF Export", "Exporting PDF...", true, parentComponent);
    job.addRunnable(new JobRunnable("PDF Export", 1.0f) {
        public Object run() throws Exception {
            Document document = new Document();
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            pageable.update();/*from w  ww  .  ja v  a  2  s . c o m*/
            int pageCount = pageable.getNumberOfPages();
            if (pageCount > 0) {
                ViewPrintable printable = pageable.getSafePrintable();
                ExtendedPageFormat pageFormat = pageable.getSafePageFormat();
                double width = pageFormat.getWidth();
                double height = pageFormat.getHeight();
                float startIncrement = 0.1f;
                float endIncrement = 0.0f;
                float progressIncrement = (1.0f - startIncrement - endIncrement) / pageCount;
                for (int p = 0; p < pageCount; p++) {
                    setProgress(startIncrement + p * progressIncrement);
                    document.setPageSize(new Rectangle((float) width, (float) height));
                    if (p == 0)
                        document.open();
                    else
                        document.newPage();

                    Graphics2D g = writer.getDirectContent().createGraphics((float) width, (float) height);
                    printable.print(g, p);
                    g.dispose();
                }
                document.close();
            }
            setProgress(1.0f);
            return null;
        }
    });
    jobQueue.schedule(job);
}

From source file:org.pz.platypus.plugin.pdf.commands.PdfPageSize.java

License:Open Source License

/**
 * Load the page names and the corresponding iText rectangles into a hash table.
 * for more info on page sizes see: http://en.wikipedia.org/wiki/Paper_size#Loose_sizes
 * for info on ID cards sizes, see: http://en.wikipedia.org/wiki/ISO_7810
 *
 * @return the loaded up HashMap containing all supported page-size names
 *///from  w ww  .j a v a 2s  .c o m
HashMap<String, Rectangle> createPageSizeLookupTable() {
    HashMap<String, Rectangle> pageNames = new HashMap<String, Rectangle>(50);

    pageNames.put("4A0", new Rectangle(4768, 6741)); // 1682mm x 2378mm DIN476
    pageNames.put("2A0", new Rectangle(3370, 4768)); // 1189mm x 1682mm DIN476
    pageNames.put("A0", com.lowagie.text.PageSize.A0); //  841mm x 1189mm
    pageNames.put("A1", com.lowagie.text.PageSize.A1); //  594mm x  841mm
    pageNames.put("A2", com.lowagie.text.PageSize.A2); //  420mm x  594mm
    pageNames.put("A3", com.lowagie.text.PageSize.A3); //  297mm x  420mm
    pageNames.put("A4", com.lowagie.text.PageSize.A4); //  210mm x  297mm
    pageNames.put("A5", com.lowagie.text.PageSize.A5); //  148mm x  210mm
    pageNames.put("A6", com.lowagie.text.PageSize.A6); //  105mm x  148mm
    pageNames.put("A7", com.lowagie.text.PageSize.A7); //   74mm x  105mm
    pageNames.put("A8", com.lowagie.text.PageSize.A8); //   52mm x   74mm
    pageNames.put("A9", com.lowagie.text.PageSize.A9); //   37mm x   52mm
    pageNames.put("A10", com.lowagie.text.PageSize.A10); //   26mm x   37mm
    pageNames.put("B0", com.lowagie.text.PageSize.B0); // 1000mm x 1414mm
    pageNames.put("B1", com.lowagie.text.PageSize.B1); //  707mm x 1000mm
    pageNames.put("B2", com.lowagie.text.PageSize.B2); //  500mm x  707mm
    pageNames.put("B3", com.lowagie.text.PageSize.B3); //  353mm x  500mm
    pageNames.put("B4", com.lowagie.text.PageSize.B4); //  250mm x  353mm
    pageNames.put("B5", com.lowagie.text.PageSize.B5); //  176mm x  250mm
    pageNames.put("B6", com.lowagie.text.PageSize.B6); //  125mm x  176mm
    pageNames.put("B7", com.lowagie.text.PageSize.B7); //   88mm x  125mm
    pageNames.put("B8", com.lowagie.text.PageSize.B8); //   62mm x   88mm
    pageNames.put("B9", com.lowagie.text.PageSize.B9); //   44mm x   62mm
    pageNames.put("B10", com.lowagie.text.PageSize.A10); //   31mm x   44mm
    pageNames.put("BUSCARD-INTL", new Rectangle(243, 153)); // Business card int'l
    pageNames.put("BUSCARD-US", new Rectangle(252, 144)); // Business card US
    pageNames.put("ANSI-A", com.lowagie.text.PageSize.LETTER); // ANSI Letter
    pageNames.put("ANSI-B", com.lowagie.text.PageSize._11X17); // ANSI 11 x 17
    pageNames.put("ANSI-C", new Rectangle(1224, 1584)); // ANSI 17 x 22
    pageNames.put("ANSI-D", new Rectangle(1584, 2448)); // ANSI 22 x 34
    pageNames.put("ANSI-E", new Rectangle(2448, 3168)); // ANSI 34 x 44
    pageNames.put("ARCH-A", com.lowagie.text.PageSize.ARCH_A); // architectural A
    pageNames.put("ARCH-B", com.lowagie.text.PageSize.ARCH_B); // architectural B
    pageNames.put("ARCH-C", com.lowagie.text.PageSize.ARCH_C); // architectural C
    pageNames.put("ARCH-D", com.lowagie.text.PageSize.ARCH_D); // architectural D
    pageNames.put("ARCH-E", com.lowagie.text.PageSize.ARCH_C); // architectural E
    pageNames.put("HALFLETTER", com.lowagie.text.PageSize.HALFLETTER); // 5.5" x 8.5"
    pageNames.put("ID-1", com.lowagie.text.PageSize.ID_1); // ISO 7810 ID-1
    pageNames.put("ID-2", com.lowagie.text.PageSize.ID_2); // ISO 7810 ID-2
    pageNames.put("ID-3", com.lowagie.text.PageSize.ID_3); // ISO 7810 ID-3
    pageNames.put("INDEX3X5", new Rectangle(216, 360)); //  3" x 5"
    pageNames.put("INDEX4X6", new Rectangle(288, 432)); //  4" x 6"
    pageNames.put("INDEX5X8", new Rectangle(360, 576)); //  5" x 8"
    pageNames.put("LEDGER", com.lowagie.text.PageSize.LEDGER); // 17"  x 11"
    pageNames.put("LEGAL", com.lowagie.text.PageSize.LEGAL); // 8.5" x 14"
    pageNames.put("LETTER", com.lowagie.text.PageSize.LETTER); // 8.5" x 11"
    pageNames.put("NOTE", com.lowagie.text.PageSize.NOTE); // 7.5" x 10"
    pageNames.put("11X17", com.lowagie.text.PageSize._11X17); // 11"  x 17"

    return (pageNames);
}

From source file:org.pz.platypus.plugin.pdf.PdfOutfile.java

License:Open Source License

/**
 * Low level function for opening an iText file (that is, an iText Document)
 * @param gdd the GDD/*  www .ja v  a 2s. c om*/
 * @param pdf the PDF data
 * @param filename name of file to be opened
 * @throws IOException in the event opening the file runs into an error
 */
void openPdfFile(final GDD gdd, final PdfData pdf, final String filename) throws IOException {
    /** for writing to columns */
    PdfContentByte iTContentByte;

    final Rectangle pageSize = new Rectangle(pdf.getPageWidth(), pdf.getPageHeight());

    iTDocument = new Document(pageSize, pdf.getMarginLeft(), pdf.getMarginRight(), pdf.getMarginTop(),
            pdf.getMarginBottom());

    FileOutputStream fos;
    try {
        fos = new FileOutputStream(filename);
        iTWriter = PdfWriter.getInstance(iTDocument, fos);
        gdd.log("Opened PDF output stream: " + filename);
    } catch (DocumentException e) {
        throw new IOException("Document Exception");
    } catch (FileNotFoundException e) {
        throw new IOException("Document Not Found");
    }

    // add the routines for iText to call automatically
    //        iTWriter.setPageEvent( new OnPageStart() );
    iTWriter.setPageEvent(new OnPageEnd());
    //
    //        // set up the needed iText fields in the footer
    //        PageFooterPdf pfpdf = (PageFooterPdf) gdd.getFooter();
    //        pfpdf.setDocument( iTDocument );
    //        pfpdf.setWriter( iTWriter );

    // add metadata referring to Platypus
    iTDocument.addCreator(gdd.getLit("CREATED_BY_PLATYPUS") + " " + gdd.getLit("VERSION") + "  "
            + gdd.getLit("AVAILABLE_AT_PZ_ORG"));

    // open the document
    iTDocument.open();

    // are the margins mirrored?
    if (pdf.getMarginsMirrored()) {
        iTDocument.setMarginMirroring(true);
    }

    // get the ContentByte for writing to the columns
    iTContentByte = iTWriter.getDirectContent();

    iTColumn = new ColumnText(iTContentByte);

    // determine the size of columns based on page size at open
    pdf.setColumns(new Columns(pdf.getColumnCount(), 0f, pdf));

    openStatus = true;
}

From source file:org.sipfoundry.faxrx.FaxProcessor.java

License:Open Source License

private File tiff2Pdf(File tiffFile) {
    Pattern pattern = Pattern.compile("(.*).tiff");
    Matcher matcher = pattern.matcher(tiffFile.getName());
    boolean matchFound = matcher.find();

    // check if tiffFile is actually a TIFF file, just in case
    if (matchFound) {
        // located at default tmp-file directory
        File pdfFile = new File(System.getProperty("java.io.tmpdir"), matcher.group(1) + ".pdf");
        try {//from  www  .  j a  v  a  2  s.  c  o  m
            // read TIFF file
            RandomAccessFileOrArray tiff = new RandomAccessFileOrArray(tiffFile.getAbsolutePath());

            // get number of pages of TIFF file
            int pages = TiffImage.getNumberOfPages(tiff);

            // create PDF file
            Document pdf = new Document(PageSize.LETTER, 0, 0, 0, 0);

            PdfWriter writer = PdfWriter.getInstance(pdf, new FileOutputStream(pdfFile));
            writer.setStrictImageSequence(true);

            // open PDF filex
            pdf.open();

            PdfContentByte contentByte = writer.getDirectContent();

            // write PDF file page by page
            for (int page = 1; page <= pages; page++) {
                Image temp = TiffImage.getTiffImage(tiff, page);
                temp.scalePercent(7200f / temp.getDpiX(), 7200f / temp.getDpiY());
                pdf.setPageSize(new Rectangle(temp.getScaledWidth(), temp.getScaledHeight()));
                temp.setAbsolutePosition(0, 0);
                contentByte.addImage(temp);
                pdf.newPage();
            }
            // close PDF file
            pdf.close();
        } catch (Exception e) {
            LOG.error("faxrx::tiff2Pdf error " + e.getMessage());
            e.printStackTrace();
            return null;
        }
        return pdfFile;
    }

    else {
        return null;
    }
}

From source file:org.unitime.timetable.action.RoomFeatureListAction.java

License:Open Source License

public static void printPdfFeatureTable(OutputStream out, SessionContext context,
        RoomFeatureListForm roomFeatureListForm) throws Exception {
    boolean hasTypes = RoomFeatureType.hasFeatureTypes(context.getUser().getCurrentAcademicSessionId());

    PdfWebTable globalWebTable = new PdfWebTable(5, "Global Room Features", null,
            new String[] { "Name", "Abbreviation", hasTypes ? "Type" : "", "", "Rooms" },
            new String[] { "left", "left", "left", "left", "left" },
            new boolean[] { true, true, true, true, true });

    PdfWebTable departmentWebTable = new PdfWebTable(5, "Department Room Features", null,
            new String[] { "Name", "Abbreviation", hasTypes ? "Type" : "", "Department ", "Rooms" },
            new String[] { "left", "left", "left", "left", "left" },
            new boolean[] { true, true, true, true, true });

    Set<Department> depts = Department.getUserDepartments(context.getUser());
    Long examType = null;// ww  w.j a v  a  2s .c  o m
    Department department = null;
    if (roomFeatureListForm.getDeptCodeX() != null && roomFeatureListForm.getDeptCodeX().matches("Exam[0-9]*"))
        examType = Long.valueOf(roomFeatureListForm.getDeptCodeX().substring(4));
    else if (roomFeatureListForm.getDeptCodeX() != null && !roomFeatureListForm.getDeptCodeX().isEmpty()
            && !"All".equals(roomFeatureListForm.getDeptCodeX()))
        department = Department.findByDeptCode(roomFeatureListForm.getDeptCodeX(),
                context.getUser().getCurrentAcademicSessionId());
    boolean deptCheck = examType == null
            && !context.getUser().getCurrentAuthority().hasRight(Right.DepartmentIndependent);
    if (department != null) {
        deptCheck = true;
        depts = new TreeSet<Department>();
        depts.add(department);
    }

    boolean splitRows = false;

    // build global room features rows
    Collection globalRoomFeatures = roomFeatureListForm.getGlobalRoomFeatures();
    boolean haveGlobalRoomFeature = false;
    for (Iterator it = globalRoomFeatures.iterator(); it.hasNext();) {
        GlobalRoomFeature gr = (GlobalRoomFeature) it.next();
        Collection rs = new TreeSet(gr.getRooms());

        // get rooms
        StringBuffer assignedRoom = new StringBuffer();
        int nrRows = 0;

        boolean haveRooms = false;
        for (Iterator iter = rs.iterator(); iter.hasNext();) {
            Location r = (Location) iter.next();
            if (examType != null && !r.isExamEnabled(examType))
                continue;
            if (deptCheck) {
                boolean skip = true;
                for (RoomDept rd : r.getRoomDepts())
                    if (depts.contains(rd.getDepartment())) {
                        skip = false;
                        break;
                    }
                if (skip)
                    continue;
            }
            if (assignedRoom.length() > 0)
                assignedRoom.append(", ");
            if (PdfWebTable.getWidthOfLastLine(assignedRoom.toString(), false, false) > 750) {
                assignedRoom.append("\n");
                nrRows++;
            }
            assignedRoom.append(r.getLabel());
            haveRooms = true;
        }

        if (nrRows > 40)
            splitRows = true;

        if (!haveRooms && !context.hasPermission(gr, Right.GlobalRoomFeatureEdit))
            continue;

        globalWebTable.addLine(null,
                new String[] { gr.getLabel(), gr.getAbbv(),
                        gr.getFeatureType() == null ? "" : gr.getFeatureType().getLabel(), "",
                        assignedRoom.toString() },
                new Comparable[] { gr.getLabel(), gr.getAbbv(),
                        gr.getFeatureType() == null ? "" : gr.getFeatureType().getLabel(), "", null });
        haveGlobalRoomFeature = true;
    }

    // build department room features rows
    Collection departmentRoomFeatures = roomFeatureListForm.getDepartmentRoomFeatures();
    for (Iterator it = departmentRoomFeatures.iterator(); it.hasNext();) {
        DepartmentRoomFeature drf = (DepartmentRoomFeature) it.next();

        String ownerName = drf.getDepartment().getShortLabel();

        Collection rs = new TreeSet(drf.getRooms());

        // get rooms
        StringBuffer assignedRoom = new StringBuffer();

        for (Iterator iter = rs.iterator(); iter.hasNext();) {
            Location r = (Location) iter.next();
            if (examType != null) {
                if (!r.isExamEnabled(examType))
                    continue;
            } else {
                boolean skip = true;
                for (Iterator j = r.getRoomDepts().iterator(); j.hasNext();) {
                    RoomDept rd = (RoomDept) j.next();
                    if (drf.getDepartment().equals(rd.getDepartment())) {
                        skip = false;
                        break;
                    }
                }
                if (skip)
                    continue;
            }
            if (assignedRoom.length() > 0)
                assignedRoom.append(", ");
            if (PdfWebTable.getWidthOfLastLine(assignedRoom.toString(), false, false) > 750)
                assignedRoom.append("\n");
            assignedRoom.append(r.getLabel());
        }

        departmentWebTable.addLine(null,
                new String[] { drf.getLabel(), drf.getAbbv(),
                        drf.getFeatureType() == null ? "" : drf.getFeatureType().getLabel(), ownerName,
                        assignedRoom.toString() },
                new Comparable[] { drf.getLabel(), drf.getAbbv(),
                        drf.getFeatureType() == null ? "" : drf.getFeatureType().getLabel(), ownerName, null });
    }

    Document doc = null;

    if (haveGlobalRoomFeature) {
        PdfWebTable table = globalWebTable;
        PdfPTable pdfTable = table.printPdfTable(WebTable.getOrder(context, "roomFeatureList.gord"));
        pdfTable.setSplitRows(splitRows);
        if (doc == null) {
            doc = new Document(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth()), 30, 30,
                    30, 30);
            PdfWriter iWriter = PdfWriter.getInstance(doc, out);
            iWriter.setPageEvent(new PdfEventHandler());
            doc.open();
        }
        doc.add(new Paragraph(table.getName(), PdfFont.getBigFont(true)));
        doc.add(pdfTable);
    }

    if (!departmentRoomFeatures.isEmpty()) {
        PdfWebTable table = departmentWebTable;
        PdfPTable pdfTable = table.printPdfTable(WebTable.getOrder(context, "roomFeatureList.mord"));
        if (doc == null) {
            doc = new Document(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth()), 30, 30,
                    30, 30);
            PdfWriter iWriter = PdfWriter.getInstance(doc, out);
            iWriter.setPageEvent(new PdfEventHandler());
            doc.open();
        } else {
            doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth()));
            doc.newPage();
        }
        doc.add(new Paragraph(table.getName(), PdfFont.getBigFont(true)));
        doc.add(pdfTable);
    }

    if (doc != null)
        doc.close();
}

From source file:org.unitime.timetable.action.RoomGroupListAction.java

License:Open Source License

public static void printPdfGroupTable(OutputStream out, SessionContext context,
        RoomGroupListForm roomGroupListForm) throws Exception {
    PdfWebTable globalWebTable = new PdfWebTable(5, "Global Room Groups", null,
            new String[] { "Name", "Abbreviation", "Default ", "Rooms", "Description" },
            new String[] { "left", "left", "middle", "left", "left" },
            new boolean[] { true, true, true, true, true });

    PdfWebTable departmentWebTable = new PdfWebTable(5, "Department Room Groups", null,
            new String[] { "Name", "Abbreviation", "Department ", "Rooms", "Description" },
            new String[] { "left", "left", "left", "left", "left" },
            new boolean[] { true, true, true, true, true });

    Set<Department> depts = Department.getUserDepartments(context.getUser());
    Long examType = null;/*from  www.j ava 2s.  com*/
    Department department = null;
    if (roomGroupListForm.getDeptCodeX() != null && roomGroupListForm.getDeptCodeX().matches("Exam[0-9]*"))
        examType = Long.valueOf(roomGroupListForm.getDeptCodeX().substring(4));
    else if (roomGroupListForm.getDeptCodeX() != null && !roomGroupListForm.getDeptCodeX().isEmpty()
            && !"All".equals(roomGroupListForm.getDeptCodeX()))
        department = Department.findByDeptCode(roomGroupListForm.getDeptCodeX(),
                context.getUser().getCurrentAcademicSessionId());
    boolean deptCheck = examType == null
            && !context.getUser().getCurrentAuthority().hasRight(Right.DepartmentIndependent);
    if (department != null) {
        deptCheck = true;
        depts = new TreeSet<Department>();
        depts.add(department);
    }

    boolean splitRows = false;

    boolean haveGlobalRoomGroup = false;
    for (RoomGroup rg : RoomGroup.getAllGlobalRoomGroups(context.getUser().getCurrentAcademicSessionId())) {
        Collection rs = new TreeSet(rg.getRooms());

        StringBuffer assignedRoom = new StringBuffer();
        int nrRows = 0;

        boolean haveRooms = false;
        for (Iterator iter = rs.iterator(); iter.hasNext();) {
            Location r = (Location) iter.next();
            if (examType != null && !r.isExamEnabled(examType))
                continue;
            if (deptCheck) {
                boolean skip = true;
                for (RoomDept rd : r.getRoomDepts())
                    if (depts.contains(rd.getDepartment())) {
                        skip = false;
                        break;
                    }
                if (skip)
                    continue;
            }
            if (assignedRoom.length() > 0)
                assignedRoom.append(", ");
            if (PdfWebTable.getWidthOfLastLine(assignedRoom.toString(), false, false) > 750) {
                assignedRoom.append("\n");
                nrRows++;
            }
            assignedRoom.append(r.getLabel());
            haveRooms = true;
        }

        if (nrRows > 40)
            splitRows = true;

        if (!haveRooms && !context.hasPermission(rg, Right.GlobalRoomGroupEdit))
            continue;

        globalWebTable.addLine(null,
                new String[] { rg.getName(), rg.getAbbv(), (rg.isDefaultGroup().booleanValue() ? "Yes" : "No"),
                        assignedRoom.toString(), (rg.getDescription() == null ? "" : rg.getDescription()) },
                new Comparable[] { rg.getName(), rg.getAbbv(),
                        new Integer(rg.isDefaultGroup().booleanValue() ? 0 : 1), null,
                        (rg.getDescription() == null ? "" : rg.getDescription()) });

        haveGlobalRoomGroup = true;
    }

    Set<RoomGroup> departmentRoomGroups = new TreeSet<RoomGroup>();
    for (Department d : Department.getUserDepartments(context.getUser())) {
        if ("All".equals(roomGroupListForm.getDeptCodeX())
                || d.getDeptCode().equals(roomGroupListForm.getDeptCodeX()))
            departmentRoomGroups.addAll(RoomGroup.getAllDepartmentRoomGroups(d));
    }
    if (department != null && department.isExternalManager()) {
        departmentRoomGroups.addAll(RoomGroup.getAllDepartmentRoomGroups(department));
    }

    for (RoomGroup rg : departmentRoomGroups) {
        String ownerName = rg.getDepartment().getShortLabel();

        Collection rs = new TreeSet(rg.getRooms());

        // get rooms
        StringBuffer assignedRoom = new StringBuffer();

        for (Iterator iter = rs.iterator(); iter.hasNext();) {
            Location r = (Location) iter.next();
            if (examType != null) {
                if (!r.isExamEnabled(examType))
                    continue;
            } else {
                boolean skip = true;
                for (Iterator j = r.getRoomDepts().iterator(); j.hasNext();) {
                    RoomDept rd = (RoomDept) j.next();
                    if (rg.getDepartment().equals(rd.getDepartment())) {
                        skip = false;
                        break;
                    }
                }
                if (skip)
                    continue;
            }
            if (assignedRoom.length() > 0)
                assignedRoom.append(", ");
            if (PdfWebTable.getWidthOfLastLine(assignedRoom.toString(), false, false) > 750)
                assignedRoom.append("\n");
            assignedRoom.append(r.getLabel());
        }

        departmentWebTable.addLine(null,
                new String[] { rg.getName(), rg.getAbbv(), ownerName, assignedRoom.toString(),
                        (rg.getDescription() == null ? "" : rg.getDescription()) },
                new Comparable[] { rg.getName(), rg.getAbbv(), ownerName, null,
                        (rg.getDescription() == null ? "" : rg.getDescription()) });
    }

    Document doc = null;

    if (haveGlobalRoomGroup) {
        PdfWebTable table = globalWebTable;
        PdfPTable pdfTable = table.printPdfTable(WebTable.getOrder(context, "roomGroupList.gord"));
        pdfTable.setSplitRows(splitRows);
        if (doc == null) {
            doc = new Document(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth()), 30, 30,
                    30, 30);
            PdfWriter iWriter = PdfWriter.getInstance(doc, out);
            iWriter.setPageEvent(new PdfEventHandler());
            doc.open();
        }
        doc.add(new Paragraph(table.getName(), PdfFont.getBigFont(true)));
        doc.add(pdfTable);
    }

    if (!departmentRoomGroups.isEmpty()) {
        PdfWebTable table = departmentWebTable;
        PdfPTable pdfTable = table.printPdfTable(WebTable.getOrder(context, "roomGroupList.mord"));
        if (doc == null) {
            doc = new Document(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth()), 30, 30,
                    30, 30);
            PdfWriter iWriter = PdfWriter.getInstance(doc, out);
            iWriter.setPageEvent(new PdfEventHandler());
            doc.open();
        } else {
            doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth()));
            doc.newPage();
        }
        doc.add(new Paragraph(table.getName(), PdfFont.getBigFont(true)));
        doc.add(pdfTable);
    }

    if (doc != null)
        doc.close();

}

From source file:org.unitime.timetable.action.RoomListAction.java

License:Open Source License

public void buildPdfWebTable(OutputStream out, RoomListForm roomListForm, boolean featuresOneColumn,
        ExamType examType) throws Exception {
    Long sessionId = sessionContext.getUser().getCurrentAcademicSessionId();
    Session session = SessionDAO.getInstance().get(sessionId);
    DecimalFormat dfa = new DecimalFormat(ApplicationProperty.RoomAreaUnitsFormat.value());

    Collection rooms = roomListForm.getRooms();

    ArrayList globalRoomFeatures = new ArrayList();
    Set deptRoomFeatures = new TreeSet();

    Set depts = null;//from   w ww.  j  a  v  a  2s. c o m
    if (roomListForm.getDeptCodeX().equalsIgnoreCase("All")) {
        depts = Department.getUserDepartments(sessionContext.getUser());
    } else if (roomListForm.getDeptCodeX().matches("Exam[0-9]*")) {
        depts = new HashSet(0);
    } else {
        depts = new HashSet(1);
        depts.add(Department.findByDeptCode(roomListForm.getDeptCodeX(), sessionId));
    }

    org.hibernate.Session hibSession = null;
    try {

        RoomFeatureDAO d = new RoomFeatureDAO();
        hibSession = d.getSession();

        List list = hibSession.createCriteria(GlobalRoomFeature.class).addOrder(Order.asc("label")).list();

        for (Iterator iter = list.iterator(); iter.hasNext();) {
            GlobalRoomFeature rf = (GlobalRoomFeature) iter.next();
            globalRoomFeatures.add(rf);
        }

        if (roomListForm.getDeptCodeX().equalsIgnoreCase("All")) {
            if (sessionContext.getUser().getCurrentAuthority().hasRight(Right.DepartmentIndependent)) {
                deptRoomFeatures.addAll(hibSession.createQuery(
                        "select distinct f from DepartmentRoomFeature f inner join f.department d where "
                                + "d.session.uniqueId=:sessionId order by f.label")
                        .setLong("sessionId", sessionId).setCacheable(true).list());
            } else {
                String deptIds = "";
                for (Qualifiable q : sessionContext.getUser().getCurrentAuthority()
                        .getQualifiers("Department")) {
                    if (!deptIds.isEmpty())
                        deptIds += ",";
                    deptIds += q.getQualifierId();
                }
                if (!deptIds.isEmpty())
                    deptRoomFeatures.addAll(hibSession
                            .createQuery(
                                    "select distinct f from DepartmentRoomFeature f inner join f.department d "
                                            + "where d.session.uniqueId=:sessionId and d.uniqueId in ("
                                            + deptIds + ") order by f.label")
                            .setLong("sessionId", sessionId).setCacheable(true).list());
            }
        } else if (roomListForm.getDeptCodeX().matches("Exam[0-9]*")) {
        } else {
            deptRoomFeatures.addAll(hibSession
                    .createQuery("select distinct f from DepartmentRoomFeature f inner join f.department d "
                            + "where d.session.uniqueId=:sessionId and d.deptCode = :deptCode order by f.label")
                    .setLong("sessionId", sessionId).setString("deptCode", roomListForm.getDeptCodeX())
                    .setCacheable(true).list());
        }

    } catch (Exception e) {
        Debug.error(e);
    }

    //build headings for university rooms
    String fixedHeading1[][] = (examType != null
            ? (featuresOneColumn ? new String[][] { { "Bldg", "left", "true" }, { "Room", "left", "true" },
                    { "Capacity", "right", "false" }, { "Exam Capacity", "right", "false" },
                    { MSG.columnAreaPDF(), "right", "false" }, { "Period Preferences", "center", "true" },
                    { "Groups", "left", "true" }, { "Features", "left", "true" } }
                    : new String[][] { { "Bldg", "left", "true" }, { "Room", "left", "true" },
                            { "Capacity", "right", "false" }, { "Exam Capacity", "right", "false" },
                            { MSG.columnAreaPDF(), "right", "false" },
                            { "Period Preferences", "center", "true" }, { "Groups", "left", "true" } })
            : (featuresOneColumn
                    ? new String[][] { { "Bldg", "left", "true" }, { "Room", "left", "true" },
                            { "Capacity", "right", "false" }, { MSG.columnAreaPDF(), "right", "false" },
                            { "Availability", "left", "true" }, { "Departments", "left", "true" },
                            { "Control", "left", "true" }, { "Events", "left", "true" },
                            { "Groups", "left", "true" }, { "Features", "left", "true" } }
                    : new String[][] { { "Bldg", "left", "true" }, { "Room", "left", "true" },
                            { "Capacity", "right", "false" }, { MSG.columnAreaPDF(), "right", "false" },
                            { "Availability", "left", "true" }, { "Departments", "left", "true" },
                            { "Control", "left", "true" }, { "Events", "left", "true" },
                            { "Groups", "left", "true" } }));

    String heading1[] = new String[fixedHeading1.length
            + (featuresOneColumn ? 0 : (globalRoomFeatures.size() + deptRoomFeatures.size()))];
    String alignment1[] = new String[heading1.length];
    boolean sorted1[] = new boolean[heading1.length];

    for (int i = 0; i < fixedHeading1.length; i++) {
        heading1[i] = fixedHeading1[i][0];
        alignment1[i] = fixedHeading1[i][1];
        sorted1[i] = (Boolean.valueOf(fixedHeading1[i][2])).booleanValue();
    }

    if (!featuresOneColumn) {
        int i = fixedHeading1.length;
        for (Iterator it = globalRoomFeatures.iterator(); it.hasNext();) {
            heading1[i] = ((GlobalRoomFeature) it.next()).getLabel();
            heading1[i] = heading1[i].replaceFirst(" ", "\n");
            alignment1[i] = "center";
            sorted1[i] = true;
            i++;
        }
        for (Iterator it = deptRoomFeatures.iterator(); it.hasNext();) {
            DepartmentRoomFeature drf = (DepartmentRoomFeature) it.next();
            heading1[i] = drf.getLabel();
            heading1[i] = heading1[i].replaceFirst(" ", "\n");
            if (roomListForm.getDeptCodeX().equalsIgnoreCase("All")) {
                Department dept = drf.getDepartment();
                heading1[i] += " (" + dept.getShortLabel() + ")";
            }
            alignment1[i] = "center";
            sorted1[i] = true;
            i++;
        }
    }

    //build headings for non-univ locations
    String fixedHeading2[][] = (examType != null
            ? (featuresOneColumn
                    ? new String[][] { { "Location", "left", "true" }, { "Capacity", "right", "false" },
                            { "Exam Capacity", "right", "false" }, { MSG.columnAreaPDF(), "right", "false" },
                            { "Period Preferences", "center", "true" }, { "Groups", "left", "true" },
                            { "Features", "left", "true" } }
                    : new String[][] { { "Location", "left", "true" }, { "Capacity", "right", "false" },
                            { MSG.columnAreaPDF(), "right", "false" },
                            { "Period Preferences", "center", "true" }, { "Groups", "left", "true" } })
            : (featuresOneColumn
                    ? new String[][] { { "Location", "left", "true" }, { "Capacity", "right", "false" },
                            { MSG.columnAreaPDF(), "right", "false" }, { "IgnTooFar", "center", "true" },
                            { "IgnChecks", "center", "true" }, { "Availability", "left", "true" },
                            { "Departments", "left", "true" }, { "Control", "left", "true" },
                            { "Events", "left", "true" }, { "Groups", "left", "true" },
                            { "Features", "left", "true" } }
                    : new String[][] { { "Location", "left", "true" }, { "Capacity", "right", "false" },
                            { "Exam Capacity", "right", "false" }, { MSG.columnAreaPDF(), "right", "false" },
                            { "IgnTooFar", "center", "true" }, { "IgnChecks", "center", "true" },
                            { "Availability", "left", "true" }, { "Departments", "left", "true" },
                            { "Control", "left", "true" }, { "Events", "left", "true" },
                            { "Groups", "left", "true" } }));

    String heading2[] = new String[fixedHeading2.length
            + (featuresOneColumn ? 0 : (globalRoomFeatures.size() + deptRoomFeatures.size()))];
    String alignment2[] = new String[heading2.length];
    boolean sorted2[] = new boolean[heading2.length];

    for (int i = 0; i < fixedHeading2.length; i++) {
        heading2[i] = fixedHeading2[i][0];
        alignment2[i] = fixedHeading2[i][1];
        sorted2[i] = (Boolean.valueOf(fixedHeading2[i][2])).booleanValue();
    }

    if (!featuresOneColumn) {
        int i = fixedHeading2.length;
        for (Iterator it = globalRoomFeatures.iterator(); it.hasNext();) {
            heading2[i] = ((GlobalRoomFeature) it.next()).getLabel();
            heading2[i] = heading2[i].replaceFirst(" ", "\n");
            alignment2[i] = "center";
            sorted2[i] = true;
            i++;
        }
        for (Iterator it = deptRoomFeatures.iterator(); it.hasNext();) {
            DepartmentRoomFeature drf = (DepartmentRoomFeature) it.next();
            heading2[i] = drf.getLabel();
            heading2[i] = heading2[i].replaceFirst(" ", "\n");
            if (roomListForm.getDeptCodeX().equalsIgnoreCase("All")) {
                Department dept = Department.findByDeptCode(drf.getDeptCode(), sessionId);
                heading2[i] += " (" + dept.getShortLabel() + ")";
            }
            alignment2[i] = "center";
            sorted2[i] = true;
            i++;
        }
    }

    TreeSet<RoomType> roomTypes = new TreeSet<RoomType>(RoomTypeDAO.getInstance().findAll());
    Hashtable<RoomType, PdfWebTable> tables = new Hashtable();
    for (RoomType t : roomTypes) {
        PdfWebTable table = (t.isRoom()
                ? new PdfWebTable(heading1.length, t.getLabel(), null, heading1, alignment1, sorted1)
                : new PdfWebTable(heading2.length, t.getLabel(), null, heading2, alignment2, sorted2));
        tables.put(t, table);
    }

    boolean timeVertical = CommonValues.VerticalGrid
            .eq(UserProperty.GridOrientation.get(sessionContext.getUser()));
    boolean gridAsText = CommonValues.TextGrid.eq(UserProperty.GridOrientation.get(sessionContext.getUser()));
    String timeGridSize = UserProperty.GridSize.get(sessionContext.getUser());

    Department dept = new Department();
    if (!roomListForm.getDeptCodeX().equalsIgnoreCase("All")) {
        dept = Department.findByDeptCode(roomListForm.getDeptCodeX(), sessionId);
    } else {
        dept = null;
    }

    for (Iterator iter = rooms.iterator(); iter.hasNext();) {
        Location location = (Location) iter.next();

        boolean editable = sessionContext.hasPermission(location, Right.RoomDetail);

        Room room = (location instanceof Room ? (Room) location : null);
        Building bldg = (room == null ? null : room.getBuilding());

        PdfWebTable table = tables.get(location.getRoomType());

        DecimalFormat df5 = new DecimalFormat("####0");
        String text[] = new String[Math.max(heading1.length, heading2.length)];
        Comparable comp[] = new Comparable[text.length];
        int idx = 0;
        if (bldg != null) {
            text[idx] = (location.isIgnoreRoomCheck().booleanValue() ? "@@ITALIC " : "")
                    + bldg.getAbbreviation()
                    + (location.isIgnoreRoomCheck().booleanValue() ? "@@END_ITALIC " : "");
            comp[0] = location.getLabel();
            idx++;
        }

        text[idx] = (location.isIgnoreRoomCheck().booleanValue() ? "@@ITALIC " : "")
                + (room == null ? location.getLabel() : room.getRoomNumber())
                + (location.isIgnoreRoomCheck().booleanValue() ? "@@END_ITALIC " : "");
        comp[idx] = location.getLabel();
        idx++;

        text[idx] = df5.format(location.getCapacity());
        comp[idx] = new Long(location.getCapacity().intValue());
        idx++;

        if (examType != null) {
            if (location.isExamEnabled(examType)) {
                text[idx] = df5.format(location.getExamCapacity());
                comp[idx] = location.getExamCapacity();
            } else {
                text[idx] = "";
                comp[idx] = new Integer(0);
            }
            idx++;

            if (location.getArea() == null) {
                text[idx] = "";
                comp[idx] = new Double(0);
            } else {
                text[idx] = dfa.format(location.getArea());
                comp[idx] = location.getArea();
            }
            idx++;

            if (location.isExamEnabled(examType)) {
                text[idx] = location.getExamPreferencesAbbreviation(examType);
                comp[idx] = null;
            } else {
                text[idx] = "";
                comp[idx] = null;
            }
            idx++;
        } else {
            if (location.getArea() == null) {
                text[idx] = "";
                comp[idx] = new Double(0);
            } else {
                text[idx] = dfa.format(location.getArea());
                comp[idx] = location.getArea();
            }
            idx++;

            PreferenceLevel roomPref = location.getRoomPreferenceLevel(dept);
            if (editable && roomPref != null && !PreferenceLevel.sNeutral.equals(roomPref.getPrefProlog())) {
                if (room == null) {
                    text[0] = (location.isIgnoreRoomCheck().booleanValue() ? "@@ITALIC " : "")
                            + location.getLabel() + " (" + PreferenceLevel.prolog2abbv(roomPref.getPrefProlog())
                            + ")" + (location.isIgnoreRoomCheck().booleanValue() ? "@@END_ITALIC " : "");
                } else {
                    text[0] = (location.isIgnoreRoomCheck().booleanValue() ? "@@ITALIC " : "")
                            + (bldg == null ? "" : bldg.getAbbreviation())
                            + (location.isIgnoreRoomCheck().booleanValue() ? "@@END_ITALIC " : "");
                    text[1] = (location.isIgnoreRoomCheck().booleanValue() ? "@@ITALIC " : "")
                            + room.getRoomNumber() + " ("
                            + PreferenceLevel.prolog2abbv(roomPref.getPrefProlog()) + ")"
                            + (location.isIgnoreRoomCheck().booleanValue() ? "@@END_ITALIC " : "");
                }
            }

            //ignore too far
            if (location instanceof NonUniversityLocation) {
                boolean itf = (location.isIgnoreTooFar() == null ? false
                        : location.isIgnoreTooFar().booleanValue());
                text[idx] = (itf ? "Yes" : "No");
                comp[idx] = new Integer(itf ? 1 : 0);
                idx++;
                boolean con = (location.isIgnoreRoomCheck() == null ? true
                        : location.isIgnoreRoomCheck().booleanValue());
                text[idx] = (con ? "YES" : "No");
                comp[idx] = new Integer(con ? 1 : 0);
                idx++;
            }

            // get pattern column
            RequiredTimeTable rtt = location.getRoomSharingTable();
            if (gridAsText) {
                text[idx] = rtt.getModel().toString().replaceAll(", ", "\n");
            } else {
                rtt.getModel().setDefaultSelection(timeGridSize);
                Image image = rtt.createBufferedImage(timeVertical);
                if (image != null) {
                    table.addImage(location.getUniqueId().toString(), image);
                    text[idx] = ("@@IMAGE " + location.getUniqueId().toString() + " ");
                } else {
                    text[idx] = rtt.getModel().toString().replaceAll(", ", "\n");
                }
            }
            comp[idx] = null;
            idx++;

            // get departments column
            Department controlDept = null;
            text[idx] = "";
            Set rds = location.getRoomDepts();
            Set departments = new HashSet();
            for (Iterator iterRds = rds.iterator(); iterRds.hasNext();) {
                RoomDept rd = (RoomDept) iterRds.next();
                Department d = rd.getDepartment();
                if (rd.isControl().booleanValue())
                    controlDept = d;
                departments.add(d);
            }
            TreeSet ts = new TreeSet(new DepartmentNameComparator());
            ts.addAll(departments);
            if (ts.size() == session.getDepartments().size()) {
                text[idx] = "@@BOLD All";
                comp[idx] = "";
            } else {
                int cnt = 0;
                for (Iterator it = ts.iterator(); it.hasNext(); cnt++) {
                    Department d = (Department) it.next();
                    if (text[idx].length() > 0)
                        text[idx] = text[idx] + (ts.size() <= 5 || cnt % 5 == 0 ? "\n" : ", ");
                    else
                        comp[idx] = d.getDeptCode();
                    text[idx] = text[idx] + "@@COLOR " + d.getRoomSharingColor(null) + " " + d.getShortLabel();
                }
            }
            idx++;

            //control column
            if (!roomListForm.getDeptCodeX().equalsIgnoreCase("All")
                    && !roomListForm.getDeptCodeX().matches("Exam[0-9]*")) {
                if (controlDept != null && controlDept.getDeptCode().equals(roomListForm.getDeptCodeX())) {
                    text[idx] = "Yes";
                    comp[idx] = new Integer(1);
                } else {
                    text[idx] = "No";
                    comp[idx] = new Integer(0);
                }
            } else {
                if (controlDept != null) {
                    text[idx] = "@@COLOR " + controlDept.getRoomSharingColor(null) + " "
                            + controlDept.getShortLabel();
                    comp[idx] = controlDept.getDeptCode();
                } else {
                    text[idx] = "";
                    comp[idx] = "";
                }
            }
            idx++;

            //events column
            if (location.getEventDepartment() != null && location.getEventDepartment().isAllowEvents()) {
                text[idx] = "@@COLOR " + location.getEventDepartment().getRoomSharingColor(null) + " "
                        + location.getEventDepartment().getShortLabel();
                comp[idx] = location.getEventDepartment().getDeptCode();
            } else {
                text[idx] = "";
                comp[idx] = "";
            }
            idx++;
        }

        // get groups column
        text[idx] = "";
        for (Iterator it = new TreeSet(location.getRoomGroups()).iterator(); it.hasNext();) {
            RoomGroup rg = (RoomGroup) it.next();
            if (!rg.isGlobal().booleanValue() && (examType != null || !depts.contains(rg.getDepartment())))
                continue;
            if (!rg.isGlobal().booleanValue()) {
                boolean skip = true;
                for (Iterator j = location.getRoomDepts().iterator(); j.hasNext();) {
                    RoomDept rd = (RoomDept) j.next();
                    if (rg.getDepartment().equals(rd.getDepartment())) {
                        skip = false;
                        break;
                    }
                }
                if (skip)
                    continue;
            }
            if (text[idx].length() > 0)
                text[idx] += "\n";
            comp[idx] = comp[idx] + rg.getName().trim();
            text[idx] += (rg.isGlobal().booleanValue() ? ""
                    : "@@COLOR " + rg.getDepartment().getRoomSharingColor(null) + " ") + rg.getName();
        }
        idx++;

        if (featuresOneColumn) {
            // get features column
            text[idx] = "";
            for (Iterator it = new TreeSet(location.getGlobalRoomFeatures()).iterator(); it.hasNext();) {
                GlobalRoomFeature rf = (GlobalRoomFeature) it.next();
                if (text[idx].length() > 0)
                    text[idx] += "\n";
                comp[idx] = comp[idx] + rf.getLabel().trim();
                text[idx] += rf.getLabelWithType();
            }
            if (examType == null)
                for (Iterator it = new TreeSet(location.getDepartmentRoomFeatures()).iterator(); it
                        .hasNext();) {
                    DepartmentRoomFeature drf = (DepartmentRoomFeature) it.next();
                    if (!depts.contains(drf.getDepartment()))
                        continue;
                    boolean skip = true;
                    for (Iterator j = location.getRoomDepts().iterator(); j.hasNext();) {
                        RoomDept rd = (RoomDept) j.next();
                        if (drf.getDepartment().equals(rd.getDepartment())) {
                            skip = false;
                            break;
                        }
                    }
                    if (skip)
                        continue;
                    if (text[idx].length() > 0)
                        text[idx] += "\n";
                    comp[idx] = comp[idx] + drf.getLabel().trim();
                    text[idx] += "@@COLOR " + drf.getDepartment().getRoomSharingColor(null) + " "
                            + drf.getLabelWithType();
                }
            idx++;
        } else {
            // get features columns
            for (Iterator it = globalRoomFeatures.iterator(); it.hasNext();) {
                GlobalRoomFeature grf = (GlobalRoomFeature) it.next();
                boolean b = location.hasFeature(grf);
                text[idx] = b ? "Yes" : "No";
                comp[idx] = "" + b;
                idx++;
            }
            for (Iterator it = deptRoomFeatures.iterator(); it.hasNext();) {
                DepartmentRoomFeature drf = (DepartmentRoomFeature) it.next();
                boolean b = location.hasFeature(drf);
                for (Iterator j = location.getRoomDepts().iterator(); j.hasNext();) {
                    RoomDept rd = (RoomDept) j.next();
                    if (drf.getDepartment().equals(rd.getDepartment())) {
                        b = false;
                        break;
                    }
                }
                text[idx] = b ? "Yes" : "No";
                comp[idx] = "" + b;
                idx++;
            }
        }

        // build rows
        table.addLine(
                (editable ? "onClick=\"document.location='roomDetail.do?id=" + location.getUniqueId() + "';\""
                        : null),
                text, comp);
    }

    Document doc = null;
    // set request attributes
    for (RoomType t : roomTypes) {
        PdfWebTable table = tables.get(t);
        if (!table.getLines().isEmpty()) {
            int ord = WebTable.getOrder(sessionContext, t.getReference() + ".ord");
            if (ord > heading1.length)
                ord = 0;
            PdfPTable pdfTable = table.printPdfTable(ord);
            if (doc == null) {
                doc = new Document(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth()), 30,
                        30, 30, 30);
                PdfWriter iWriter = PdfWriter.getInstance(doc, out);
                iWriter.setPageEvent(new PdfEventHandler());
                doc.open();
            } else {
                doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth()));
                doc.newPage();
            }
            doc.add(new Paragraph(table.getName(), PdfFont.getBigFont(true)));
            doc.add(pdfTable);

        }
    }

    if (doc == null)
        return;

    doc.close();
}

From source file:org.unitime.timetable.action.SolutionReportAction.java

License:Open Source License

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    SolutionReportForm myForm = (SolutionReportForm) form;

    sessionContext.checkPermission(Right.SolutionReports);

    // Read operation to be performed
    String op = (myForm.getOp() != null ? myForm.getOp() : request.getParameter("op"));
    Session session = SessionDAO.getInstance().get(sessionContext.getUser().getCurrentAcademicSessionId());
    BitSet sessionDays = session.getDefaultDatePattern().getPatternBitSet();
    int startDayDayOfWeek = Constants.getDayOfWeek(session.getDefaultDatePattern().getStartDate());

    SolverProxy solver = courseTimetablingSolverService.getSolver();
    if (solver == null) {
        request.setAttribute("SolutionReport.message", "Neither a solver is started nor solution is loaded.");
    } else {//w ww.  j  a  v a2  s  .c  o  m
        try {
            for (RoomType type : RoomType.findAll()) {
                RoomReport roomReport = solver.getRoomReport(sessionDays, startDayDayOfWeek,
                        type.getUniqueId());
                if (roomReport != null && !roomReport.getGroups().isEmpty()) {
                    WebTable t = getRoomReportTable(request, roomReport, false, type.getUniqueId());
                    if (t != null)
                        request.setAttribute("SolutionReport.roomReportTable." + type.getReference(),
                                t.printTable(
                                        WebTable.getOrder(sessionContext, "solutionReports.roomReport.ord")));
                }
            }
            RoomReport roomReport = solver.getRoomReport(sessionDays, startDayDayOfWeek, null);
            if (roomReport != null && !roomReport.getGroups().isEmpty()) {
                WebTable t = getRoomReportTable(request, roomReport, false, null);
                if (t != null)
                    request.setAttribute("SolutionReport.roomReportTable.nonUniv",
                            t.printTable(WebTable.getOrder(sessionContext, "solutionReports.roomReport.ord")));
            }
            DeptBalancingReport deptBalancingReport = solver.getDeptBalancingReport();
            if (deptBalancingReport != null && !deptBalancingReport.getGroups().isEmpty())
                request.setAttribute("SolutionReport.deptBalancingReportTable",
                        getDeptBalancingReportTable(request, deptBalancingReport, false).printTable(
                                WebTable.getOrder(sessionContext, "solutionReports.deptBalancingReport.ord")));
            ViolatedDistrPreferencesReport violatedDistrPreferencesReport = solver
                    .getViolatedDistrPreferencesReport();
            if (violatedDistrPreferencesReport != null && !violatedDistrPreferencesReport.getGroups().isEmpty())
                request.setAttribute("SolutionReport.violatedDistrPreferencesReportTable",
                        getViolatedDistrPreferencesReportTable(request, violatedDistrPreferencesReport, false)
                                .printTable(WebTable.getOrder(sessionContext,
                                        "solutionReports.violDistPrefReport.ord")));
            DiscouragedInstructorBtbReport discouragedInstructorBtbReportReport = solver
                    .getDiscouragedInstructorBtbReport();
            if (discouragedInstructorBtbReportReport != null
                    && !discouragedInstructorBtbReportReport.getGroups().isEmpty())
                request.setAttribute("SolutionReport.discouragedInstructorBtbReportReportTable",
                        getDiscouragedInstructorBtbReportReportTable(request,
                                discouragedInstructorBtbReportReport, false).printTable(
                                        WebTable.getOrder(sessionContext, "solutionReports.violInstBtb.ord")));
            StudentConflictsReport studentConflictsReport = solver.getStudentConflictsReport();
            if (studentConflictsReport != null && !studentConflictsReport.getGroups().isEmpty())
                request.setAttribute("SolutionReport.studentConflictsReportTable",
                        getStudentConflictsReportTable(request, studentConflictsReport, false)
                                .printTable(WebTable.getOrder(sessionContext, "solutionReports.studConf.ord")));
            SameSubpartBalancingReport sameSubpartBalancingReport = solver.getSameSubpartBalancingReport();
            if (sameSubpartBalancingReport != null && !sameSubpartBalancingReport.getGroups().isEmpty())
                request.setAttribute("SolutionReport.sameSubpartBalancingReportTable",
                        getSameSubpartBalancingReportTable(request, sameSubpartBalancingReport, false)
                                .printTable(PdfWebTable.getOrder(sessionContext,
                                        "solutionReports.sectBalancingReport.ord")));
            PerturbationReport perturbationReport = solver.getPerturbationReport();
            if (perturbationReport != null && !perturbationReport.getGroups().isEmpty())
                request.setAttribute("SolutionReport.perturbationReportTable",
                        getPerturbationReportTable(request, perturbationReport, false)
                                .printTable(WebTable.getOrder(sessionContext, "solutionReports.pert.ord")));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    if ("Export PDF".equals(op)) {
        OutputStream out = ExportUtils.getPdfOutputStream(response, "report");

        Document doc = new Document(
                new Rectangle(60f + PageSize.LETTER.getHeight(), 60f + 0.75f * PageSize.LETTER.getHeight()), 30,
                30, 30, 30);

        PdfWriter iWriter = PdfWriter.getInstance(doc, out);
        iWriter.setPageEvent(new PdfEventHandler());
        doc.open();

        boolean atLeastOneRoomReport = false;
        for (RoomType type : RoomType.findAll()) {
            RoomReport roomReport = solver.getRoomReport(sessionDays, startDayDayOfWeek, type.getUniqueId());
            if (roomReport == null || roomReport.getGroups().isEmpty())
                continue;
            PdfWebTable table = getRoomReportTable(request, roomReport, true, type.getUniqueId());
            if (table == null)
                continue;
            PdfPTable pdfTable = table
                    .printPdfTable(WebTable.getOrder(sessionContext, "solutionReports.roomReport.ord"));
            if (!atLeastOneRoomReport) {
                doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth()));
                doc.newPage();
            }
            doc.add(new Paragraph(table.getName(), PdfFont.getBigFont(true)));
            doc.add(pdfTable);
            atLeastOneRoomReport = true;
        }
        RoomReport roomReport = solver.getRoomReport(sessionDays, startDayDayOfWeek, null);
        if (roomReport != null && !roomReport.getGroups().isEmpty()) {
            PdfWebTable table = getRoomReportTable(request, roomReport, true, null);
            if (table != null) {
                PdfPTable pdfTable = table
                        .printPdfTable(WebTable.getOrder(sessionContext, "solutionReports.roomReport.ord"));
                if (!atLeastOneRoomReport) {
                    doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth()));
                    doc.newPage();
                }
                doc.add(new Paragraph(table.getName(), PdfFont.getBigFont(true)));
                doc.add(pdfTable);
                atLeastOneRoomReport = true;
            }
        }

        if (atLeastOneRoomReport) {
            PdfPTable pdfTable = new PdfPTable(new float[] { 10f, 100f });
            pdfTable.setWidthPercentage(100);
            pdfTable.getDefaultCell().setPadding(3);
            pdfTable.getDefaultCell().setBorderWidth(0);
            pdfTable.setSplitRows(false);
            pdfTable.addCell("Group");
            pdfTable.addCell("group size <minimum, maximum)");
            pdfTable.addCell("Size");
            pdfTable.addCell("actual group size (size of the smallest and the biggest room in the group)");
            pdfTable.addCell("NrRooms");
            pdfTable.addCell("number of rooms in the group");
            pdfTable.addCell("ClUse");
            pdfTable.addCell("number of classes that are using a room from the group (actual solution)");
            pdfTable.addCell("ClShould");
            pdfTable.addCell(
                    "number of classes that \"should\" use a room of the group (smallest available room of a class is in this group)");
            pdfTable.addCell("ClMust");
            pdfTable.addCell(
                    "number of classes that must use a room of the group (all available rooms of a class are in this group)");
            pdfTable.addCell("HrUse");
            pdfTable.addCell("average hours a room of the group is used (actual solution)");
            pdfTable.addCell("HrShould");
            pdfTable.addCell(
                    "average hours a room of the group should be used (smallest available room of a class is in this group)");
            pdfTable.addCell("HrMust");
            pdfTable.addCell(
                    "average hours a room of this group must be used (all available rooms of a class are in this group)");
            pdfTable.addCell("");
            pdfTable.addCell("*) cumulative numbers (group minimum ... inf) are displayed in parentheses.");
            doc.add(pdfTable);
        }

        DiscouragedInstructorBtbReport discouragedInstructorBtbReportReport = solver
                .getDiscouragedInstructorBtbReport();
        if (discouragedInstructorBtbReportReport != null
                && !discouragedInstructorBtbReportReport.getGroups().isEmpty()) {
            PdfWebTable table = getDiscouragedInstructorBtbReportReportTable(request,
                    discouragedInstructorBtbReportReport, true);
            PdfPTable pdfTable = table
                    .printPdfTable(WebTable.getOrder(sessionContext, "solutionReports.violInstBtb.ord"));
            doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth()));
            doc.newPage();
            doc.add(new Paragraph(table.getName(), PdfFont.getBigFont(true)));
            doc.add(pdfTable);
        }

        ViolatedDistrPreferencesReport violatedDistrPreferencesReport = solver
                .getViolatedDistrPreferencesReport();
        if (violatedDistrPreferencesReport != null && !violatedDistrPreferencesReport.getGroups().isEmpty()) {
            PdfWebTable table = getViolatedDistrPreferencesReportTable(request, violatedDistrPreferencesReport,
                    true);
            PdfPTable pdfTable = table
                    .printPdfTable(WebTable.getOrder(sessionContext, "solutionReports.violDistPrefReport.ord"));
            doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth()));
            doc.newPage();
            doc.add(new Paragraph(table.getName(), PdfFont.getBigFont(true)));
            doc.add(pdfTable);
        }

        StudentConflictsReport studentConflictsReport = solver.getStudentConflictsReport();
        if (studentConflictsReport != null && !studentConflictsReport.getGroups().isEmpty()) {
            PdfWebTable table = getStudentConflictsReportTable(request, studentConflictsReport, true);
            PdfPTable pdfTable = table
                    .printPdfTable(WebTable.getOrder(sessionContext, "solutionReports.studConf.ord"));
            doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth()));
            doc.newPage();
            doc.add(new Paragraph(table.getName(), PdfFont.getBigFont(true)));
            doc.add(pdfTable);
        }

        SameSubpartBalancingReport sameSubpartBalancingReport = solver.getSameSubpartBalancingReport();
        if (sameSubpartBalancingReport != null && !sameSubpartBalancingReport.getGroups().isEmpty()) {
            PdfWebTable table = getSameSubpartBalancingReportTable(request, sameSubpartBalancingReport, true);
            PdfPTable pdfTable = table.printPdfTable(
                    WebTable.getOrder(sessionContext, "solutionReports.sectBalancingReport.ord"));
            doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth()));
            doc.newPage();
            doc.add(new Paragraph(table.getName(), PdfFont.getBigFont(true)));
            doc.add(pdfTable);
        }

        DeptBalancingReport deptBalancingReport = solver.getDeptBalancingReport();
        if (deptBalancingReport != null && !deptBalancingReport.getGroups().isEmpty()) {
            PdfWebTable table = getDeptBalancingReportTable(request, deptBalancingReport, true);
            PdfPTable pdfTable = table.printPdfTable(
                    WebTable.getOrder(sessionContext, "solutionReports.deptBalancingReport.ord"));
            doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth()));
            doc.newPage();
            doc.add(new Paragraph(table.getName(), PdfFont.getBigFont(true)));
            doc.add(pdfTable);
        }

        PerturbationReport perturbationReport = solver.getPerturbationReport();
        if (perturbationReport != null && !perturbationReport.getGroups().isEmpty()) {
            PdfWebTable table = getPerturbationReportTable(request, perturbationReport, true);
            PdfPTable pdfTable = table
                    .printPdfTable(WebTable.getOrder(sessionContext, "solutionReports.pert.ord"));
            doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth()));
            doc.newPage();
            doc.add(new Paragraph(table.getName(), PdfFont.getBigFont(true)));
            doc.add(pdfTable);
            pdfTable = new PdfPTable(new float[] { 5f, 100f });
            pdfTable.setWidthPercentage(100);
            pdfTable.getDefaultCell().setPadding(3);
            pdfTable.getDefaultCell().setBorderWidth(0);
            pdfTable.setSplitRows(false);
            pdfTable.addCell("Class");
            pdfTable.addCell("Class name");
            pdfTable.addCell("Time");
            pdfTable.addCell("Time (initial -> assigned)");
            pdfTable.addCell("Room");
            pdfTable.addCell("Room (initial -> assigned)");
            pdfTable.addCell("Dist");
            pdfTable.addCell("Distance between assignments (if different are used buildings)");
            pdfTable.addCell("St");
            pdfTable.addCell("Number of affected students");
            pdfTable.addCell("StT");
            pdfTable.addCell("Number of affected students by time change");
            pdfTable.addCell("StR");
            pdfTable.addCell("Number of affected students by room change");
            pdfTable.addCell("StB");
            pdfTable.addCell("Number of affected students by building change");
            pdfTable.addCell("Ins");
            pdfTable.addCell("Number of affected instructors");
            pdfTable.addCell("InsT");
            pdfTable.addCell("Number of affected instructors by time change");
            pdfTable.addCell("InsR");
            pdfTable.addCell("Number of affected instructors by room change");
            pdfTable.addCell("InsB");
            pdfTable.addCell("Number of affected instructors by building change");
            pdfTable.addCell("Rm");
            pdfTable.addCell("Number of rooms changed");
            pdfTable.addCell("Bld");
            pdfTable.addCell("Number of buildings changed");
            pdfTable.addCell("Tm");
            pdfTable.addCell("Number of times changed");
            pdfTable.addCell("Day");
            pdfTable.addCell("Number of days changed");
            pdfTable.addCell("Hr");
            pdfTable.addCell("Number of hours changed");
            pdfTable.addCell("TFSt");
            pdfTable.addCell("Assigned building too far for instructor (from the initial one)");
            pdfTable.addCell("TFIns");
            pdfTable.addCell("Assigned building too far for students (from the initial one)");
            pdfTable.addCell("DStC");
            pdfTable.addCell("Difference in student conflicts");
            pdfTable.addCell("NStC");
            pdfTable.addCell("Number of new student conflicts");
            pdfTable.addCell("DTPr");
            pdfTable.addCell("Difference in time preferences");
            pdfTable.addCell("DRPr");
            pdfTable.addCell("Difference in room preferences");
            pdfTable.addCell("DInsB");
            pdfTable.addCell("Difference in back-to-back instructor preferences");
            doc.add(pdfTable);
        }

        doc.close();

        out.flush();
        out.close();

        return null;
    }

    return mapping.findForward("showSolutionReport");
}

From source file:org.unitime.timetable.export.PDFPrinter.java

License:Open Source License

@Override
public void close() throws IOException {
    try {/*from ww  w .j  a  v  a 2  s.  com*/
        float width = 0;
        float[] w = new float[iMaxWidth.length - iHiddenColumns.size()];
        int wi = 0;
        for (int i = 0; i < iMaxWidth.length; i++)
            if (!iHiddenColumns.contains(i)) {
                width += 15f + iMaxWidth[i];
                w[wi++] = iMaxWidth[i];
            }
        Document document = new Document(new Rectangle(60f + width, 60f + width * 0.75f), 30f, 30f, 30f, 30f);
        PdfWriter writer = PdfWriter.getInstance(document, iOutput);
        writer.setPageEvent(new PdfEventHandler());
        document.open();
        iTable.setWidths(w);
        document.add(iTable);
        document.close();
    } catch (DocumentException e) {
        throw new IOException(e.getMessage(), e);
    }
}