/** * To put a table within the existing table at the given position generateTable will of course * re-arrange the widths of the columns. * * @param aTable the table you want to insert * @param aLocation a <CODE>Point</CODE> */ public void insertTable(Table aTable, Point aLocation) { if (aTable == null) throw new NullPointerException( MessageLocalization.getComposedMessage("inserttable.table.has.null.value")); if (aLocation == null) throw new NullPointerException( MessageLocalization.getComposedMessage("inserttable.point.has.null.value")); mTableInserted = true; aTable.complete(); if (aLocation.y > columns) { throw new IllegalArgumentException( MessageLocalization.getComposedMessage( "inserttable.wrong.columnposition.1.of.location.max.eq.2", String.valueOf(aLocation.y), String.valueOf(columns))); } int rowCount = aLocation.x + 1 - rows.size(); int i = 0; if (rowCount > 0) { // create new rows ? for (; i < rowCount; i++) { rows.add(new Row(columns)); } } ((Row) rows.get(aLocation.x)).setElement(aTable, aLocation.y); setCurrentLocationToNextValidPosition(aLocation); }
/* * (non-Javadoc) * * @see com.afunms.report.ExportInterface#insertChart(java.lang.String) */ public void insertChart(String path) throws Exception { if (!document.isOpen()) { document.open(); } Image png = Image.getInstance(path); // png.scaleAbsolute(560, 320); png.scalePercent(90); Table pngtable = new Table(1); pngtable.setAutoFillEmptyCells(true); pngtable.setAlignment(Element.ALIGN_CENTER); pngtable.setCellsFitPage(true); pngtable.setWidth(100); pngtable.setBorder(0); RtfCell cell = new RtfCell(png); cell.setBorder(0); pngtable.addCell(cell); document.add(pngtable); }
/** * Extended headers / footers example * * @param args Unused */ public static void main(String[] args) { System.out.println("Demonstrates use of the RtfHeaderFooter for extended headers and footers"); try { Document document = new Document(); RtfWriter2.getInstance(document, new FileOutputStream("ExtendedHeaderFooter.rtf")); // Create the Paragraphs that will be used in the header. Paragraph date = new Paragraph("01.01.2010"); date.setAlignment(Paragraph.ALIGN_RIGHT); Paragraph address = new Paragraph("TheFirm\nTheRoad 24, TheCity\n" + "+00 99 11 22 33 44"); // Create the RtfHeaderFooter with an array containing the Paragraphs to add RtfHeaderFooter header = new RtfHeaderFooter(new Element[] {date, address}); // Set the header document.setHeader(header); // Create the table that will be used as the footer Table footer = new Table(2); footer.setBorder(0); footer.getDefaultCell().setBorder(0); footer.setWidth(100); footer.addCell(new Cell("(c) Mark Hall")); Paragraph pageNumber = new Paragraph("Page "); // The RtfPageNumber is an RTF specific element that adds a page number field pageNumber.add(new RtfPageNumber()); pageNumber.setAlignment(Paragraph.ALIGN_RIGHT); footer.addCell(new Cell(pageNumber)); // Create the RtfHeaderFooter and set it as the footer to use document.setFooter(new RtfHeaderFooter(footer)); document.open(); document.add( new Paragraph( "This document has headers and footers created" + " using the RtfHeaderFooter class.")); document.close(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (DocumentException de) { de.printStackTrace(); } }
@Override protected void buildPdfDocument( Map<String, Object> model, Document document, PdfWriter writer, HttpServletRequest request, HttpServletResponse response) throws Exception { Reservation reservation = (Reservation) model.get("reservation"); DateFormat df = new SimpleDateFormat("dd-MMM-yyyy"); Table table = new Table(4); table.addCell("ID"); table.addCell("Court name"); table.addCell("Date"); table.addCell("Hour"); table.addCell(Integer.toString(reservation.getId())); table.addCell(reservation.getCourtName()); table.addCell(df.format(reservation.getDate())); table.addCell(Integer.toString(reservation.getHour())); document.add(table); }
@Override public void buildPdfDocument( Map<String, Object> model, Document document, PdfWriter writer, HttpServletRequest request, HttpServletResponse response) { try { response.setContentType("application/pdf"); response.setHeader("Content-disposition", "attachment; filename=Report.pdf"); Table table = new Table(7); table.addCell("Candidate Id"); table.addCell("First Name"); table.addCell("Last Name"); table.addCell("Course"); table.addCell("Stream"); table.addCell("Email Id"); table.addCell("Cell Number"); document.add(table); } catch (Exception e) { e.printStackTrace(); } }
/* * (non-Javadoc) * * @see com.afunms.report.ExportInterface#insertTable(java.util.ArrayList) */ public void insertTable(ArrayList<String[]> tableal) throws Exception { // step 3: we open the document if (!document.isOpen()) { document.open(); } Table pdfTable = new Table(tableal.get(0).length); for (int k = 0; k < tableal.size(); k++) { String[] row = tableal.get(k); for (int j = 0; j < row.length; j++) { Cell pdfcell = new Cell(); if (k == 0) { pdfcell.addElement(new Paragraph(row[j], FontChineseTitle)); pdfcell.setBackgroundColor(Color.gray); pdfTable.endHeaders(); } else { pdfcell.addElement(new Paragraph(row[j], FontChineseRow)); if (k % 2 == 0) { pdfcell.setBackgroundColor(Color.LIGHT_GRAY); } } // 合并单元格 // pdfcell.setColspan(1); // pdfcell.setRowspan(1); // 对齐方式 pdfcell.setHorizontalAlignment(Element.ALIGN_CENTER); pdfcell.setVerticalAlignment(Element.ALIGN_MIDDLE); pdfTable.addCell(pdfcell); } } pdfTable.setWidth(100); // 设置表格填距 pdfTable.setPadding(5); pdfTable.setAlignment(Element.ALIGN_CENTER); // pdfTable.setTableFitsPage(true); document.add(pdfTable); // step 5: we close the document }
/** * Shows how a table is split if it doesn't fit the page. * * @param args no arguments needed */ public static void main(String[] args) { System.out.println("table splitting"); // creation of the document with a certain size and certain margins Document document = new Document(PageSize.A4.rotate(), 50, 50, 50, 50); try { // creation of the different writers PdfWriter.getInstance(document, new FileOutputStream("repeatingtable.pdf")); // we add some meta information to the document document.addAuthor("Alan Soukup"); document.addSubject("This is the result of a Test."); document.open(); Table datatable = new Table(10); int headerwidths[] = {10, 24, 12, 12, 7, 7, 7, 7, 7, 7}; datatable.setWidths(headerwidths); datatable.setWidth(100); datatable.setPadding(3); // the first cell spans 10 columns Cell cell = new Cell( new Phrase( "Administration -System Users Report", FontFactory.getFont(FontFactory.HELVETICA, 24, Font.BOLD))); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setLeading(30); cell.setColspan(10); cell.setBorder(Rectangle.NO_BORDER); cell.setBackgroundColor(new Color(0xC0, 0xC0, 0xC0)); datatable.addCell(cell); // These cells span 2 rows datatable.getDefaultCell().setBorderWidth(2); datatable.getDefaultCell().setHorizontalAlignment(1); datatable.addCell("User Id"); datatable.addCell("Name\nAddress"); datatable.addCell("Company"); datatable.addCell("Department"); datatable.addCell("Admin"); datatable.addCell("Data"); datatable.addCell("Expl"); datatable.addCell("Prod"); datatable.addCell("Proj"); datatable.addCell("Online"); // this is the end of the table header datatable.endHeaders(); datatable.getDefaultCell().setBorderWidth(1); for (int i = 1; i < 30; i++) { datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT); datatable.addCell("myUserId"); datatable.addCell( "Somebody with a very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very long long name"); datatable.addCell("No Name Company"); datatable.addCell("D" + i); datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); datatable.addCell("No"); datatable.addCell("Yes"); datatable.addCell("No"); datatable.addCell("Yes"); datatable.addCell("No"); datatable.addCell("Yes"); } document.add(new Paragraph("com.lowagie.text.Table - Cells split")); document.add(datatable); document.newPage(); document.add(new Paragraph("com.lowagie.text.pdf.PdfPTable - Cells split\n\n")); datatable.setConvert2pdfptable(true); document.add(datatable); document.newPage(); document.add(new Paragraph("com.lowagie.text.Table - Cells kept together")); datatable.setConvert2pdfptable(false); datatable.setCellsFitPage(true); document.add(datatable); document.newPage(); document.add(new Paragraph("com.lowagie.text.pdf.PdfPTable - Cells kept together\n\n")); datatable.setConvert2pdfptable(true); document.add(datatable); } catch (Exception e) { e.printStackTrace(); } // we close the document document.close(); }
@Override protected Table indexPdfDoc( Map<String, String> params, Font titleFont, Font minFont, Font haderFont, Font contextFont) throws DocumentException { List<Map<String, Object>> list = service.financialIndexData_02(params); Table table = ITextUtil.loadTable( 7, new int[] {16, 14, 14, 14, 14, 14, 14}, 95, Element.ALIGN_CENTER, true, 1); // 设置表头 table.addCell( ITextUtil.loadHeaderCell( params.get("statMonth") + getReportName(), titleFont, 7, 1, new float[] {0, 0, 0, 0}, null, null)); table.addCell( ITextUtil.loadCell( "表号:002 \n单位:万元 ", minFont, true, Element.ALIGN_RIGHT, Element.ALIGN_MIDDLE, new float[] {0, 0, 0, 0}, null, null, 7, 1)); table.addCell(ITextUtil.loadHeaderCell("地区", haderFont, 1, 2)); table.addCell(ITextUtil.loadHeaderCell("利润总额", haderFont, 2, 1)); table.addCell(ITextUtil.loadHeaderCell("资产总额", haderFont, 2, 1)); table.addCell(ITextUtil.loadHeaderCell("所有者权益", haderFont, 2, 1)); table.addCell(ITextUtil.loadHeaderCell("本期", haderFont, 1, 1)); table.addCell(ITextUtil.loadHeaderCell("同比(%)", haderFont, 1, 1)); table.addCell(ITextUtil.loadHeaderCell("本期", haderFont, 1, 1)); table.addCell(ITextUtil.loadHeaderCell("同比(%)", haderFont, 1, 1)); table.addCell(ITextUtil.loadHeaderCell("本期", haderFont, 1, 1)); table.addCell(ITextUtil.loadHeaderCell("同比(%)", haderFont, 1, 1)); table.endHeaders(); // 计算 if (list != null && list.size() > 0) { for (Map<String, Object> map : list) { table.addCell(ITextUtil.loadContextCell(map.get("ENT_NAME").toString(), contextFont)); table.addCell( ITextUtil.loadContextCell(StringUitl.obj2doule(map.get("TJ1"), 2) + "", contextFont)); table.addCell( ITextUtil.loadContextCell(StringUitl.obj2doule(map.get("TB1"), 2) + "", contextFont)); table.addCell( ITextUtil.loadContextCell(StringUitl.obj2doule(map.get("TJ2"), 2) + "", contextFont)); table.addCell( ITextUtil.loadContextCell(StringUitl.obj2doule(map.get("TB2"), 2) + "", contextFont)); table.addCell( ITextUtil.loadContextCell(StringUitl.obj2doule(map.get("TJ3"), 2) + "", contextFont)); table.addCell( ITextUtil.loadContextCell(StringUitl.obj2doule(map.get("TB3"), 2) + "", contextFont)); } } return table; }
// utility function to make an item Element. private Table makeItemElement(ShoppingCartItemData pItm) throws DocumentException { Table itmTbl = new PTable(mColumnCount); itmTbl.setWidth(100); itmTbl.setWidths(itmColumnWidth); itmTbl.getDefaultCell().setBorderColor(java.awt.Color.black); itmTbl.getDefaultCell().setVerticalAlignment(Cell.ALIGN_TOP); itmTbl.setOffset(0); itmTbl.setBorder(Table.NO_BORDER); if (!catalogOnly) { String t0 = ""; if (pItm.getIsaInventoryItem()) { t0 = "i"; } if (null != mSiteData && mSiteData.isAnInventoryAutoOrderItem(pItm.getProduct().getProductId())) { t0 += "a"; } Cell tpc0 = new Cell(makePhrase(t0, small, true)); if (!pItm.getIsaInventoryItem()) { tpc0.setBorder(0); } itmTbl.addCell(tpc0); } Cell tpc01 = new Cell(makePhrase("", normal, true)); itmTbl.addCell(tpc01); String t = ""; if (pItm.getProduct().isPackProblemSku()) { t += "*"; } if (t.length() > 0) t += " "; Cell tpc1 = new Cell(makePhrase(t + pItm.getActualSkuNum(), normal, true)); itmTbl.addCell(tpc1); itmTbl.addCell(makePhrase(pItm.getProduct().getCatalogProductShortDesc(), normal, true)); if (mShowSize) { itmTbl.addCell(makePhrase(pItm.getProduct().getSize(), normal, true)); } // itmTbl.addCell(makePhrase(pItm.getProduct().getPack(), normal, true)); // itmTbl.addCell(makePhrase(pItm.getProduct().getUom(), normal, true)); // itmTbl.addCell(makePhrase(pItm.getProduct().getManufacturerName(),normal,true)); if (mShowPrice) { BigDecimal price = new BigDecimal(pItm.getPrice()); String priceStr = ""; try { priceStr = mFormatter.priceFormatWithoutCurrency(price); } catch (Exception exc) { exc.printStackTrace(); } Cell pcell = new Cell(makePhrase(priceStr, normal, true)); pcell.setHorizontalAlignment(Element.ALIGN_RIGHT); itmTbl.addCell(pcell); } if (catalogOnly) { if (pItm.getProduct() != null && pItm.getProduct().getCatalogDistrMapping() != null && Utility.isTrue(pItm.getProduct().getCatalogDistrMapping().getStandardProductList())) { String yStr = ClwI18nUtil.getMessage(mRequest, "shoppingItems.text.y", null); itmTbl.addCell(makePhrase(yStr, normal, true)); } else { String nStr = ClwI18nUtil.getMessage(mRequest, "shoppingItems.text.n", null); itmTbl.addCell(makePhrase(nStr, normal, true)); } } if (!catalogOnly) { // BigDecimal amount = new BigDecimal(pItm.getAmount()); itmTbl.addCell(makePhrase("", normal, true)); } return itmTbl; }
/** @noinspection IOResourceOpenedButNotSafelyClosed */ public void print( final LogicalPageKey logicalPageKey, final LogicalPageBox logicalPage, final TableContentProducer contentProducer, final RTFOutputProcessorMetaData metaData, final boolean incremental) throws ContentProcessingException { final int startRow = contentProducer.getFinishedRows(); final int finishRow = contentProducer.getFilledRows(); if (incremental && startRow == finishRow) { return; } if (document == null) { this.cellBackgroundProducer = new CellBackgroundProducer( metaData.isFeatureSupported(AbstractTableOutputProcessor.TREAT_ELLIPSE_AS_RECTANGLE), metaData.isFeatureSupported(OutputProcessorFeature.UNALIGNED_PAGEBANDS)); final PhysicalPageBox pageFormat = logicalPage.getPageGrid().getPage(0, 0); final float urx = (float) StrictGeomUtility.toExternalValue(pageFormat.getWidth()); final float ury = (float) StrictGeomUtility.toExternalValue(pageFormat.getHeight()); final float marginLeft = (float) StrictGeomUtility.toExternalValue(pageFormat.getImageableX()); final float marginRight = (float) StrictGeomUtility.toExternalValue( pageFormat.getWidth() - pageFormat.getImageableWidth() - pageFormat.getImageableX()); final float marginTop = (float) StrictGeomUtility.toExternalValue(pageFormat.getImageableY()); final float marginBottom = (float) StrictGeomUtility.toExternalValue( pageFormat.getHeight() - pageFormat.getImageableHeight() - pageFormat.getImageableY()); final Rectangle pageSize = new Rectangle(urx, ury); document = new Document(pageSize, marginLeft, marginRight, marginTop, marginBottom); imageCache = new RTFImageCache(resourceManager); // rtf does not support PageFormats or other meta data... final PatchRtfWriter2 instance = PatchRtfWriter2.getInstance(document, new NoCloseOutputStream(outputStream)); instance.getDocumentSettings().setAlwaysUseUnicode(true); final String author = config.getConfigProperty( "org.pentaho.reporting.engine.classic.core.modules.output.table.rtf.Author"); if (author != null) { document.addAuthor(author); } final String title = config.getConfigProperty( "org.pentaho.reporting.engine.classic.core.modules.output.table.rtf.Title"); if (title != null) { document.addTitle(title); } document.addProducer(); document.addCreator(RTFPrinter.CREATOR); try { document.addCreationDate(); } catch (Exception e) { RTFPrinter.logger.debug("Unable to add creation date. It will have to work without it.", e); } document.open(); } // Start a new page. try { final SheetLayout sheetLayout = contentProducer.getSheetLayout(); final int columnCount = contentProducer.getColumnCount(); if (table == null) { final int rowCount = contentProducer.getRowCount(); table = new Table(columnCount, rowCount); table.setAutoFillEmptyCells(false); table.setWidth(100); // span the full page.. // and finally the content .. final float[] cellWidths = new float[columnCount]; for (int i = 0; i < columnCount; i++) { cellWidths[i] = (float) StrictGeomUtility.toExternalValue(sheetLayout.getCellWidth(i, i + 1)); } table.setWidths(cellWidths); } // logger.debug ("Processing: " + startRow + " " + finishRow + " " + incremental); for (int row = startRow; row < finishRow; row++) { for (short col = 0; col < columnCount; col++) { final RenderBox content = contentProducer.getContent(row, col); final CellMarker.SectionType sectionType = contentProducer.getSectionType(row, col); if (content == null) { final RenderBox backgroundBox = contentProducer.getBackground(row, col); final CellBackground background; if (backgroundBox != null) { background = cellBackgroundProducer.getBackgroundForBox( logicalPage, sheetLayout, col, row, 1, 1, true, sectionType, backgroundBox); } else { background = cellBackgroundProducer.getBackgroundAt( logicalPage, sheetLayout, col, row, true, sectionType); } if (background == null) { // An empty cell .. ignore final PatchRtfCell cell = new PatchRtfCell(); cell.setBorderWidth(0); cell.setMinimumHeight( (float) StrictGeomUtility.toExternalValue(sheetLayout.getRowHeight(row))); table.addCell(cell, row, col); continue; } // A empty cell with a defined background .. final PatchRtfCell cell = new PatchRtfCell(); cell.setBorderWidth(0); cell.setMinimumHeight( (float) StrictGeomUtility.toExternalValue(sheetLayout.getRowHeight(row))); updateCellStyle(cell, background); table.addCell(cell, row, col); continue; } if (content.isCommited() == false) { throw new InvalidReportStateException("Uncommited content encountered"); } final long contentOffset = contentProducer.getContentOffset(row, col); final long colPos = sheetLayout.getXPosition(col); final long rowPos = sheetLayout.getYPosition(row); if (content.getX() != colPos || (content.getY() + contentOffset) != rowPos) { // A spanned cell .. continue; } final int colSpan = sheetLayout.getColSpan(col, content.getX() + content.getWidth()); final int rowSpan = sheetLayout.getRowSpan(row, content.getY() + content.getHeight() + contentOffset); final CellBackground realBackground = cellBackgroundProducer.getBackgroundForBox( logicalPage, sheetLayout, col, row, colSpan, rowSpan, false, sectionType, content); final PatchRtfCell cell = new PatchRtfCell(); cell.setRowspan(rowSpan); cell.setColspan(colSpan); cell.setBorderWidth(0); cell.setMinimumHeight( (float) StrictGeomUtility.toExternalValue(sheetLayout.getRowHeight(row))); if (realBackground != null) { updateCellStyle(cell, realBackground); } computeCellStyle(content, cell); // export the cell and all content .. final RTFTextExtractor etx = new RTFTextExtractor(metaData); etx.compute(content, cell, imageCache); table.addCell(cell, row, col); content.setFinishedTable(true); // logger.debug("set Finished to cell (" + col + ", " + row + "," + content.getName() + // ")"); } } if (incremental == false) { document.add(table); table = null; } } catch (DocumentException e) { throw new ContentProcessingException("Failed to generate RTF-Document", e); } }
/** * Creates a Table object based on this TableAttributes object. * * @return a com.lowagie.text.Table object * @throws BadElementException */ public Table createTable() throws BadElementException { if (content.isEmpty()) throw new BadElementException("Trying to create a table without rows."); SimpleCell row = (SimpleCell) content.get(0); SimpleCell cell; int columns = 0; for (Iterator i = row.getContent().iterator(); i.hasNext(); ) { cell = (SimpleCell) i.next(); columns += cell.getColspan(); } float[] widths = new float[columns]; float[] widthpercentages = new float[columns]; Table table = new Table(columns); table.setAlignment(alignment); table.setSpacing(cellspacing); table.setPadding(cellpadding); table.cloneNonPositionParameters(this); int pos; for (Iterator rows = content.iterator(); rows.hasNext(); ) { row = (SimpleCell) rows.next(); pos = 0; for (Iterator cells = row.getContent().iterator(); cells.hasNext(); ) { cell = (SimpleCell) cells.next(); table.addCell(cell.createCell(row)); if (cell.getColspan() == 1) { if (cell.getWidth() > 0) widths[pos] = cell.getWidth(); if (cell.getWidthpercentage() > 0) widthpercentages[pos] = cell.getWidthpercentage(); } pos += cell.getColspan(); } } float sumWidths = 0f; for (int i = 0; i < columns; i++) { if (widths[i] == 0) { sumWidths = 0; break; } sumWidths += widths[i]; } if (sumWidths > 0) { table.setWidth(sumWidths); table.setLocked(true); table.setWidths(widths); } else { for (int i = 0; i < columns; i++) { if (widthpercentages[i] == 0) { sumWidths = 0; break; } sumWidths += widthpercentages[i]; } if (sumWidths > 0) { table.setWidths(widthpercentages); } } if (width > 0) { table.setWidth(width); table.setLocked(true); } else if (widthpercentage > 0) { table.setWidth(widthpercentage); } return table; }
/** Integrates all added tables and recalculates column widths. */ private void mergeInsertedTables() { int i = 0, j = 0; float[] lNewWidths = null; int[] lDummyWidths = new int[columns]; // to keep track in how many new cols this one will be split float[][] lDummyColumnWidths = new float[columns][]; // bugfix Tony Copping int[] lDummyHeights = new int[rows.size()]; // to keep track in how many new rows this one will be split ArrayList newRows = null; boolean isTable = false; int lTotalRows = 0, lTotalColumns = 0; int lNewMaxRows = 0, lNewMaxColumns = 0; Table lDummyTable = null; // first we'll add new columns when needed // check one column at a time, find maximum needed nr of cols // Search internal tables and find one with max columns for (j = 0; j < columns; j++) { lNewMaxColumns = 1; // value to hold in how many columns the current one will be split float[] tmpWidths = null; for (i = 0; i < rows.size(); i++) { if (Table.class.isInstance(((Row) rows.get(i)).getCell(j))) { isTable = true; lDummyTable = ((Table) ((Row) rows.get(i)).getCell(j)); if (tmpWidths == null) { tmpWidths = lDummyTable.widths; lNewMaxColumns = tmpWidths.length; } else { int cols = lDummyTable.getDimension().width; float[] tmpWidthsN = new float[cols * tmpWidths.length]; float tpW = 0, btW = 0, totW = 0; int tpI = 0, btI = 0, totI = 0; tpW += tmpWidths[0]; btW += lDummyTable.widths[0]; while (tpI < tmpWidths.length && btI < cols) { if (btW > tpW) { tmpWidthsN[totI] = tpW - totW; tpI++; if (tpI < tmpWidths.length) { tpW += tmpWidths[tpI]; } } else { tmpWidthsN[totI] = btW - totW; btI++; if (Math.abs(btW - tpW) < 0.0001) { tpI++; if (tpI < tmpWidths.length) { tpW += tmpWidths[tpI]; } } if (btI < cols) { btW += lDummyTable.widths[btI]; } } totW += tmpWidthsN[totI]; totI++; } /*if( tpI<tmpWidths.length) { System.arraycopy(tmpWidths, tpI, tmpWidthsN, totI, tmpWidths.length-tpI); totI +=tmpWidths.length-tpI; } else if(btI<cols) { System.arraycopy(lDummyTable.widths, btI, tmpWidthsN, totI, lDummyTable.widths.length-btI); totI +=lDummyTable.widths.length-btI; }*/ tmpWidths = new float[totI]; System.arraycopy(tmpWidthsN, 0, tmpWidths, 0, totI); lNewMaxColumns = totI; } /*if ( lDummyTable.getDimension().width > lNewMaxColumns ) { lNewMaxColumns = lDummyTable.getDimension().width; lDummyColumnWidths[j] = lDummyTable.widths; // bugfix Tony Copping }*/ } } lDummyColumnWidths[j] = tmpWidths; lTotalColumns += lNewMaxColumns; lDummyWidths[j] = lNewMaxColumns; } // next we'll add new rows when needed for (i = 0; i < rows.size(); i++) { lNewMaxRows = 1; // holds value in how many rows the current one will be split for (j = 0; j < columns; j++) { if (Table.class.isInstance(((Row) rows.get(i)).getCell(j))) { isTable = true; lDummyTable = (Table) ((Row) rows.get(i)).getCell(j); if (lDummyTable.getDimension().height > lNewMaxRows) { lNewMaxRows = lDummyTable.getDimension().height; } } } lTotalRows += lNewMaxRows; lDummyHeights[i] = lNewMaxRows; } if ((lTotalColumns != columns) || (lTotalRows != rows.size()) || isTable) // NO ADJUSTMENT { // ** WIDTH // set correct width for new columns // divide width over new nr of columns // Take new max columns of internal table and work out widths for each col lNewWidths = new float[lTotalColumns]; int lDummy = 0; for (int tel = 0; tel < widths.length; tel++) { if (lDummyWidths[tel] != 1) { // divide for (int tel2 = 0; tel2 < lDummyWidths[tel]; tel2++) { // lNewWidths[lDummy] = widths[tel] / lDummyWidths[tel]; lNewWidths[lDummy] = widths[tel] * lDummyColumnWidths[tel][tel2] / 100f; // bugfix Tony Copping lDummy++; } } else { lNewWidths[lDummy] = widths[tel]; lDummy++; } } // ** FILL OUR NEW TABLE // generate new table // set new widths // copy old values newRows = new ArrayList(lTotalRows); for (i = 0; i < lTotalRows; i++) { newRows.add(new Row(lTotalColumns)); } int lDummyRow = 0, lDummyColumn = 0; // to remember where we are in the new, larger table Object lDummyElement = null; for (i = 0; i < rows.size(); i++) { lDummyColumn = 0; lNewMaxRows = 1; for (j = 0; j < columns; j++) { if (Table.class.isInstance( ((Row) rows.get(i)).getCell(j))) // copy values from embedded table { lDummyTable = (Table) ((Row) rows.get(i)).getCell(j); // Work out where columns in table table correspond to columns in current table int colMap[] = new int[lDummyTable.widths.length + 1]; int cb = 0, ct = 0; for (; cb < lDummyTable.widths.length; cb++) { colMap[cb] = lDummyColumn + ct; float wb; wb = lDummyTable.widths[cb]; float wt = 0; while (ct < lDummyWidths[j]) { wt += lDummyColumnWidths[j][ct++]; if (Math.abs(wb - wt) < 0.0001) break; } } colMap[cb] = lDummyColumn + ct; // need to change this to work out how many cols to span for (int k = 0; k < lDummyTable.getDimension().height; k++) { for (int l = 0; l < lDummyTable.getDimension().width; l++) { lDummyElement = lDummyTable.getElement(k, l); if (lDummyElement != null) { int col = lDummyColumn + l; if (Cell.class.isInstance(lDummyElement)) { Cell lDummyC = (Cell) lDummyElement; // Find col to add cell in and set col span col = colMap[l]; int ot = colMap[l + lDummyC.getColspan()]; lDummyC.setColspan(ot - col); } ((Row) newRows.get(k + lDummyRow)) .addElement( lDummyElement, col); // use addElement to set reserved status ok in row } } } } else // copy others values { Object aElement = getElement(i, j); if (Cell.class.isInstance(aElement)) { // adjust spans for cell ((Cell) aElement) .setRowspan( ((Cell) ((Row) rows.get(i)).getCell(j)).getRowspan() + lDummyHeights[i] - 1); ((Cell) aElement) .setColspan( ((Cell) ((Row) rows.get(i)).getCell(j)).getColspan() + lDummyWidths[j] - 1); // most likely this cell covers a larger area because of the row/cols splits : define // not-to-be-filled cells placeCell(newRows, ((Cell) aElement), new Point(lDummyRow, lDummyColumn)); } } lDummyColumn += lDummyWidths[j]; } lDummyRow += lDummyHeights[i]; } // Set our new matrix columns = lTotalColumns; rows = newRows; this.widths = lNewWidths; } }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext()); CourseManager manager = (CourseManager) ctx.getBean("courseManager"); HttpSession session = request.getSession(false); List selectFilterCouList = (List) session.getAttribute("selectFilterCouList"); Date date = new Date(); DateFormat dateFormat = new SimpleDateFormat("yyyy年 MM月 dd日 HH:mm"); String stuTmp[] = new String[selectFilterCouList.size()]; List students = new ArrayList(); for (int i = 0; i < selectFilterCouList.size(); i++) { stuTmp[i] = ((Map) selectFilterCouList.get(i)).get("dtimeOid").toString(); } students = manager.getSeldStuFilterBy(stuTmp, true); Document document = new Document(PageSize.A4, 72, 72, 35, 35); ByteArrayOutputStream ba = new ByteArrayOutputStream(); String year = manager.getNowBy("School_year"); String term = manager.getNowBy("School_term"); // 如果是下學期, 學年要+1 if (Integer.parseInt(term) == 2) { Integer tmpYear = (Integer.parseInt(year) + 1); year = tmpYear.toString(); term = "1"; } else { term = "2"; } try { PdfWriter writer = PdfWriter.getInstance(document, ba); // TODO 路徑 // Image // image=Image.getInstance("http://cap.chit.edu.tw/CIS/pages/images/2002chitWatermark.gif"); // Watermark wamark=new Watermark(image, ((PageSize.A4).width()-image.plainHeight())/2, // ((PageSize.A4).height()-image.plainHeight())/2); // document.add(wamark); Phrase now = doEncode("課程管理系統 " + dateFormat.format(date)); HeaderFooter header = new HeaderFooter(now, false); document.setHeader(header); document.setFooter(header); // Image logo=Image.getInstance("http://192.192.231.32:8080/CIS/pages/images/art.gif"); document.open(); for (int i = 0; i < students.size(); i++) { String buf[] = {((Map) students.get(i)).get("student_no").toString()}; List tmp = manager.getSeldStuFilterBy(buf, false); if (i % 2 != 0) { document.add(new Paragraph(doEncode("\n"))); document.add(new Paragraph(doEncode("\n"))); document.add(new Paragraph(doEncode("\n"))); } document.add(new Paragraph("")); Table table = new Table(6); table.setWidth(100); table.setBorderWidth(0); table.setPadding(5); // table.setSpacing(5); // table.setDefaultHorizontalAlignment(table.ALIGN_CENTER); // table.setDefaultHorizontalAlignment(table.ALIGN_MIDDLE); // table.setDefaultCellBorderColor(new Color(255, 255, 255)); Cell cell = new Cell(); cell.add(doEncode(year)); cell.add(doEncode("學年 第")); cell.add(doEncode(term)); cell.add(doEncode("學期 網路預選失敗通知單")); // cell.addElement(logo); cell.setColspan(6); cell.setHorizontalAlignment(cell.ALIGN_CENTER); cell.setBorderColor(new Color(255, 255, 255)); table.addCell(cell); // ((Map)students.get(i)).get("ClassName2"); cell = new Cell(); // cell.add(doEncode("學生班級: ")); cell.add(doEncode(((Map) students.get(i)).get("ClassName").toString())); cell.add(doEncode("\t學號: ")); cell.add(doEncode(((Map) students.get(i)).get("student_no").toString())); cell.add(doEncode("\t姓名: ")); cell.add(doEncode(((Map) students.get(i)).get("student_name").toString())); cell.setColspan(6); cell.setHorizontalAlignment(cell.ALIGN_LEFT); cell.setBorderColor(new Color(255, 255, 255)); table.addCell(cell); cell = new Cell(); cell.add(doEncode("您在第一階段網路選課所選的下列課程並未成功,請按照規定時間進行網路第二階段選課,以免影響您的權益。")); cell.setColspan(6); cell.setHorizontalAlignment(cell.ALIGN_LEFT); cell.setBorderColor(new Color(255, 255, 255)); table.addCell(cell); document.add(table); float[] widths = {0.2f, 0.3f, 0.1f, 0.1f, 0.1f, 0.2f}; PdfPTable tables = new PdfPTable(widths); tables.setWidthPercentage(100); PdfPCell cells = new PdfPCell(doEncode("開課班級")); tables.addCell(cells); cells = new PdfPCell(doEncode("科目名稱")); tables.addCell(cells); cells = new PdfPCell(doEncode("選別")); tables.addCell(cells); cells = new PdfPCell(doEncode("學分")); tables.addCell(cells); cells = new PdfPCell(doEncode("時數")); tables.addCell(cells); cells = new PdfPCell(doEncode("上課時間")); tables.addCell(cells); for (int j = 0; j < tmp.size(); j++) { cells = new PdfPCell(); cells = new PdfPCell(doEncode(((Map) tmp.get(j)).get("ClassName2").toString())); tables.addCell(cells); cells = new PdfPCell(doEncode(((Map) tmp.get(j)).get("chi_name").toString())); tables.addCell(cells); cells = new PdfPCell(doEncode(getOpt(((Map) tmp.get(j)).get("opt").toString()))); tables.addCell(cells); cells = new PdfPCell(doEncode(((Map) tmp.get(j)).get("credit").toString())); tables.addCell(cells); cells = new PdfPCell(doEncode(((Map) tmp.get(j)).get("thour").toString())); tables.addCell(cells); List dcTmp = manager.getDtimeClassListForOpenCourse(((Map) tmp.get(j)).get("dtimeOid").toString()); StringBuffer strBuf = new StringBuffer(); DtimeClass dtimeClass; for (int x = 0; x < dcTmp.size(); x++) { dtimeClass = (DtimeClass) dcTmp.get(x); strBuf.append("週" + dtimeClass.getWeek() + ":"); strBuf.append(dtimeClass.getBegin() + "~" + dtimeClass.getEnd() + " "); } cells = new PdfPCell(doEncode(strBuf.toString())); tables.addCell(cells); } for (int k = 13; k > tmp.size(); k--) { cells = new PdfPCell(doEncode("\t")); tables.addCell(cells); cells = new PdfPCell(doEncode("\t")); tables.addCell(cells); cells = new PdfPCell(doEncode("\t")); tables.addCell(cells); cells = new PdfPCell(doEncode("\t")); tables.addCell(cells); cells = new PdfPCell(doEncode("\t")); tables.addCell(cells); cells = new PdfPCell(doEncode("\t")); tables.addCell(cells); } document.add(tables); if (i % 2 == 1) { document.newPage(); } } } catch (DocumentException de) { de.printStackTrace(); System.err.println("A Document error:" + de.getMessage()); } document.close(); response.setContentType("application/pdf"); response.setContentLength(ba.size()); ServletOutputStream out = response.getOutputStream(); ba.writeTo(out); ba.close(); out.flush(); out.close(); }
// int sportId = 1; public void SelPlaWD(String filePath, String fileName) { SelectPlayerDAO sd = new SelectPlayerDAO(); // ArrayList departList = new ArrayList(); ArrayList stuDepartList = new ArrayList(); ArrayList teaDepartList = new ArrayList(); // ArrayList selectSportsid=new ArrayList(); // departList=sd.selectDepartment(sportId); // selectSportsid=sd.selectSportsid(); stuDepartList = sd.slectStuDepidBySid(sportId); teaDepartList = sd.selectDepartment(sportId); Document document = new Document(PageSize.A4); try { RtfWriter2.getInstance(document, new FileOutputStream(filePath + fileName)); document.open(); for (int i = 0; i < stuDepartList.size(); i++) { int id = Integer.parseInt(stuDepartList.get(i).toString()); // int sid = Integer.parseInt(selectSportsid.get(i).toString()); ArrayList playBoy = new ArrayList(); ArrayList playGirl = new ArrayList(); // ArrayList playTeacher = new ArrayList(); // int type=sd.selectDepartmentType(id); // if(type==1){ // 查询学生男子组的姓名和号码 playBoy = sd.selectPlayersByDept(1, id, sportId); String groupname = "男子组"; String departname = sd.selectDepartmentName(id); Paragraph p = new Paragraph(departname, new Font(Font.BOLD, 18, Font.BOLD, new Color(0, 0, 0))); p.setAlignment(1); document.add(p); // document.add(new Paragraph(groupname)); Table table = new Table(8); Cell cc5 = new Cell(groupname); cc5.setColspan(8); cc5.setBorderWidth(0); table.addCell(cc5); // 指定表格为八列 table.setBorder(0); table.setBorderWidth(0); table.setBorderColor(Color.WHITE); table.setPadding(0); table.setSpacing(0); for (int a = 0; a < playBoy.size(); a++) { PlayerPojo pojp = (PlayerPojo) playBoy.get(a); Cell cc = new Cell(pojp.getPlayernum()); cc.setBorderWidth(0); table.addCell(cc); Cell ce = new Cell(pojp.getPlayername()); ce.setBorderWidth(0); table.addCell(ce); } // document.add(p1); document.add(table); // 查询学生女子组的姓名和号码 Table table1 = new Table(8); // 指定表格为八列 table1.setBorder(0); table1.setBorderWidth(0); table1.setBorderColor(Color.WHITE); table1.setPadding(0); table1.setSpacing(0); playGirl = sd.selectPlayersByDept(0, id, sportId); String groupname1 = "女子组"; // document.add(new Paragraph(groupname1)); Cell cc6 = new Cell(groupname1); cc6.setColspan(8); cc6.setBorderWidth(0); table1.addCell(cc6); for (int a = 0; a < playGirl.size(); a++) { PlayerPojo pojp = (PlayerPojo) playGirl.get(a); Cell cc1 = new Cell(pojp.getPlayernum()); cc1.setBorderWidth(0); table1.addCell(cc1); Cell ce1 = new Cell(pojp.getPlayername()); ce1.setBorderWidth(0); table1.addCell(ce1); } document.add(table1); document.add(new Paragraph()); document.add(new Paragraph()); // } else{ } for (int i = 0; i < teaDepartList.size(); i++) { int id = Integer.parseInt(teaDepartList.get(i).toString()); ArrayList playTeacher = sd.selectPlayersByDept1(id, sportId); String groupname = "教工组"; String departname = sd.selectDepartmentName(id); Paragraph p = new Paragraph(departname, new Font(Font.BOLD, 18, Font.BOLD, new Color(0, 0, 0))); p.setAlignment(1); document.add(p); // document.add(new Paragraph(groupname)); Table table2 = new Table(8); Cell cc6 = new Cell(groupname); cc6.setColspan(8); cc6.setBorderWidth(0); table2.addCell(cc6); // 指定表格为八列 table2.setBorder(0); table2.setBorderWidth(0); table2.setBorderColor(Color.WHITE); table2.setPadding(0); table2.setSpacing(0); for (int a = 0; a < playTeacher.size(); a++) { PlayerPojo pojp = (PlayerPojo) playTeacher.get(a); Cell cc = new Cell(pojp.getPlayernum()); cc.setBorderWidth(0); table2.addCell(cc); Cell ce = new Cell(pojp.getPlayername()); ce.setBorderWidth(0); table2.addCell(ce); } document.add(table2); } // 查询教工组的姓名和号码 // document.add(p1); document.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }