List of usage examples for com.lowagie.text Document setPageSize
public boolean setPageSize(Rectangle pageSize)
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 .j av a 2s. com 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.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 ww w. 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;// w ww . j a v a2s .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;/* w w w. j a v a 2 s. 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 w w . ja va 2s .c om*/ 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 w w . j ava2 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 ww w .java2 s . c o m*/ 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); } }
From source file:oscar.eform.util.EFormPDFServlet.java
License:Open Source License
private void addDocumentProps(Document document, String title, Properties props) { document.addTitle(title);/*from www .j a va2 s. c o m*/ document.addSubject(""); document.addKeywords("pdf, itext"); document.addCreator("OSCAR"); document.addAuthor(""); document.addHeader("Expires", "0"); // A0-A10, LEGAL, LETTER, HALFLETTER, _11x17, LEDGER, NOTE, B0-B5, ARCH_A-ARCH_E, FLSA // and FLSE // the following shows a temp way to get a print page size final String PAGESIZE = "printPageSize"; Rectangle pageSize = PageSize.LETTER; if ("PageSize.HALFLETTER".equals(props.getProperty(PAGESIZE))) pageSize = PageSize.HALFLETTER; if ("PageSize.A6".equals(props.getProperty(PAGESIZE))) pageSize = PageSize.A6; document.setPageSize(pageSize); document.open(); }
From source file:oscar.form.pdfservlet.FrmCustomedPDFServlet.java
License:Open Source License
protected ByteArrayOutputStream generatePDFDocumentBytes(final HttpServletRequest req, final ServletContext ctx) throws DocumentException { logger.debug("***in generatePDFDocumentBytes2 FrmCustomedPDFServlet.java***"); // added by vic, hsfo Enumeration<String> em = req.getParameterNames(); while (em.hasMoreElements()) { logger.debug("para=" + em.nextElement()); }/*from ww w . j a v a2 s. c o m*/ em = req.getAttributeNames(); while (em.hasMoreElements()) logger.debug("attr: " + em.nextElement()); if (HSFO_RX_DATA_KEY.equals(req.getParameter("__title"))) { return generateHsfoRxPDF(req); } String newline = System.getProperty("line.separator"); ByteArrayOutputStream baosPDF = new ByteArrayOutputStream(); PdfWriter writer = null; String method = req.getParameter("__method"); String origPrintDate = null; String numPrint = null; if (method != null && method.equalsIgnoreCase("rePrint")) { origPrintDate = req.getParameter("origPrintDate"); numPrint = req.getParameter("numPrints"); } logger.debug("method in generatePDFDocumentBytes " + method); String clinicName; String clinicTel; String clinicFax; // check if satellite clinic is used String useSatelliteClinic = req.getParameter("useSC"); logger.debug(useSatelliteClinic); if (useSatelliteClinic != null && useSatelliteClinic.equalsIgnoreCase("true")) { String scAddress = req.getParameter("scAddress"); logger.debug("clinic detail" + "=" + scAddress); HashMap<String, String> hm = parseSCAddress(scAddress); clinicName = hm.get("clinicName"); clinicTel = hm.get("clinicTel"); clinicFax = hm.get("clinicFax"); } else { // parameters need to be passed to header and footer clinicName = req.getParameter("clinicName"); logger.debug("clinicName" + "=" + clinicName); clinicTel = req.getParameter("clinicPhone"); clinicFax = req.getParameter("clinicFax"); } String patientPhone = req.getParameter("patientPhone"); String patientCityPostal = req.getParameter("patientCityPostal"); String patientAddress = req.getParameter("patientAddress"); String patientName = req.getParameter("patientName"); String sigDoctorName = req.getParameter("sigDoctorName"); String rxDate = req.getParameter("rxDate"); String rx = req.getParameter("rx"); String patientDOB = req.getParameter("patientDOB"); String showPatientDOB = req.getParameter("showPatientDOB"); String imgFile = req.getParameter("imgFile"); String patientHIN = req.getParameter("patientHIN"); String patientChartNo = req.getParameter("patientChartNo"); String pracNo = req.getParameter("pracNo"); Locale locale = req.getLocale(); boolean isShowDemoDOB = false; if (showPatientDOB != null && showPatientDOB.equalsIgnoreCase("true")) { isShowDemoDOB = true; } if (!isShowDemoDOB) patientDOB = ""; if (rx == null) { rx = ""; } String additNotes = req.getParameter("additNotes"); String[] rxA = rx.split(newline); List<String> listRx = new ArrayList<String>(); String listElem = ""; // parse rx and put into a list of rx; for (String s : rxA) { if (s.equals("") || s.equals(newline) || s.length() == 1) { listRx.add(listElem); listElem = ""; } else { listElem = listElem + s; listElem += newline; } } // get the print prop values Properties props = new Properties(); StringBuilder temp = new StringBuilder(); for (Enumeration<String> e = req.getParameterNames(); e.hasMoreElements();) { temp = new StringBuilder(e.nextElement().toString()); props.setProperty(temp.toString(), req.getParameter(temp.toString())); } for (Enumeration<String> e = req.getAttributeNames(); e.hasMoreElements();) { temp = new StringBuilder(e.nextElement().toString()); props.setProperty(temp.toString(), req.getAttribute(temp.toString()).toString()); } Document document = new Document(); try { String title = req.getParameter("__title") != null ? req.getParameter("__title") : "Unknown"; // specify the page of the picture using __graphicPage, it may be used multiple times to specify multiple pages // however the same graphic will be applied to all pages // ie. __graphicPage=2&__graphicPage=3 String[] cfgGraphicFile = req.getParameterValues("__cfgGraphicFile"); int cfgGraphicFileNo = cfgGraphicFile == null ? 0 : cfgGraphicFile.length; if (cfgGraphicFile != null) { // for (String s : cfgGraphicFile) { // p("cfgGraphicFile", s); // } } String[] graphicPage = req.getParameterValues("__graphicPage"); ArrayList<String> graphicPageArray = new ArrayList<String>(); if (graphicPage != null) { // for (String s : graphicPage) { // p("graphicPage", s); // } graphicPageArray = new ArrayList<String>(Arrays.asList(graphicPage)); } // A0-A10, LEGAL, LETTER, HALFLETTER, _11x17, LEDGER, NOTE, B0-B5, ARCH_A-ARCH_E, FLSA // and FLSE // the following shows a temp way to get a print page size Rectangle pageSize = PageSize.LETTER; String pageSizeParameter = req.getParameter("rxPageSize"); if (pageSizeParameter != null) { if ("PageSize.HALFLETTER".equals(pageSizeParameter)) { pageSize = PageSize.HALFLETTER; } else if ("PageSize.A6".equals(pageSizeParameter)) { pageSize = PageSize.A6; } else if ("PageSize.A4".equals(pageSizeParameter)) { pageSize = PageSize.A4; } } /* * if ("PageSize.HALFLETTER".equals(props.getProperty(PAGESIZE))) { pageSize = PageSize.HALFLETTER; } else if ("PageSize.A6".equals(props.getProperty(PAGESIZE))) { pageSize = PageSize.A6; } else if * ("PageSize.A4".equals(props.getProperty(PAGESIZE))) { pageSize = PageSize.A4; } */ // p("size of page ", props.getProperty(PAGESIZE)); document.setPageSize(pageSize); // 285=left margin+width of box, 5f is space for looking nice document.setMargins(15, pageSize.getWidth() - 285f + 5f, 170, 60);// left, right, top , bottom writer = PdfWriter.getInstance(document, baosPDF); writer.setPageEvent(new EndPage(clinicName, clinicTel, clinicFax, patientPhone, patientCityPostal, patientAddress, patientName, patientDOB, sigDoctorName, rxDate, origPrintDate, numPrint, imgFile, patientHIN, patientChartNo, pracNo, locale)); document.addTitle(title); document.addSubject(""); document.addKeywords("pdf, itext"); document.addCreator("OSCAR"); document.addAuthor(""); document.addHeader("Expires", "0"); document.open(); document.newPage(); PdfContentByte cb = writer.getDirectContent(); BaseFont bf; // = normFont; cb.setRGBColorStroke(0, 0, 255); // render prescriptions for (String rxStr : listRx) { bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Paragraph p = new Paragraph(new Phrase(rxStr, new Font(bf, 10))); p.setKeepTogether(true); p.setSpacingBefore(5f); document.add(p); } // render additional notes if (additNotes != null && !additNotes.equals("")) { bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Paragraph p = new Paragraph(new Phrase(additNotes, new Font(bf, 10))); p.setKeepTogether(true); p.setSpacingBefore(10f); document.add(p); } // render optometristEyeParam if (req.getAttribute("optometristEyeParam") != null) { bf = BaseFont.createFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); Paragraph p = new Paragraph( new Phrase("Eye " + (String) req.getAttribute("optometristEyeParam"), new Font(bf, 10))); p.setKeepTogether(true); p.setSpacingBefore(15f); document.add(p); } // render QrCode if (PrescriptionQrCodeUIBean.isPrescriptionQrCodeEnabledForCurrentProvider()) { Integer scriptId = Integer.parseInt(req.getParameter("scriptId")); byte[] qrCodeImage = PrescriptionQrCodeUIBean.getPrescriptionHl7QrCodeImage(scriptId); Image qrCode = Image.getInstance(qrCodeImage); document.add(qrCode); } } catch (DocumentException dex) { baosPDF.reset(); throw dex; } catch (Exception e) { logger.error("Error", e); } finally { if (document != null) { document.close(); } if (writer != null) { writer.close(); } } logger.debug("***END in generatePDFDocumentBytes2 FrmCustomedPDFServlet.java***"); return baosPDF; }
From source file:ppro.contoller.ExportController.java
public void preProcessPDF(Object document) throws IOException, DocumentException { final Document pdf = (Document) document; pdf.setPageSize(PageSize.A4.rotate()); pdf.open();/*from ww w . jav a 2s . c o m*/ String logo = getAbsolutePath("logo_1663576_web.jpg"); pdf.add(Image.getInstance(logo)); }