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: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 w w.jav 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.schreibubi.JCombinations.ui.GridChartPanel.java

License:Open Source License

/**
 * Create PDF//from   w  w  w .j ava2s.  com
 * 
 * @param name
 *            Filename
 * @param selection
 *            Selected Nodes
 * @param dm
 *            DataModel
 * @param pl
 *            ProgressListener
 */
@SuppressWarnings("unchecked")
public static void generatePDF(File name, DataModel dm, ArrayList<TreePath> selection, ProgressListener pl) {
    com.lowagie.text.Document document = new Document(PageSize.A4.rotate(), 50, 50, 50, 50);
    try {
        ArrayList<ExtendedJFreeChart> charts = dm.getCharts(selection);
        if (charts.size() > 0) {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(name));
            writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
            document.addAuthor("Jrg Werner");
            document.addSubject("Created by JCombinations");
            document.addKeywords("JCombinations");
            document.addCreator("JCombinations using iText");

            // we define a header and a footer
            HeaderFooter header = new HeaderFooter(new Phrase("JCombinations by Jrg Werner"), false);
            HeaderFooter footer = new HeaderFooter(new Phrase("Page "), new Phrase("."));
            footer.setAlignment(Element.ALIGN_CENTER);
            document.setHeader(header);
            document.setFooter(footer);

            document.open();
            DefaultFontMapper mapper = new DefaultFontMapper();
            FontFactory.registerDirectories();
            mapper.insertDirectory("c:\\WINNT\\fonts");

            PdfContentByte cb = writer.getDirectContent();

            pl.progressStarted(new ProgressEvent(GridChartPanel.class, 0, charts.size()));
            for (int i = 0; i < charts.size(); i++) {
                ExtendedJFreeChart chart = charts.get(i);
                PdfTemplate tp = cb.createTemplate(document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN),
                        document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN));
                Graphics2D g2d = tp.createGraphics(document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN),
                        document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN), mapper);
                Rectangle2D r2d = new Rectangle2D.Double(0, 0,
                        document.right(EXTRA_MARGIN) - document.left(EXTRA_MARGIN),
                        document.top(EXTRA_MARGIN) - document.bottom(EXTRA_MARGIN));
                chart.draw(g2d, r2d);
                g2d.dispose();
                cb.addTemplate(tp, document.left(EXTRA_MARGIN), document.bottom(EXTRA_MARGIN));
                PdfDestination destination = new PdfDestination(PdfDestination.FIT);
                TreePath treePath = chart.getTreePath();
                PdfOutline po = cb.getRootOutline();
                for (int j = 0; j < treePath.getPathCount(); j++) {
                    ArrayList<PdfOutline> lpo = po.getKids();
                    PdfOutline cpo = null;
                    for (PdfOutline outline : lpo)
                        if (outline.getTitle().compareTo(treePath.getPathComponent(j).toString()) == 0)
                            cpo = outline;
                    if (cpo == null)
                        cpo = new PdfOutline(po, destination, treePath.getPathComponent(j).toString());
                    po = cpo;
                }
                document.newPage();
                pl.progressIncremented(new ProgressEvent(GridChartPanel.class, i));
            }
            document.close();
            pl.progressEnded(new ProgressEvent(GridChartPanel.class));

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

From source file:org.silverpeas.components.almanach.control.AlmanachPdfGenerator.java

License:Open Source License

static public void buildPdf(String name, AlmanachSessionController almanach, String mode)
        throws AlmanachRuntimeException {
    try {/*w w  w .  j  ava  2  s.c om*/

        String fileName = FileRepositoryManager.getTemporaryPath(almanach.getSpaceId(),
                almanach.getComponentId()) + name;
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);

        // we add some meta information to the document
        document.addAuthor(almanach.getSettings().getString("author", ""));
        document.addSubject(almanach.getSettings().getString("subject", ""));
        document.addCreationDate();

        PdfWriter.getInstance(document, new FileOutputStream(fileName));
        document.open();

        try {
            Calendar currentDay = Calendar.getInstance();
            currentDay.setTime(almanach.getCurrentDay());
            String sHeader = almanach.getString("events");
            if (mode.equals(PDF_MONTH_ALLDAYS) || mode.equals(PDF_MONTH_EVENTSONLY)) {
                sHeader += " " + almanach.getString("GML.mois" + currentDay.get(Calendar.MONTH));
            }
            sHeader += " " + currentDay.get(Calendar.YEAR);
            HeaderFooter header = new HeaderFooter(new Phrase(sHeader), false);
            HeaderFooter footer = new HeaderFooter(new Phrase("Page "), true);
            footer.setAlignment(Element.ALIGN_CENTER);

            document.setHeader(header);
            document.setFooter(footer);

            createFirstPage(almanach, document);
            document.newPage();

            Font titleFont = new Font(Font.HELVETICA, 24, Font.NORMAL, new Color(255, 255, 255));
            Paragraph cTitle = new Paragraph(almanach.getString("Almanach") + " "
                    + almanach.getString("GML.mois" + currentDay.get(Calendar.MONTH)) + " "
                    + currentDay.get(Calendar.YEAR), titleFont);
            Chapter chapter = new Chapter(cTitle, 1);

            // Collection<EventDetail> events =
            // almanach.getListRecurrentEvent(mode.equals(PDF_YEAR_EVENTSONLY));
            AlmanachCalendarView almanachView;
            if (PDF_YEAR_EVENTSONLY.equals(mode)) {
                almanachView = almanach.getYearlyAlmanachCalendarView();
            } else {
                almanachView = almanach.getMonthlyAlmanachCalendarView();
            }

            List<DisplayableEventOccurrence> occurrences = almanachView.getEvents();
            generateAlmanach(chapter, almanach, occurrences, mode);

            document.add(chapter);
        } catch (Exception ex) {
            throw new AlmanachRuntimeException("PdfGenerator.generate", AlmanachRuntimeException.WARNING,
                    "AlmanachRuntimeException.EX_PROBLEM_TO_GENERATE_PDF", ex);
        }

        document.close();

    } catch (Exception e) {
        throw new AlmanachRuntimeException("PdfGenerator.generate", AlmanachRuntimeException.WARNING,
                "AlmanachRuntimeException.EX_PROBLEM_TO_GENERATE_PDF", e);
    }

}

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 {/*  w  ww  .j a  v  a2  s  . c om*/
            // 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.sonarqube.report.extendedpdf.OverviewPDFReporter.java

License:Open Source License

protected void printFrontPage(Document frontPageDocument, PdfWriter frontPageWriter)
        throws org.dom4j.DocumentException, ReportException {
    String frontPageTemplate = "/templates/frontpage.pdf";
    try {//from  w w  w.  j a  v  a 2 s.  c  o m
        PdfContentByte cb = frontPageWriter.getDirectContent();
        PdfReader reader = new PdfReader(this.getClass().getResourceAsStream(frontPageTemplate));
        PdfImportedPage page = frontPageWriter.getImportedPage(reader, 1);
        frontPageDocument.newPage();
        cb.addTemplate(page, 0, 0);

        Project project = getProject();

        Rectangle pageSize = frontPageDocument.getPageSize();
        PdfPTable projectInfo = new PdfPTable(1);
        projectInfo.getDefaultCell().setVerticalAlignment(PdfCell.ALIGN_MIDDLE);
        projectInfo.getDefaultCell().setHorizontalAlignment(PdfCell.ALIGN_LEFT);
        projectInfo.getDefaultCell().setBorder(Rectangle.BOTTOM);
        projectInfo.getDefaultCell().setPaddingBottom(10);
        projectInfo.getDefaultCell().setBorderColor(Color.GRAY);
        Font font = FontFactory.getFont(FontFactory.COURIER, 18, Font.NORMAL, Color.LIGHT_GRAY);

        Phrase projectName = new Phrase("Project: " + project.getName(), font);
        projectInfo.addCell(projectName);

        Phrase projectVersion = new Phrase("Version: " + project.getMeasures().getVersion(), font);
        projectInfo.addCell(projectVersion);

        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm");
        Phrase projectAnalysisDate = new Phrase("Analysis Date: " + df.format(project.getMeasures().getDate()),
                font);
        projectInfo.addCell(projectAnalysisDate);

        projectInfo.setTotalWidth(
                pageSize.getWidth() - frontPageDocument.leftMargin() * 2 - frontPageDocument.rightMargin() * 2);
        projectInfo.writeSelectedRows(0, -1, frontPageDocument.leftMargin(), pageSize.getHeight() - 575,
                frontPageWriter.getDirectContent());
        projectInfo.setSpacingAfter(10);
    } catch (IOException e) {
        Logger.error("Cannot find the required template: " + frontPageTemplate);
        e.printStackTrace();
    }
}

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;/* w  w 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;// ww  w  .  j av a2s  .c om
    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 w  w  .ja  v a 2  s  .  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 {//from   w  ww. ja  va2 s.c om
        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.solver.ExportTimetablePDF.java

License:Apache License

protected void printTables(FilterInterface filter, TimetableGridResponse response, ExportHelper helper)
        throws IOException {
    helper.setup("application/pdf", reference(), true);
    try {//from   w  w w . j  av a  2  s  .com
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, helper.getOutputStream());
        writer.setPageEvent(new PdfEventHandler());
        int index = 0;
        int margin = 50;
        int width = 1000;
        for (TimetableGridModel model : response.getModels())
            width = Math.max(width, pageWidth(filter, model, response.getWeekOffset()));
        int displayMode = Integer.valueOf(filter.getParameterValue("dispMode", "0"));
        int height = (displayMode == 2 ? (2 * margin + width) * 22 / 17 - 2 * margin
                : (2 * margin + width) * 17 / 22 - 2 * margin);
        for (TimetableGridModel model : response.getModels())
            height = Math.max(height, pageHeight(filter, model, response.getWeekOffset(), true));
        document.setPageSize(new Rectangle(width + 2 * margin, height + 2 * margin));
        document.setMargins(margin, margin, margin, margin);
        document.open();
        int used = 0;
        if (Integer.valueOf(filter.getParameterValue("dispMode", "0")) == 0) {
            boolean hasDay[] = { true, true, true, true, true, false, false };
            String days = filter.getParameterValue("days");
            if (days != null && days.length() == 7 && days.indexOf('1') >= 0) {
                for (int i = 0; i < 7; i++)
                    hasDay[i] = (days.charAt(i) == '1');
            }
            for (int i = 0; i < 7; i++) {
                if (!hasDay[i])
                    continue;
                String d = "";
                for (int j = 0; j < 7; j++)
                    d += (i == j ? "1" : "0");
                filter.getParameter("days").setValue(d);
                boolean first = true;
                for (TimetableGridModel model : response.getModels()) {
                    if (used > 0
                            && pageHeight(filter, model, response.getWeekOffset(), first) > height - used) {
                        document.newPage();
                        used = 0;
                    }
                    TimetableGrid tg = new TimetableGrid(filter, model, index++, width,
                            response.getWeekOffset(), used == 0 || first);
                    PdfContentByte canvas = writer.getDirectContent();
                    tg.print(canvas, margin, margin + used, height + 2 * margin, null);
                    used += tg.getHeight();
                    first = false;
                }
                used += 25;
            }
        } else {
            for (TimetableGridModel model : response.getModels()) {
                if (used > 0 && pageHeight(filter, model, response.getWeekOffset(), false) > height - used) {
                    document.newPage();
                    used = 0;
                }
                TimetableGrid tg = new TimetableGrid(filter, model, index++, width, response.getWeekOffset(),
                        used == 0);
                PdfContentByte canvas = writer.getDirectContent();
                tg.print(canvas, margin, margin + used, height + 2 * margin, null);
                used += tg.getHeight() + 25;
            }
        }
        if (document != null)
            document.close();
    } catch (DocumentException e) {
        throw new IOException(e.getMessage(), e);
    }
}