List of usage examples for com.lowagie.text.pdf PdfPTable setWidthPercentage
public void setWidthPercentage(float widthPercentage)
From source file:org.tellervo.desktop.print.BasicBoxLabel.java
License:Open Source License
/** * Get PdfPTable containing the samples per object * /* w ww . jav a 2s . co m*/ * @return PdfPTable * @throws DocumentException */ private void addTable(WSIBox b) throws DocumentException { float[] widths = { 0.15f, 0.75f, 0.2f }; PdfPTable tbl = new PdfPTable(widths); PdfPCell headerCell = new PdfPCell(); tbl.setWidthPercentage(100f); // Write header cells of table headerCell.setBorderWidthBottom(headerLineWidth); headerCell.setBorderWidthTop(headerLineWidth); headerCell.setBorderWidthLeft(0); headerCell.setBorderWidthRight(0); headerCell.setPhrase(new Phrase("Object", tableHeaderFontLarge)); headerCell.setHorizontalAlignment(Element.ALIGN_LEFT); tbl.addCell(headerCell); headerCell.setPhrase(new Phrase("Elements", tableHeaderFontLarge)); headerCell.setHorizontalAlignment(Element.ALIGN_LEFT); tbl.addCell(headerCell); headerCell.setPhrase(new Phrase("# Samples", tableHeaderFontLarge)); headerCell.setHorizontalAlignment(Element.ALIGN_RIGHT); tbl.addCell(headerCell); // Find all objects associated with samples in this box SearchParameters objparam = new SearchParameters(SearchReturnObject.OBJECT); objparam.addSearchConstraint(SearchParameterName.SAMPLEBOXID, SearchOperator.EQUALS, b.getIdentifier().getValue().toString()); EntitySearchResource<TridasObject> objresource = new EntitySearchResource<TridasObject>(objparam); objresource.setProperty(TellervoResourceProperties.ENTITY_REQUEST_FORMAT, TellervoRequestFormat.COMPREHENSIVE); TellervoResourceAccessDialog dialog = new TellervoResourceAccessDialog(objresource); objresource.query(); dialog.setVisible(true); if (!dialog.isSuccessful()) { System.out.println("oopsey doopsey. Error getting objects"); return; } List<TridasObject> obj = objresource.getAssociatedResult(); // Check that there are not too many objects to fit on box label if (obj.size() > 10) { System.out.println("Warning this label has " + Integer.toString(obj.size()) + " objects associated with it so is unlikely to fit and may take some time to produce!"); } if (obj.size() < 4) { // Not many objects so add some space to the table for prettiness sake headerCell.setBorder(0); headerCell.setPhrase(new Phrase(" ")); tbl.addCell(headerCell); tbl.addCell(headerCell); tbl.addCell(headerCell); } // Sort objects into alphabetically order based on labcode TridasComparator sorter = new TridasComparator(); Collections.sort(obj, sorter); Integer sampleCountInBox = 0; // Loop through objects List<TridasObject> objdone = new ArrayList<TridasObject>(); // Array of top level objects that have already been dealt with mainobjloop: for (TridasObject myobj : obj) { // Need to check if this object has already been done as there will be duplicate top level objects if there are samples // from more than one subobject in the box if (objdone.size() > 0) { try { for (TridasObject tlo : objdone) { TridasObjectEx tloex = (TridasObjectEx) tlo; TridasObjectEx myobjex = (TridasObjectEx) myobj; if (tloex.getLabCode().compareTo(myobjex.getLabCode()) == 0) { // Object already been done so skip to next continue mainobjloop; } else { // Object has not been done so add to the done list and keep going objdone.add(myobj); } } } catch (Exception e) { } } else { objdone.add(myobj); } // Add object code to first column PdfPCell dataCell = new PdfPCell(); dataCell.setBorderWidthBottom(0); dataCell.setBorderWidthTop(0); dataCell.setBorderWidthLeft(0); dataCell.setBorderWidthRight(0); dataCell.setHorizontalAlignment(Element.ALIGN_LEFT); String objCode = null; if (myobj instanceof TridasObjectEx) objCode = ((TridasObjectEx) myobj).getLabCode(); dataCell.setPhrase(new Phrase(objCode, bodyFontLarge)); tbl.addCell(dataCell); // Search for elements associated with this object System.out.println("Starting search for elements associated with " + myobj.getTitle().toString()); SearchParameters sp = new SearchParameters(SearchReturnObject.ELEMENT); sp.addSearchConstraint(SearchParameterName.SAMPLEBOXID, SearchOperator.EQUALS, b.getIdentifier().getValue()); sp.addSearchConstraint(SearchParameterName.ANYPARENTOBJECTID, SearchOperator.EQUALS, myobj.getIdentifier().getValue()); EntitySearchResource<TridasElement> resource = new EntitySearchResource<TridasElement>(sp); resource.setProperty(TellervoResourceProperties.ENTITY_REQUEST_FORMAT, TellervoRequestFormat.SUMMARY); TellervoResourceAccessDialog dialog2 = new TellervoResourceAccessDialog(resource); resource.query(); dialog2.setVisible(true); if (!dialog2.isSuccessful()) { System.out.println("oopsey doopsey. Error getting elements"); return; } //XMLDebugView.showDialog(); List<TridasElement> elements = resource.getAssociatedResult(); TridasComparator numSorter = new TridasComparator(TridasComparator.Type.TITLES, TridasComparator.NullBehavior.NULLS_LAST, TridasComparator.CompareBehavior.AS_NUMBERS_THEN_STRINGS); Collections.sort(elements, numSorter); // Loop through elements Integer smpCnt = 0; ArrayList<String> numlist = new ArrayList<String>(); for (TridasElement myelem : elements) { // Add element title to string if (myelem.getTitle() != null) { String mytitle = myelem.getTitle(); numlist.add(mytitle); } // Grab associated samples and add count to running total List<TridasSample> samples = myelem.getSamples(); smpCnt += samples.size(); } // Add element names to second column dataCell.setPhrase(new Phrase(hyphenSummarize(numlist), bodyFontLarge)); tbl.addCell(dataCell); // Add sample count to third column dataCell.setPhrase(new Phrase(smpCnt.toString(), bodyFontLarge)); dataCell.setHorizontalAlignment(Element.ALIGN_RIGHT); tbl.addCell(dataCell); sampleCountInBox += smpCnt; } if (obj.size() < 4) { // Not many objects so add some space to the table for prettiness sake headerCell.setBorder(0); headerCell.setPhrase(new Phrase(" ")); tbl.addCell(headerCell); tbl.addCell(headerCell); tbl.addCell(headerCell); } headerCell.setBorderWidthBottom(headerLineWidth); headerCell.setBorderWidthTop(headerLineWidth); headerCell.setBorderWidthLeft(0); headerCell.setBorderWidthRight(0); headerCell.setPhrase(new Phrase(" ", bodyFontLarge)); tbl.addCell(headerCell); headerCell.setPhrase(new Phrase("Grand Total", tableHeaderFontLarge)); headerCell.setHorizontalAlignment(Element.ALIGN_RIGHT); tbl.addCell(headerCell); headerCell.setPhrase(new Phrase(sampleCountInBox.toString(), bodyFontLarge)); tbl.addCell(headerCell); // Add table to document document.add(tbl); }
From source file:org.tellervo.desktop.print.CompleteBoxLabel.java
License:Open Source License
/** * Get PdfPTable containing the samples per object * //from w w w . j a v a 2 s . c om * @return PdfPTable * @throws DocumentException */ private void addTable(WSIBox b) throws DocumentException { float[] widths = { 0.15f, 0.75f, 0.2f }; PdfPTable tbl = new PdfPTable(widths); PdfPCell headerCell = new PdfPCell(); tbl.setWidthPercentage(100f); // Write header cells of table headerCell.setBorderWidthBottom(headerLineWidth); headerCell.setBorderWidthTop(headerLineWidth); headerCell.setBorderWidthLeft(0); headerCell.setBorderWidthRight(0); headerCell.setPhrase(new Phrase("Object", tableHeaderFontLarge)); headerCell.setHorizontalAlignment(Element.ALIGN_LEFT); tbl.addCell(headerCell); headerCell.setPhrase(new Phrase("Elements", tableHeaderFontLarge)); headerCell.setHorizontalAlignment(Element.ALIGN_LEFT); tbl.addCell(headerCell); headerCell.setPhrase(new Phrase("# Samples", tableHeaderFontLarge)); headerCell.setHorizontalAlignment(Element.ALIGN_RIGHT); tbl.addCell(headerCell); // Find all objects associated with samples in this box SearchParameters objparam = new SearchParameters(SearchReturnObject.OBJECT); objparam.addSearchConstraint(SearchParameterName.SAMPLEBOXID, SearchOperator.EQUALS, b.getIdentifier().getValue().toString()); EntitySearchResource<TridasObject> objresource = new EntitySearchResource<TridasObject>(objparam); objresource.setProperty(TellervoResourceProperties.ENTITY_REQUEST_FORMAT, TellervoRequestFormat.COMPREHENSIVE); TellervoResourceAccessDialog dialog = new TellervoResourceAccessDialog(objresource); objresource.query(); dialog.setVisible(true); if (!dialog.isSuccessful()) { System.out.println("oopsey doopsey. Error getting objects"); return; } List<TridasObject> obj = objresource.getAssociatedResult(); // Check that there are not too many objects to fit on box label if (obj.size() > 10) { System.out.println("Warning this label has " + Integer.toString(obj.size()) + " objects associated with it so is unlikely to fit and may take some time to produce!"); } if (obj.size() < 4) { // Not many objects so add some space to the table for prettiness sake headerCell.setBorder(0); headerCell.setPhrase(new Phrase(" ")); tbl.addCell(headerCell); tbl.addCell(headerCell); tbl.addCell(headerCell); } // Sort objects into alphabetically order based on labcode TridasComparator sorter = new TridasComparator(); Collections.sort(obj, sorter); Integer sampleCountInBox = 0; // Loop through objects List<TridasObject> objlist = new ArrayList<TridasObject>(); // Array of top level objects that have already been dealt with for (TridasObject myobj : obj) { objlist.add(myobj); if (myobj.isSetObjects()) { for (TridasObject obj2 : myobj.getObjects()) { objlist.add(obj2); } } } Collections.sort(objlist, sorter); mainobjloop: for (TridasObject myobj : objlist) { // Need to check if this object has already been done as there will be duplicate top level objects if there are samples // from more than one subobject in the box /*if(objdone.size()>0) { try{for(TridasObject tlo : objdone){ TridasObjectEx tloex = (TridasObjectEx) tlo; TridasObjectEx myobjex = (TridasObjectEx) myobj; //if (tloex.getLabCode().compareTo(myobjex.getLabCode())==0){ // Object already been done so skip to next // continue mainobjloop; //} //else { // Object has not been done so add to the done list and keep going objdone.add(myobj); //} }} catch (Exception e){} } else { objdone.add(myobj); }*/ // Add object code to first column PdfPCell dataCell = new PdfPCell(); dataCell.setBorderWidthBottom(0); dataCell.setBorderWidthTop(0); dataCell.setBorderWidthLeft(0); dataCell.setBorderWidthRight(0); dataCell.setHorizontalAlignment(Element.ALIGN_LEFT); String objCode = null; if (myobj instanceof TridasObjectEx) objCode = ((TridasObjectEx) myobj).getMultiLevelLabCode(); // Search for elements associated with this object System.out.println("Starting search for elements associated with " + myobj.getTitle().toString()); SearchParameters sp = new SearchParameters(SearchReturnObject.ELEMENT); sp.addSearchConstraint(SearchParameterName.SAMPLEBOXID, SearchOperator.EQUALS, b.getIdentifier().getValue()); sp.addSearchConstraint(SearchParameterName.OBJECTID, SearchOperator.EQUALS, myobj.getIdentifier().getValue()); EntitySearchResource<TridasElement> resource = new EntitySearchResource<TridasElement>(sp); resource.setProperty(TellervoResourceProperties.ENTITY_REQUEST_FORMAT, TellervoRequestFormat.SUMMARY); TellervoResourceAccessDialog dialog2 = new TellervoResourceAccessDialog(resource); resource.query(); dialog2.setVisible(true); if (!dialog2.isSuccessful()) { System.out.println("oopsey doopsey. Error getting elements"); return; } //XMLDebugView.showDialog(); List<TridasElement> elements = resource.getAssociatedResult(); if (elements == null || elements.size() == 0) continue; dataCell.setPhrase(new Phrase(objCode, bodyFontLarge)); tbl.addCell(dataCell); TridasComparator numSorter = new TridasComparator(TridasComparator.Type.TITLES, TridasComparator.NullBehavior.NULLS_LAST, TridasComparator.CompareBehavior.AS_NUMBERS_THEN_STRINGS); Collections.sort(elements, numSorter); // Loop through elements Integer smpCnt = 0; ArrayList<String> numlist = new ArrayList<String>(); for (TridasElement myelem : elements) { // Add element title to string if (myelem.getTitle() != null) { String mytitle = myelem.getTitle(); numlist.add(mytitle); } // Grab associated samples and add count to running total List<TridasSample> samples = myelem.getSamples(); smpCnt += samples.size(); } // Add element names to second column dataCell.setPhrase(new Phrase(hyphenSummarize(numlist), bodyFontLarge)); tbl.addCell(dataCell); // Add sample count to third column dataCell.setPhrase(new Phrase(smpCnt.toString(), bodyFontLarge)); dataCell.setHorizontalAlignment(Element.ALIGN_RIGHT); tbl.addCell(dataCell); sampleCountInBox += smpCnt; } if (obj.size() < 4) { // Not many objects so add some space to the table for prettiness sake headerCell.setBorder(0); headerCell.setPhrase(new Phrase(" ")); tbl.addCell(headerCell); tbl.addCell(headerCell); tbl.addCell(headerCell); } headerCell.setBorderWidthBottom(headerLineWidth); headerCell.setBorderWidthTop(headerLineWidth); headerCell.setBorderWidthLeft(0); headerCell.setBorderWidthRight(0); headerCell.setPhrase(new Phrase(" ", bodyFontLarge)); tbl.addCell(headerCell); headerCell.setPhrase(new Phrase("Grand Total", tableHeaderFontLarge)); headerCell.setHorizontalAlignment(Element.ALIGN_RIGHT); tbl.addCell(headerCell); headerCell.setPhrase(new Phrase(sampleCountInBox.toString(), bodyFontLarge)); tbl.addCell(headerCell); // Add table to document document.add(tbl); }
From source file:org.tellervo.desktop.print.ProSheet.java
License:Open Source License
/** * Get PdfPTable containing the ring width data for this series * /* ww w .j a va2s . c o m*/ * @return PdfPTable * @throws DocumentException */ private void getElementTable() throws DocumentException { PdfPTable tbl = new PdfPTable(5); PdfPCell headerCell = new PdfPCell(); tbl.setWidthPercentage(100f); float[] widths = { 0.1f, 0.4f, 0.2f, 0.1f, 0.2f }; tbl.setWidths(widths); // Set up header headerCell.setPhrase(new Phrase("Element", tableHeaderFont)); headerCell.setBorderWidthBottom(headerLineWidth); headerCell.setBorderWidthTop(headerLineWidth); headerCell.setBorderWidthLeft(0); headerCell.setBorderWidthRight(0); headerCell.setPaddingTop(5); headerCell.setPaddingBottom(5); tbl.addCell(headerCell); headerCell.setPhrase(new Phrase("Comments", tableHeaderFont)); tbl.addCell(headerCell); headerCell.setPhrase(new Phrase("Taxon", tableHeaderFont)); tbl.addCell(headerCell); headerCell.setPhrase(new Phrase("# Rings", tableHeaderFont)); tbl.addCell(headerCell); headerCell.setPhrase(new Phrase("Dates", tableHeaderFont)); tbl.addCell(headerCell); // Loop through rows for (org.tellervo.desktop.sample.Element e : this.elements) { Sample s = null; try { s = e.load(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); continue; } // Find element details for this series SearchParameters param = new SearchParameters(SearchReturnObject.DERIVED_SERIES); param.addSearchConstraint(SearchParameterName.SERIESDBID, SearchOperator.EQUALS, s.getIdentifier().getValue().toString()); EntitySearchResource<TridasObject> searchResource = new EntitySearchResource<TridasObject>(param, TridasObject.class); searchResource.setProperty(TellervoResourceProperties.ENTITY_REQUEST_FORMAT, TellervoRequestFormat.COMPREHENSIVE); TellervoResourceAccessDialog dialog = new TellervoResourceAccessDialog(searchResource); searchResource.query(); dialog.setVisible(true); List<TridasObject> oblist = searchResource.getAssociatedResult(); if (oblist.size() != 1) { System.out.println(e.getName() + " has more than one (or no) associated objects so skipping"); continue; } TridasObject obj = oblist.get(0); List<TridasElement> ellist = obj.getElements(); if (ellist.size() != 1) { System.out.println(e.getName() + " has more than one (or no) associated element so skipping"); continue; } TridasElement el = ellist.get(0); // make lab code LabCode labcode = new LabCode(); labcode.appendSiteCode(((TridasObjectEx) obj).getLabCode()); labcode.setElementCode(el.getTitle()); PdfPCell dataCell = new PdfPCell(); dataCell.setBorderWidthBottom(0); dataCell.setBorderWidthTop(0); dataCell.setBorderWidthLeft(0); dataCell.setBorderWidthRight(0); dataCell.setPaddingTop(5); dataCell.setPaddingBottom(5); dataCell.setHorizontalAlignment(Element.ALIGN_LEFT); // Title Column dataCell.setPhrase(new Phrase(LabCodeFormatter.getSamplePrefixFormatter().format(labcode).toString(), tableBodyFont)); tbl.addCell(dataCell); // Comments Column if (el.getComments() != null) dataCell.setPhrase(new Phrase(el.getComments(), tableBodyFont)); else dataCell.setPhrase(new Phrase(" ", tableBodyFont)); tbl.addCell(dataCell); // Taxon Column dataCell.setHorizontalAlignment(Element.ALIGN_LEFT); dataCell.setPhrase(new Phrase(el.getTaxon().getNormal().toString(), tableBodyFont)); tbl.addCell(dataCell); // Rings Column dataCell.setHorizontalAlignment(Element.ALIGN_CENTER); dataCell.setPhrase(new Phrase(String.valueOf(s.countRings()), tableBodyFont)); tbl.addCell(dataCell); // Dates column String datingLabel; String datingType = s.getSeries().getInterpretation().getDating().getType().value().toString(); datingLabel = s.getSeries().getInterpretation().getFirstYear().getValue().toString(); if (datingType == "Absolute") { datingLabel += s.getSeries().getInterpretation().getFirstYear().getSuffix().toString(); } datingLabel += " - " + String.valueOf( s.getSeries().getInterpretation().getFirstYear().getValue().intValue() + s.countRings() - 1); if (datingType == "Relative") { datingLabel += " (Rel. Date)"; } dataCell.setHorizontalAlignment(Element.ALIGN_LEFT); dataCell.setPhrase(new Phrase(datingLabel, tableBodyFont)); tbl.addCell(dataCell); } // Add table to document document.add(tbl); }
From source file:org.tellervo.desktop.print.SeriesReport.java
License:Open Source License
private void getTableKey() throws DocumentException, IOException, IOException { PdfPTable mainTable = new PdfPTable(12); float[] widths = { 0.1f, 0.1f, 0.8f, 0.1f, 0.1f, 0.8f, 0.1f, 0.1f, 0.8f, 0.1f, 0.1f, 0.8f }; mainTable.setWidths(widths);/*from w w w .ja v a 2 s .c om*/ mainTable.setWidthPercentage(100); PdfPTable userRemarksTable = new PdfPTable(2); float[] widths2 = { 0.083f, 0.92f }; userRemarksTable.setWidths(widths2); userRemarksTable.setWidthPercentage(100); Boolean userRemarkUsed = false; DecadalModel model; model = new UnitAwareDecadalModel(s); int rows = model.getRowCount(); List<TridasRemark> masterList = null; // Loop through rows for (int row = 0; row < rows; row++) { // Loop through columns for (int col = 0; col < 11; col++) { org.tellervo.desktop.Year year = model.getYear(row, col); List<TridasRemark> remarksList = null; remarksList = s.getRemarksForYear(year); // If masterlist is still null initialize it with this remarks list if (remarksList.size() > 0 && masterList == null) masterList = remarksList; for (TridasRemark remark : remarksList) { if (!masterList.contains(remark)) masterList.add(remark); } } } for (TridasRemark remark : masterList) { PdfPCell iconCell = new PdfPCell(); PdfPCell equalsCell = new PdfPCell(); PdfPCell descriptionCell = new PdfPCell(); iconCell.setBorder(0); equalsCell.setBorder(0); descriptionCell.setBorder(0); iconCell.setVerticalAlignment(Element.ALIGN_TOP); equalsCell.setVerticalAlignment(Element.ALIGN_TOP); descriptionCell.setVerticalAlignment(Element.ALIGN_TOP); Image icon = null; String remarkStr = null; // Get actual icon (either tridas or tellervo) if (remark.isSetNormalTridas()) { remarkStr = remark.getNormalTridas().toString().toLowerCase(); remarkStr = remarkStr.replace("_", " "); icon = getTridasIcon(remark.getNormalTridas()); if (icon == null) icon = Builder.getITextImageMissingIcon(); } else if (TELLERVO.equals(remark.getNormalStd())) { remarkStr = remark.getNormal(); icon = getCorinaIcon(remark.getNormal()); if (icon == null) icon = Builder.getITextImageMissingIcon(); } else { if (!userRemarkUsed) { remarkStr = "User Remark (See Below)"; icon = Builder.getITextImageIcon("user.png"); userRemarkUsed = true; } else { // User remark and we already have a key for this so continue continue; } } iconCell.addElement(icon); equalsCell.addElement(new Phrase("=", tableBodyFont)); descriptionCell.addElement(new Phrase(WordUtils.capitalize(remarkStr), tableBodyFont)); mainTable.addCell(iconCell); mainTable.addCell(equalsCell); mainTable.addCell(descriptionCell); } // Pad out empty cells PdfPCell blankCell = new PdfPCell(); blankCell.addElement(new Phrase("")); blankCell.setBorder(0); for (int i = 0; i < 12; i++) { mainTable.addCell(blankCell); } document.add(mainTable); if (userRemarkUsed) { PdfPCell yearCell = new PdfPCell(); yearCell.setBorder(0); yearCell.setHorizontalAlignment(Element.ALIGN_RIGHT); yearCell.addElement(new Phrase("Year", tableHeaderFont)); userRemarksTable.addCell(yearCell); PdfPCell remarkCell = new PdfPCell(); remarkCell.setBorder(0); remarkCell.addElement(new Phrase("User ring remarks", tableHeaderFont)); userRemarksTable.addCell(remarkCell); for (int row = 0; row < rows; row++) { // Loop through columns for (int col = 0; col < 11; col++) { org.tellervo.desktop.Year year = model.getYear(row, col); List<TridasRemark> remarksList = null; remarksList = s.getRemarksForYear(year); for (TridasRemark remark : remarksList) { if (remark.isSetNormalTridas() || remark.isSetNormalStd()) continue; yearCell = new PdfPCell(); yearCell.setBorder(0); yearCell.setHorizontalAlignment(Element.ALIGN_RIGHT); yearCell.addElement(new Phrase(year.toString(), tableHeaderFont)); userRemarksTable.addCell(yearCell); remarkCell = new PdfPCell(); remarkCell.setBorder(0); remarkCell.addElement(new Phrase(remark.getValue(), tableBodyFont)); userRemarksTable.addCell(remarkCell); } } } document.add(userRemarksTable); } }
From source file:org.tellervo.desktop.print.SeriesReport.java
License:Open Source License
/** * Get PdfPTable containing the ring width data for this series * //from w w w .j av a 2s .c om * @return PdfPTable * @throws DocumentException * @throws IOException * @throws MalformedURLException */ private void getDataTable(Boolean wj) throws DocumentException, MalformedURLException, IOException { // THE actual table PdfPTable mainTable = new PdfPTable(11); // Cell for column headers PdfPCell colHeadCell = new PdfPCell(); // Model for data DecadalModel model; // Flag to show if there are *any* ring remarks Boolean hasRemarks = false; float[] columnWidths = new float[] { 20f, 8f, 8f, 8f, 8f, 8f, 8f, 8f, 8f, 8f, 8f }; mainTable.setWidths(columnWidths); mainTable.setWidthPercentage(100f); if (wj == true) { if (s.hasWeiserjahre() == true) { model = new WJTableModel(s); document.add(new Chunk("Weiserjahre:", subSubSectionFont)); } else { return; } } else { model = new UnitAwareDecadalModel(s); document.add(new Chunk("Ring widths:", subSubSectionFont)); } int rows = model.getRowCount(); // Do column headers if (wj == true) { colHeadCell.setPhrase(new Phrase("inc/dec", tableHeaderFont)); } else if (this.s.getTridasUnits() == null) { // Unitless colHeadCell.setPhrase(new Phrase(" ", tableHeaderFont)); } else { // Normal tridas units try { /*if(this.s.getTridasUnits().getNormalTridas().equals(NormalTridasUnit.MICROMETRES)) { colHeadCell.setPhrase(new Phrase("microns", tableHeaderFont)); }*/ // Use the current default display units colHeadCell.setPhrase(new Phrase(displayUnits.value(), tableHeaderFont)); /*if(displayUnits.equals(NormalTridasUnit.MICROMETRES)) { colHeadCell.setPhrase(new Phrase("microns", tableHeaderFont)); } else if(displayUnits.equals(NormalTridasUnit.HUNDREDTH_MM)) { colHeadCell.setPhrase(new Phrase("1/100th mm", tableHeaderFont)); } */ } catch (Exception e) { colHeadCell.setPhrase(new Phrase(" ", tableHeaderFont)); } } colHeadCell.setBorderWidthBottom(headerLineWidth); colHeadCell.setBorderWidthTop(headerLineWidth); colHeadCell.setBorderWidthLeft(headerLineWidth); colHeadCell.setBorderWidthRight(headerLineWidth); mainTable.addCell(colHeadCell); for (int i = 0; i < 10; i++) { colHeadCell.setPhrase(new Phrase(Integer.toString(i), tableHeaderFont)); colHeadCell.setHorizontalAlignment(Element.ALIGN_CENTER); colHeadCell.setBorderWidthBottom(headerLineWidth); colHeadCell.setBorderWidthTop(headerLineWidth); colHeadCell.setBorderWidthLeft(lineWidth); colHeadCell.setBorderWidthRight(lineWidth); if (i == 0) colHeadCell.setBorderWidthLeft(headerLineWidth); if (i == 9) colHeadCell.setBorderWidthRight(headerLineWidth); mainTable.addCell(colHeadCell); } // Loop through rows for (int row = 0; row < rows; row++) { // Loop through columns for (int col = 0; col < 11; col++) { // Mini table to hold remark icons PdfPTable remarksMiniTable = new PdfPTable(3); float[] widths = { 0.3f, 0.3f, 0.6f }; remarksMiniTable.setWidths(widths); remarksMiniTable.setWidthPercentage(100); // Get ring value or year number for first column Phrase cellValuePhrase = null; Object value = model.getValueAt(row, col); if (value == null) { cellValuePhrase = new Phrase(""); } else { /*if(displayUnits.equals(NormalTridasUnit.HUNDREDTH_MM)) { try{ Integer val = (Integer) value; val =val/10; cellValuePhrase = new Phrase(String.valueOf(val), getTableFont(col)); } catch (Exception e){ cellValuePhrase = new Phrase(value.toString(), getTableFont(col)); } } else if(displayUnits.equals(NormalTridasUnit.FIFTIETH_MM)) { try{ Integer val = (Integer) value; val =val/20; cellValuePhrase = new Phrase(String.valueOf(val), getTableFont(col)); } catch (Exception e){ cellValuePhrase = new Phrase(value.toString(), getTableFont(col)); } } else if(displayUnits.equals(NormalTridasUnit.TWENTIETH_MM)) { try{ Integer val = (Integer) value; val =val/50; cellValuePhrase = new Phrase(String.valueOf(val), getTableFont(col)); } catch (Exception e){ cellValuePhrase = new Phrase(value.toString(), getTableFont(col)); } } else if(displayUnits.equals(NormalTridasUnit.TENTH_MM)) { try{ Integer val = (Integer) value; val =val/100; cellValuePhrase = new Phrase(String.valueOf(val), getTableFont(col)); } catch (Exception e){ cellValuePhrase = new Phrase(value.toString(), getTableFont(col)); } } else if(displayUnits.equals(NormalTridasUnit.MICROMETRES)) {*/ cellValuePhrase = new Phrase(value.toString(), getTableFont(col)); //} } // Get any remarks and compile them into a mini table org.tellervo.desktop.Year year = model.getYear(row, col); List<TridasRemark> remarksList = null; remarksList = s.getRemarksForYear(year); // If there are remarks, cycle through them adding cells to the mini table if (col != 0 && remarksList.size() > 0) { hasRemarks = true; // Get icons for remarks int cellnum = 1; int remarknum = 0; for (TridasRemark remark : remarksList) { // Keep track of which remark we are on. remarknum++; // String for holding remark name for debugging String remstr = "?"; // The actual remark icon Image icon = null; // A table cell for the remark PdfPCell remarkCell = new PdfPCell(); // Set default attributes for remark and value cells remarkCell.setBorderWidthBottom(0); remarkCell.setBorderWidthTop(0); remarkCell.setBorderWidthLeft(0); remarkCell.setBorderWidthRight(0); remarkCell.setHorizontalAlignment(Element.ALIGN_RIGHT); remarkCell.setPadding(0); remarkCell.setUseBorderPadding(true); // A table cell for the ring width value PdfPCell valueCell = new PdfPCell(); valueCell = remarkCell; // Get actual icon (either tridas or tellervo) if (remark.isSetNormalTridas()) { remstr = remark.getNormalTridas().toString(); icon = getTridasIcon(remark.getNormalTridas()); if (icon == null) icon = Builder.getITextImageMissingIcon(); } else if (TELLERVO.equals(remark.getNormalStd())) { remstr = remark.getNormal(); icon = getCorinaIcon(remark.getNormal()); if (icon == null) icon = Builder.getITextImageMissingIcon(); } else { if (remark.isSetValue()) { remstr = remark.getValue(); } else if (remark.isSetNormal()) { remstr = remark.getNormal(); } else { remstr = "Unknown"; } icon = Builder.getITextImageIcon("user.png"); } // Print debug info for this remark String errStr = "Getting icon for " + remstr + " for year " + year.toString() + "(cell value = " + cellnum + ")"; System.out.print(errStr); // Shrink the icon a bit icon.scalePercent(20); // Add icon to minitable remarkCell.addElement(icon); remarksMiniTable.addCell(remarkCell); cellnum++; if (cellnum == 1 && remarksList.size() < cellnum) { // First cell and no remark so print blank valueCell.setPhrase(new Phrase("")); remarksMiniTable.addCell(valueCell); cellnum++; } if (cellnum == 2 && remarksList.size() < cellnum) { // Second cell and no remark so print blank valueCell.setPhrase(new Phrase("")); remarksMiniTable.addCell(valueCell); cellnum++; } if (cellnum == 3) { // In third cell so print value valueCell.setPhrase(cellValuePhrase); remarksMiniTable.addCell(valueCell); cellnum++; } else if (cellnum % 3 == 0) { // In third column so print blank valueCell.setPhrase(new Phrase("")); remarksMiniTable.addCell(valueCell); cellnum++; } if (remarknum == remarksList.size()) { valueCell.setPhrase(new Phrase("")); remarksMiniTable.addCell(valueCell); remarksMiniTable.addCell(valueCell); } remarkCell = null; valueCell = null; } } else { // No remarks so make mini table have blank, blank, value // Create blank and value cells PdfPCell blankCell = new PdfPCell(); PdfPCell valueCell = new PdfPCell(); // Set up style blankCell.setBorderWidthBottom(0); blankCell.setBorderWidthTop(0); blankCell.setBorderWidthLeft(0); blankCell.setBorderWidthRight(0); blankCell.setHorizontalAlignment(Element.ALIGN_RIGHT); blankCell.setPadding(0); blankCell.setUseBorderPadding(true); valueCell = blankCell; // Add cells to mini table remarksMiniTable.addCell(blankCell); remarksMiniTable.addCell(blankCell); valueCell.setPhrase(cellValuePhrase); remarksMiniTable.addCell(valueCell); } // Set border styles depending on where we are in the table // Defaults PdfPCell mainTableCell = new PdfPCell(); mainTableCell.setBorderWidthBottom(lineWidth); mainTableCell.setBorderWidthTop(lineWidth); mainTableCell.setBorderWidthLeft(lineWidth); mainTableCell.setBorderWidthRight(lineWidth); mainTableCell.setHorizontalAlignment(Element.ALIGN_RIGHT); // Row headers if (col == 0) { mainTableCell.setHorizontalAlignment(Element.ALIGN_LEFT); mainTableCell.setBorderWidthLeft(headerLineWidth); mainTableCell.setBorderWidthRight(headerLineWidth); } // First data column if (col == 1) { mainTableCell.setBorderWidthLeft(headerLineWidth); } // Last data column if (col == 10) { mainTableCell.setBorderWidthRight(headerLineWidth); } // Last row if (row == model.getRowCount() - 1) { mainTableCell.setBorderWidthBottom(headerLineWidth); } // Write mini table to cell mainTableCell.addElement(remarksMiniTable); //mainTableCell.addElement(userRemarksMiniTable); // Write cell to main table mainTable.addCell(mainTableCell); } } // Add table to document document.add(mainTable); if (!wj && hasRemarks) getTableKey(); }
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 www . j ava 2 s . c o m*/ try { for (RoomType type : RoomType.findAll()) { RoomReport roomReport = solver.getRoomReport(sessionDays, startDayDayOfWeek, type.getUniqueId()); if (roomReport != null && !roomReport.getGroups().isEmpty()) { WebTable t = getRoomReportTable(request, roomReport, false, type.getUniqueId()); if (t != null) request.setAttribute("SolutionReport.roomReportTable." + type.getReference(), t.printTable( WebTable.getOrder(sessionContext, "solutionReports.roomReport.ord"))); } } RoomReport roomReport = solver.getRoomReport(sessionDays, startDayDayOfWeek, null); if (roomReport != null && !roomReport.getGroups().isEmpty()) { WebTable t = getRoomReportTable(request, roomReport, false, null); if (t != null) request.setAttribute("SolutionReport.roomReportTable.nonUniv", t.printTable(WebTable.getOrder(sessionContext, "solutionReports.roomReport.ord"))); } DeptBalancingReport deptBalancingReport = solver.getDeptBalancingReport(); if (deptBalancingReport != null && !deptBalancingReport.getGroups().isEmpty()) request.setAttribute("SolutionReport.deptBalancingReportTable", getDeptBalancingReportTable(request, deptBalancingReport, false).printTable( WebTable.getOrder(sessionContext, "solutionReports.deptBalancingReport.ord"))); ViolatedDistrPreferencesReport violatedDistrPreferencesReport = solver .getViolatedDistrPreferencesReport(); if (violatedDistrPreferencesReport != null && !violatedDistrPreferencesReport.getGroups().isEmpty()) request.setAttribute("SolutionReport.violatedDistrPreferencesReportTable", getViolatedDistrPreferencesReportTable(request, violatedDistrPreferencesReport, false) .printTable(WebTable.getOrder(sessionContext, "solutionReports.violDistPrefReport.ord"))); DiscouragedInstructorBtbReport discouragedInstructorBtbReportReport = solver .getDiscouragedInstructorBtbReport(); if (discouragedInstructorBtbReportReport != null && !discouragedInstructorBtbReportReport.getGroups().isEmpty()) request.setAttribute("SolutionReport.discouragedInstructorBtbReportReportTable", getDiscouragedInstructorBtbReportReportTable(request, discouragedInstructorBtbReportReport, false).printTable( WebTable.getOrder(sessionContext, "solutionReports.violInstBtb.ord"))); StudentConflictsReport studentConflictsReport = solver.getStudentConflictsReport(); if (studentConflictsReport != null && !studentConflictsReport.getGroups().isEmpty()) request.setAttribute("SolutionReport.studentConflictsReportTable", getStudentConflictsReportTable(request, studentConflictsReport, false) .printTable(WebTable.getOrder(sessionContext, "solutionReports.studConf.ord"))); SameSubpartBalancingReport sameSubpartBalancingReport = solver.getSameSubpartBalancingReport(); if (sameSubpartBalancingReport != null && !sameSubpartBalancingReport.getGroups().isEmpty()) request.setAttribute("SolutionReport.sameSubpartBalancingReportTable", getSameSubpartBalancingReportTable(request, sameSubpartBalancingReport, false) .printTable(PdfWebTable.getOrder(sessionContext, "solutionReports.sectBalancingReport.ord"))); PerturbationReport perturbationReport = solver.getPerturbationReport(); if (perturbationReport != null && !perturbationReport.getGroups().isEmpty()) request.setAttribute("SolutionReport.perturbationReportTable", getPerturbationReportTable(request, perturbationReport, false) .printTable(WebTable.getOrder(sessionContext, "solutionReports.pert.ord"))); } catch (Exception e) { e.printStackTrace(); } } if ("Export PDF".equals(op)) { OutputStream out = ExportUtils.getPdfOutputStream(response, "report"); Document doc = new Document( new Rectangle(60f + PageSize.LETTER.getHeight(), 60f + 0.75f * PageSize.LETTER.getHeight()), 30, 30, 30, 30); PdfWriter iWriter = PdfWriter.getInstance(doc, out); iWriter.setPageEvent(new PdfEventHandler()); doc.open(); boolean atLeastOneRoomReport = false; for (RoomType type : RoomType.findAll()) { RoomReport roomReport = solver.getRoomReport(sessionDays, startDayDayOfWeek, type.getUniqueId()); if (roomReport == null || roomReport.getGroups().isEmpty()) continue; PdfWebTable table = getRoomReportTable(request, roomReport, true, type.getUniqueId()); if (table == null) continue; PdfPTable pdfTable = table .printPdfTable(WebTable.getOrder(sessionContext, "solutionReports.roomReport.ord")); if (!atLeastOneRoomReport) { doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth())); doc.newPage(); } doc.add(new Paragraph(table.getName(), PdfFont.getBigFont(true))); doc.add(pdfTable); atLeastOneRoomReport = true; } RoomReport roomReport = solver.getRoomReport(sessionDays, startDayDayOfWeek, null); if (roomReport != null && !roomReport.getGroups().isEmpty()) { PdfWebTable table = getRoomReportTable(request, roomReport, true, null); if (table != null) { PdfPTable pdfTable = table .printPdfTable(WebTable.getOrder(sessionContext, "solutionReports.roomReport.ord")); if (!atLeastOneRoomReport) { doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth())); doc.newPage(); } doc.add(new Paragraph(table.getName(), PdfFont.getBigFont(true))); doc.add(pdfTable); atLeastOneRoomReport = true; } } if (atLeastOneRoomReport) { PdfPTable pdfTable = new PdfPTable(new float[] { 10f, 100f }); pdfTable.setWidthPercentage(100); pdfTable.getDefaultCell().setPadding(3); pdfTable.getDefaultCell().setBorderWidth(0); pdfTable.setSplitRows(false); pdfTable.addCell("Group"); pdfTable.addCell("group size <minimum, maximum)"); pdfTable.addCell("Size"); pdfTable.addCell("actual group size (size of the smallest and the biggest room in the group)"); pdfTable.addCell("NrRooms"); pdfTable.addCell("number of rooms in the group"); pdfTable.addCell("ClUse"); pdfTable.addCell("number of classes that are using a room from the group (actual solution)"); pdfTable.addCell("ClShould"); pdfTable.addCell( "number of classes that \"should\" use a room of the group (smallest available room of a class is in this group)"); pdfTable.addCell("ClMust"); pdfTable.addCell( "number of classes that must use a room of the group (all available rooms of a class are in this group)"); pdfTable.addCell("HrUse"); pdfTable.addCell("average hours a room of the group is used (actual solution)"); pdfTable.addCell("HrShould"); pdfTable.addCell( "average hours a room of the group should be used (smallest available room of a class is in this group)"); pdfTable.addCell("HrMust"); pdfTable.addCell( "average hours a room of this group must be used (all available rooms of a class are in this group)"); pdfTable.addCell(""); pdfTable.addCell("*) cumulative numbers (group minimum ... inf) are displayed in parentheses."); doc.add(pdfTable); } DiscouragedInstructorBtbReport discouragedInstructorBtbReportReport = solver .getDiscouragedInstructorBtbReport(); if (discouragedInstructorBtbReportReport != null && !discouragedInstructorBtbReportReport.getGroups().isEmpty()) { PdfWebTable table = getDiscouragedInstructorBtbReportReportTable(request, discouragedInstructorBtbReportReport, true); PdfPTable pdfTable = table .printPdfTable(WebTable.getOrder(sessionContext, "solutionReports.violInstBtb.ord")); doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth())); doc.newPage(); doc.add(new Paragraph(table.getName(), PdfFont.getBigFont(true))); doc.add(pdfTable); } ViolatedDistrPreferencesReport violatedDistrPreferencesReport = solver .getViolatedDistrPreferencesReport(); if (violatedDistrPreferencesReport != null && !violatedDistrPreferencesReport.getGroups().isEmpty()) { PdfWebTable table = getViolatedDistrPreferencesReportTable(request, violatedDistrPreferencesReport, true); PdfPTable pdfTable = table .printPdfTable(WebTable.getOrder(sessionContext, "solutionReports.violDistPrefReport.ord")); doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth())); doc.newPage(); doc.add(new Paragraph(table.getName(), PdfFont.getBigFont(true))); doc.add(pdfTable); } StudentConflictsReport studentConflictsReport = solver.getStudentConflictsReport(); if (studentConflictsReport != null && !studentConflictsReport.getGroups().isEmpty()) { PdfWebTable table = getStudentConflictsReportTable(request, studentConflictsReport, true); PdfPTable pdfTable = table .printPdfTable(WebTable.getOrder(sessionContext, "solutionReports.studConf.ord")); doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth())); doc.newPage(); doc.add(new Paragraph(table.getName(), PdfFont.getBigFont(true))); doc.add(pdfTable); } SameSubpartBalancingReport sameSubpartBalancingReport = solver.getSameSubpartBalancingReport(); if (sameSubpartBalancingReport != null && !sameSubpartBalancingReport.getGroups().isEmpty()) { PdfWebTable table = getSameSubpartBalancingReportTable(request, sameSubpartBalancingReport, true); PdfPTable pdfTable = table.printPdfTable( WebTable.getOrder(sessionContext, "solutionReports.sectBalancingReport.ord")); doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth())); doc.newPage(); doc.add(new Paragraph(table.getName(), PdfFont.getBigFont(true))); doc.add(pdfTable); } DeptBalancingReport deptBalancingReport = solver.getDeptBalancingReport(); if (deptBalancingReport != null && !deptBalancingReport.getGroups().isEmpty()) { PdfWebTable table = getDeptBalancingReportTable(request, deptBalancingReport, true); PdfPTable pdfTable = table.printPdfTable( WebTable.getOrder(sessionContext, "solutionReports.deptBalancingReport.ord")); doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth())); doc.newPage(); doc.add(new Paragraph(table.getName(), PdfFont.getBigFont(true))); doc.add(pdfTable); } PerturbationReport perturbationReport = solver.getPerturbationReport(); if (perturbationReport != null && !perturbationReport.getGroups().isEmpty()) { PdfWebTable table = getPerturbationReportTable(request, perturbationReport, true); PdfPTable pdfTable = table .printPdfTable(WebTable.getOrder(sessionContext, "solutionReports.pert.ord")); doc.setPageSize(new Rectangle(60f + table.getWidth(), 60f + 0.75f * table.getWidth())); doc.newPage(); doc.add(new Paragraph(table.getName(), PdfFont.getBigFont(true))); doc.add(pdfTable); pdfTable = new PdfPTable(new float[] { 5f, 100f }); pdfTable.setWidthPercentage(100); pdfTable.getDefaultCell().setPadding(3); pdfTable.getDefaultCell().setBorderWidth(0); pdfTable.setSplitRows(false); pdfTable.addCell("Class"); pdfTable.addCell("Class name"); pdfTable.addCell("Time"); pdfTable.addCell("Time (initial -> assigned)"); pdfTable.addCell("Room"); pdfTable.addCell("Room (initial -> assigned)"); pdfTable.addCell("Dist"); pdfTable.addCell("Distance between assignments (if different are used buildings)"); pdfTable.addCell("St"); pdfTable.addCell("Number of affected students"); pdfTable.addCell("StT"); pdfTable.addCell("Number of affected students by time change"); pdfTable.addCell("StR"); pdfTable.addCell("Number of affected students by room change"); pdfTable.addCell("StB"); pdfTable.addCell("Number of affected students by building change"); pdfTable.addCell("Ins"); pdfTable.addCell("Number of affected instructors"); pdfTable.addCell("InsT"); pdfTable.addCell("Number of affected instructors by time change"); pdfTable.addCell("InsR"); pdfTable.addCell("Number of affected instructors by room change"); pdfTable.addCell("InsB"); pdfTable.addCell("Number of affected instructors by building change"); pdfTable.addCell("Rm"); pdfTable.addCell("Number of rooms changed"); pdfTable.addCell("Bld"); pdfTable.addCell("Number of buildings changed"); pdfTable.addCell("Tm"); pdfTable.addCell("Number of times changed"); pdfTable.addCell("Day"); pdfTable.addCell("Number of days changed"); pdfTable.addCell("Hr"); pdfTable.addCell("Number of hours changed"); pdfTable.addCell("TFSt"); pdfTable.addCell("Assigned building too far for instructor (from the initial one)"); pdfTable.addCell("TFIns"); pdfTable.addCell("Assigned building too far for students (from the initial one)"); pdfTable.addCell("DStC"); pdfTable.addCell("Difference in student conflicts"); pdfTable.addCell("NStC"); pdfTable.addCell("Number of new student conflicts"); pdfTable.addCell("DTPr"); pdfTable.addCell("Difference in time preferences"); pdfTable.addCell("DRPr"); pdfTable.addCell("Difference in room preferences"); pdfTable.addCell("DInsB"); pdfTable.addCell("Difference in back-to-back instructor preferences"); doc.add(pdfTable); } doc.close(); out.flush(); out.close(); return null; } return mapping.findForward("showSolutionReport"); }
From source file:org.unitime.timetable.webutil.PdfWebTable.java
License:Open Source License
/** * Prints pdf table. By default does not split table across * page boundaries //from w ww. jav a 2s. com * @param ordCol * @param keepTogether true does not split table across pages * @return */ public PdfPTable printPdfTable(int ordCol, boolean keepTogether) { PdfPTable table = new PdfPTable(getNrColumns()); table.setWidthPercentage(100); table.getDefaultCell().setPadding(3); table.getDefaultCell().setBorderWidth(0); table.setSplitRows(false); table.setKeepTogether(keepTogether); boolean asc = (ordCol == 0 || iAsc == null || iAsc.length <= Math.abs(ordCol) - 1 ? true : iAsc[Math.abs(ordCol) - 1]); if (ordCol < 0) asc = !asc; widths = new float[iColumns]; for (int i = 0; i < iColumns; i++) widths[i] = 0f; String lastLine[] = new String[Math.max(iColumns, (iHeaders == null ? 0 : iHeaders.length))]; if (iHeaders != null) { for (int i = 0; i < iColumns; i++) { if (isFiltered(i)) continue; PdfPCell c = createCell(); c.setBorderWidthBottom(1); float width = addText(c, iHeaders[i] == null ? "" : iHeaders[i], true); widths[i] = Math.max(widths[i], width); String align = (iAlign != null ? iAlign[i] : "left"); if ("left".equals(align)) c.setHorizontalAlignment(Element.ALIGN_LEFT); if ("right".equals(align)) c.setHorizontalAlignment(Element.ALIGN_RIGHT); if ("center".equals(align)) c.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(c); } table.setHeaderRows(1); } if (ordCol != 0) { Collections.sort(iLines, new WebTableComparator(Math.abs(ordCol) - 1, asc)); } for (int el = 0; el < iLines.size(); el++) { WebTableLine wtline = (WebTableLine) iLines.elementAt(el); String[] line = wtline.getLine(); boolean blank = iBlankWhenSame; for (int i = 0; i < iColumns; i++) { if (isFiltered(i)) continue; if (blank && line[i] != null && !line[i].equals(lastLine[i])) blank = false; PdfPCell c = createCell(); float width = addText(c, blank || line[i] == null ? "" : line[i], false); widths[i] = Math.max(widths[i], width); String align = (iAlign != null ? iAlign[i] : "left"); if ("left".equals(align)) c.setHorizontalAlignment(Element.ALIGN_LEFT); if ("right".equals(align)) c.setHorizontalAlignment(Element.ALIGN_RIGHT); if ("center".equals(align)) c.setHorizontalAlignment(Element.ALIGN_CENTER); applyPdfStyle(c, wtline, (el + 1 < iLines.size() ? (WebTableLine) iLines.elementAt(el + 1) : null), ordCol); table.addCell(c); lastLine[i] = line[i]; } } try { if (getNrFilteredColumns() < 0) { table.setWidths(widths); } else { float[] x = new float[getNrColumns()]; int idx = 0; for (int i = 0; i < iColumns; i++) { if (isFiltered(i)) continue; x[idx++] = widths[i]; } table.setWidths(x); } } catch (Exception e) { e.printStackTrace(); } return table; }
From source file:org.viafirma.util.QRCodeUtil.java
License:Apache License
/** * @param texto//from ww w . ja v a 2s .co m * Texto a colocar * @param textoQR * Imagen QR a colocar * @param codFirma * Cdigo de Firma a generar. * @param url Url del servicio de verificacin desde donde se puede descargar el documento. * @param document * Documeto destino * @param pageSize * Tamao de la pgina * @return * @throws BadElementException * @throws MalformedURLException * @throws IOException * @throws DocumentException * @throws ExcepcionErrorInterno */ private static float addContent(String texto, String url, String textoQR, String codFirma, Document document, Rectangle pageSize, boolean completo, boolean isSellado) throws BadElementException, MalformedURLException, IOException, DocumentException, ExcepcionErrorInterno { Image imagenCabezera = null; float widthCabecera = 0; float heightCabecera = 0; if (!isSellado) { // Recuperamos la imagen de cabecera imagenCabezera = Image.getInstance(QRCodeUtil.class.getResource(IMAGE_CABECERA)); // Colocamos la imagen en la zona superior de la pgina imagenCabezera.setAbsolutePosition(0, pageSize.getHeight() - imagenCabezera.getHeight()); heightCabecera = imagenCabezera.getHeight(); widthCabecera = imagenCabezera.getWidth(); } // Recuperamos el pie de firma Image imagenQR = Image.getInstance(QRCodeUtil.getInstance().generate(texto, url, textoQR, codFirma)); float rescalado = pageSize.getWidth() / (widthCabecera + document.leftMargin() + document.rightMargin()); float sizeCabecera = 0; if (rescalado < 1f && !isSellado) { // Requiere rescalado, la imagen es mayor que la pgina. imagenCabezera.scalePercent(rescalado * 100); sizeCabecera = rescalado * imagenCabezera.getHeight(); } float sizeCabecerayPie = HEIGHT_QR_CODE_PDF + sizeCabecera + document.bottomMargin() + document.topMargin() + SPACE_SEPARACION; // float escaleQR = HEIGHT_QR_CODE_PDF / (imagenQR.getHeight() + 5); float escaleQR = (pageSize.getWidth() - document.leftMargin() - document.rightMargin()) / (imagenQR.getWidth() + 6); // imagen.setSpacingAfter(120); if (!isSellado) { document.add(imagenCabezera); } // Aadimos una caja de texto si estamos mostrando el contenido del // fichero firmado. if (completo) { // Aadimos el espacio ocupado por la imagen Paragraph p = new Paragraph(""); p.setSpacingAfter(heightCabecera * rescalado); document.add(p); // Aadimos una tabla con borde donde colocar el documento. PdfPTable table = new PdfPTable(1); table.setWidthPercentage(100); table.getDefaultCell().setBorderWidth(10); PdfPCell celda = new PdfPCell(); celda.setFixedHeight(pageSize.getHeight() - sizeCabecerayPie); table.addCell(celda); table.setSpacingAfter(SPACE_SEPARACION); document.add(table); } if (completo) { // La imagen la colocamos justo debajo imagenQR.setAbsolutePosition(document.leftMargin(), escaleQR * HEIGHT_QR_CODE_PDF - SPACE_SEPARACION * 2); } else { imagenQR.setAbsolutePosition(document.leftMargin(), pageSize.getHeight() - sizeCabecerayPie); } imagenQR.scalePercent(escaleQR * 100); document.add(imagenQR); return sizeCabecerayPie; }
From source file:org.webguitoolkit.ui.util.export.PDFTableExport.java
License:Apache License
/** * @param table//from www. ja v a 2s .c o m * @param footer * @param header * @return */ public PdfPTable pdfExport(Table table) { TableExportOptions exportOptions = table.getExportOptions(); boolean showOnlyDisplayed = exportOptions.isShowOnlyDisplayedColumns(); Font headfont = new Font(Font.UNDEFINED, Font.DEFAULTSIZE, Font.BOLD); Font bodyfont = new Font(exportOptions.getPdfFontSize(), exportOptions.getPdfFontSize(), Font.NORMAL); if (exportOptions.getPdfFontColour() != null) { Color fontColor = exportOptions.getPdfFontColour(); bodyfont.setColor(fontColor); headfont.setColor(fontColor); } List<ITableColumn> columns = getTableColumns(showOnlyDisplayed, table); int columnCount = 0; for (int i = 0; i < columns.size(); i++) { TableColumn c = (TableColumn) columns.get(i); //hide select checkbox column if (!c.isExporatble()) continue; columnCount++; } PdfPTable resulttable = new PdfPTable(columnCount); resulttable.setWidthPercentage(100f); if (StringUtils.isNotEmpty(exportOptions.getTableHeadline())) { PdfPCell cell = new PdfPCell(new Paragraph(exportOptions.getTableHeadline())); cell.setColspan(columns.size()); cell.setBackgroundColor(Color.lightGray); resulttable.addCell(cell); } for (int i = 0; i < columns.size(); i++) { TableColumn c = (TableColumn) columns.get(i); // hide select checkbox column if (!c.isExporatble()) continue; String cellData = TextService.getString(c.getTitle()); if (cellData.contains("<br/>") || cellData.contains("<br>")) { cellData = cellData.replaceAll("<br\\/>", "\\/"); cellData = cellData.replaceAll("<br>", "\\/"); } PdfPCell cell = new PdfPCell(new Paragraph((cellData), headfont)); cell.setBackgroundColor(Color.lightGray); resulttable.addCell(cell); } List tabledata = table.getDefaultModel().getFilteredList(); if (tabledata.isEmpty()) { for (int i = 0; i < columns.size(); i++) { resulttable.addCell(new PdfPCell((new Phrase("")))); } } for (Iterator it = tabledata.iterator(); it.hasNext();) { DataBag dbag = (DataBag) it.next(); for (int i = 0; i < columns.size(); i++) { TableColumn tableColumn = (TableColumn) columns.get(i); if (!tableColumn.isExporatble()) continue; logger.debug("property: " + tableColumn.getProperty()); IColumnRenderer renderer = tableColumn.getRenderer(); Converter converter = tableColumn.getConverter(); addObjectCell(bodyfont, resulttable, dbag, tableColumn, renderer, converter); } } if (StringUtils.isNotEmpty(exportOptions.getTableFooter())) { PdfPCell cell = new PdfPCell(new Paragraph(exportOptions.getTableFooter())); cell.setColspan(columnCount); cell.setBackgroundColor(Color.lightGray); resulttable.addCell(cell); } resulttable.setHeaderRows(1); return resulttable; }
From source file:oscar.oscarEncounter.oscarConsultationRequest.pageUtil.ConsultationPDFCreator.java
License:Open Source License
/** * Creates and adds the table at the top of the document * which contains the consultation request. *///from w w w . j av a2 s . com private void createConsultationRequest() throws DocumentException { float[] tableWidths = { 1f, 1f }; PdfPTable table = new PdfPTable(1); PdfPCell cell; PdfPTable border, border2, border1; table.setWidthPercentage(95); // Creating a border for the entire request. border = new PdfPTable(1); addToTable(table, border, true); if (props.getProperty("faxLogoInConsultation") != null) { // Creating container for logo and clinic information table. border1 = new PdfPTable(tableWidths); addTable(border, border1); // Adding fax logo PdfPTable infoTable = createLogoHeader(); addToTable(border1, infoTable, false); // Adding clinic information to the border. infoTable = createClinicInfoHeader(); addToTable(border1, infoTable, false); } else { // Adding clinic information to the border. PdfPTable infoTable = createClinicInfoHeader(); addTable(border, infoTable); } // Add reply info PdfPTable infoTable = createReplyHeader(); addTable(border, infoTable); // Creating container for specialist and patient table. border2 = new PdfPTable(tableWidths); addTable(border, border2); // Adding specialist info to container. infoTable = createSpecialistTable(); addToTable(border2, infoTable, true); // Adding patient info to main table. infoTable = createPatientTable(); addToTable(border2, infoTable, true); // Creating a table with details for the consultation request. infoTable = createConsultDetailTable(); // Adding promotional information if appropriate. if (props.getProperty("FORMS_PROMOTEXT") != null) { cell = new PdfPCell(new Phrase(props.getProperty(""), font)); cell.setBorder(0); infoTable.addCell(cell); cell.setPhrase(new Phrase(props.getProperty("FORMS_PROMOTEXT"), font)); cell.setVerticalAlignment(Element.ALIGN_BOTTOM); cell.setHorizontalAlignment(Element.ALIGN_CENTER); infoTable.addCell(cell); } // Adding details and promotional information. addTable(border, infoTable); document.add(table); }