Java Code Examples for com.lowagie.text.pdf.PdfPTable#addCell()

The following examples show how to use com.lowagie.text.pdf.PdfPTable#addCell() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SplitTableTest.java    From itext2 with GNU Lesser General Public License v3.0 8 votes vote down vote up
/**
 * Break a large table up into several smaller tables for memory management
 * purposes.
 * 
 */
@Test
public void main() throws Exception {
	// step1
	Document document = new Document(PageSize.A4, 10, 10, 10, 10);
	// step2
	PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("SplitTable.pdf"));
	// step3
	document.open();
	// step4

	PdfContentByte cb = writer.getDirectContent();
	PdfPTable table = new PdfPTable(10);
	for (int k = 1; k <= 100; ++k) {
		table.addCell("The number " + k);
	}
	table.setTotalWidth(800);
	table.writeSelectedRows(0, 5, 0, -1, 50, 650, cb);
	document.newPage();
	table.writeSelectedRows(5, -1, 0, -1, 50, 650, cb);
	document.close();

	// step5
	document.close();
}
 
Example 2
Source File: DefaultPdfDataEntryFormService.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void insertTable_TextRow( PdfWriter writer, PdfPTable mainTable, String text, Font font )
{
    boolean hasBorder = false;

    // Add Organization ID/Period textfield
    // Create A table to add for each group AT HERE
    PdfPTable table = new PdfPTable( 1 );
    table.setHorizontalAlignment( Element.ALIGN_LEFT );

    addCell_Text( table, PdfDataEntryFormUtil.getPdfPCell( hasBorder ), text, Element.ALIGN_LEFT, font );

    // Add to the main table
    PdfPCell cell_withInnerTable = new PdfPCell( table );

    cell_withInnerTable.setBorder( Rectangle.NO_BORDER );

    mainTable.addCell( cell_withInnerTable );
}
 
Example 3
Source File: EndPageTest.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * @see com.lowagie.text.pdf.PdfPageEventHelper#onEndPage(com.lowagie.text.pdf.PdfWriter,
 *      com.lowagie.text.Document)
 */
public void onEndPage(PdfWriter writer, Document document) {
	try {
		Rectangle page = document.getPageSize();
		PdfPTable head = new PdfPTable(3);
		for (int k = 1; k <= 6; ++k)
			head.addCell("head " + k);
		head.setTotalWidth(page.getWidth() - document.leftMargin()
				- document.rightMargin());
		head.writeSelectedRows(
				0,
				-1,
				document.leftMargin(),
				page.getHeight() - document.topMargin()
						+ head.getTotalHeight(), writer.getDirectContent());
		PdfPTable foot = new PdfPTable(3);
		for (int k = 1; k <= 6; ++k)
			foot.addCell("foot " + k);
		foot.setTotalWidth(page.getWidth() - document.leftMargin()
				- document.rightMargin());
		foot.writeSelectedRows(0, -1, document.leftMargin(),
				document.bottomMargin(), writer.getDirectContent());
	} catch (Exception e) {
		throw new ExceptionConverter(e);
	}
}
 
Example 4
Source File: ContractsGrantsInvoiceReportServiceImpl.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * This method is used to set the headers for the CG LOC review Document
 *
 * @param table
 */
protected void addAwardHeaders(PdfPTable table) {
    table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.PROPOSAL_NUMBER));
    table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.AWARD_DOCUMENT_NUMBER));
    table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.AGENCY_NUMBER));
    table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.CUSTOMER_NUMBER));
    table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.AWARD_BEGINNING_DATE));
    table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, KFSPropertyConstants.AWARD_ENDING_DATE));
    table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.AWARD_BUDGET_AMOUNT));
    table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.LETTER_OF_CREDIT_AMOUNT));
    table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.CLAIM_ON_CASH_BALANCE));
    table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.AMOUNT_TO_DRAW));
    table.addCell(getDataDictionaryService().getAttributeLabel(ContractsGrantsLetterOfCreditReviewDetail.class, ArPropertyConstants.FUNDS_NOT_DRAWN));
}
 
Example 5
Source File: FloatingBoxesTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Example originally written by Wendy Smoak to generate a Table with
 * 'floating boxes'. Adapted by Bruno Lowagie.
 * 
 */
@Test
public void main() throws Exception {
	FloatingBoxesTest floatingBoxes = new FloatingBoxesTest();
	// step 1
	Document document = new Document();
	// step 2
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("FloatingBoxes.pdf"));
	// step 3
	document.open();
	// step 4
	PdfPTable table = new PdfPTable(2);
	table.setTableEvent(floatingBoxes);
	table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
	table.getDefaultCell().setCellEvent(floatingBoxes);
	table.getDefaultCell().setPadding(5f);
	table.addCell("value");
	table.addCell("name");
	table.addCell(new Paragraph("dog"));
	table.addCell(new Paragraph("cat"));
	table.addCell(new Paragraph("bird"));
	table.addCell(new Paragraph("horse"));
	document.add(table);

	// step 5
	document.close();
}
 
Example 6
Source File: PDFPrinter.java    From unitime with Apache License 2.0 5 votes vote down vote up
@Override
public void printHeader(String... fields) {
	iTable = new PdfPTable(fields.length - iHiddenColumns.size());
	iMaxWidth = new float[fields.length];
	iTable.setHeaderRows(1);
	iTable.setWidthPercentage(100);

	for (int idx = 0; idx < fields.length; idx++) {
		if (iHiddenColumns.contains(idx)) continue;
		String f = fields[idx];
		
		PdfPCell cell = new PdfPCell();
		cell.setBorder(Rectangle.BOTTOM);
		cell.setVerticalAlignment(Element.ALIGN_TOP);
		cell.setHorizontalAlignment(Element.ALIGN_LEFT);
		
		Font font = PdfFont.getFont(true);
		Paragraph ch = new Paragraph(f, font);
		ch.setLeading(0f, 1f);
		cell.addElement(ch);		
		iTable.addCell(cell);
		
		float width = 0; 
		if (f.indexOf('\n')>=0) {
			for (StringTokenizer s = new StringTokenizer(f,"\n"); s.hasMoreTokens();)
				width = Math.max(width,font.getBaseFont().getWidthPoint(s.nextToken(), font.getSize()));
		} else 
			width = Math.max(width,font.getBaseFont().getWidthPoint(f, font.getSize()));
		iMaxWidth[idx] = width;
	}
}
 
Example 7
Source File: NestedTablesTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Using nested tables.
 * 
 */
@Test
public void main() throws Exception {
	// step1
	Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);
	// step2
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("NestedTables.pdf"));
	// step3
	document.open();
	// step4
	PdfPTable table = new PdfPTable(4);
	PdfPTable nested1 = new PdfPTable(2);
	nested1.addCell("1.1");
	nested1.addCell("1.2");
	PdfPTable nested2 = new PdfPTable(1);
	nested2.addCell("2.1");
	nested2.addCell("2.2");
	for (int k = 0; k < 24; ++k) {
		if (k == 1) {
			table.addCell(nested1);
		} else if (k == 20) {
			table.addCell(nested2);
		} else {
			table.addCell("cell " + k);
		}
	}
	document.add(table);
	// step 5: we close the document
	document.close();

	// step5
	document.close();
}
 
Example 8
Source File: DefaultCellTest.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Demonstrates the use of getDefaultCell().
 * 
 */
@Test
public void main() throws Exception {

	// step 1: creation of a document-object
	Document document = new Document();

	// step 2:
	// we create a writer that listens to the document
	// and directs a PDF-stream to a file
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("DefaultCell.pdf"));

	// step 3: we open the document
	document.open();

	PdfPTable table = new PdfPTable(3);
	PdfPCell cell = new PdfPCell(new Paragraph("header with colspan 3"));
	cell.setColspan(3);
	table.addCell(cell);
	table.addCell("1.1");
	table.addCell("2.1");
	table.addCell("3.1");
	table.getDefaultCell().setGrayFill(0.8f);
	table.addCell("1.2");
	table.addCell("2.2");
	table.addCell("3.2");
	table.getDefaultCell().setGrayFill(0f);
	table.getDefaultCell().setBorderColor(new Color(255, 0, 0));
	table.addCell("cell test1");
	table.getDefaultCell().setColspan(2);
	table.getDefaultCell().setBackgroundColor(new Color(0xC0, 0xC0, 0xC0));
	table.addCell("cell test2");
	document.add(table);

	// step 5: we close the document
	document.close();
}
 
Example 9
Source File: PurchaseOrderQuotePdf.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * A helper method to create a blank row of 6 cells in the items table.
 *
 * @param itemsTable
 */
private void createBlankRowInItemsTable(PdfPTable itemsTable) {
    // We're adding 6 cells because each row in the items table
    // contains 6 columns.
    for (int i = 0; i < 6; i++) {
        itemsTable.addCell(" ");
    }
}
 
Example 10
Source File: PdfNodeSerializer.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected void startWriteRootNode( RootNode rootNode ) throws Exception
{
    for ( Node child : rootNode.getChildren() )
    {
        if ( child.isCollection() )
        {
            PdfPTable table = PDFUtils.getPdfPTable( true, 0.25f, 0.75f );
            boolean haveContent = false;

            for ( Node node : child.getChildren() )
            {
                for ( Node property : node.getChildren() )
                {
                    if ( property.isSimple() )
                    {
                        table.addCell( PDFUtils.getItalicCell( property.getName() ) );
                        table.addCell( PDFUtils.getTextCell( getValue( (SimpleNode) property ) ) );
                        haveContent = true;
                    }
                }

                if ( haveContent )
                {
                    table.addCell( PDFUtils.getEmptyCell( 2, 15 ) );
                    haveContent = false;
                }
            }

            document.add( table );
        }
    }
}
 
Example 11
Source File: DefaultPdfDataEntryFormService.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@SuppressWarnings( "unused" )
private void addCell_WithRadioButton( PdfPTable table, PdfWriter writer, PdfPCell cell, String strfldName )
{
    PdfFormField radiogroupField = PdfFormField.createRadioButton( writer, true );
    radiogroupField.setFieldName( strfldName );

    cell.setCellEvent( new PdfFieldCell( radiogroupField, new String[]{ "Yes", "No", "null" }, new String[]{
        "true", "false", "" }, "", 30.0f, PdfDataEntryFormUtil.UNITSIZE_DEFAULT, PdfFieldCell.TYPE_RADIOBUTTON, writer ) );

    table.addCell( cell );

    writer.addAnnotation( radiogroupField );
}
 
Example 12
Source File: IncTable.java    From itext2 with GNU Lesser General Public License v3.0 5 votes vote down vote up
public PdfPTable buildTable() {
    if (rows.isEmpty())
        return new PdfPTable(1);
    int ncol = 0;
    ArrayList c0 = (ArrayList)rows.get(0);
    for (int k = 0; k < c0.size(); ++k) {
        ncol += ((PdfPCell)c0.get(k)).getColspan();
    }
    PdfPTable table = new PdfPTable(ncol);
    String width = (String)props.get("width");
    if (width == null)
        table.setWidthPercentage(100);
    else {
        if (width.endsWith("%"))
            table.setWidthPercentage(Float.parseFloat(width.substring(0, width.length() - 1)));
        else {
            table.setTotalWidth(Float.parseFloat(width));
            table.setLockedWidth(true);
        }
    }
    for (int row = 0; row < rows.size(); ++row) {
        ArrayList col = (ArrayList)rows.get(row);
        for (int k = 0; k < col.size(); ++k) {
            table.addCell((PdfPCell)col.get(k));
        }
    }
    return table;
}
 
Example 13
Source File: IncTable.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
public PdfPTable buildTable() {
	if (rows.isEmpty()) {
		return new PdfPTable(1);
	}
	int ncol = 0;
	ArrayList c0 = (ArrayList) rows.get(0);
	for (int k = 0; k < c0.size(); ++k) {
		ncol += ((PdfPCell) c0.get(k)).getColspan();
	}
	PdfPTable table = new PdfPTable(ncol);
	String width = (String) props.get("width");
	if (width == null) {
		table.setWidthPercentage(100);
	} else {
		if (width.endsWith("%")) {
			table.setWidthPercentage(Float.parseFloat(width.substring(0, width.length() - 1)));
		} else {
			table.setTotalWidth(Float.parseFloat(width));
			table.setLockedWidth(true);
		}
	}
	for (int row = 0; row < rows.size(); ++row) {
		ArrayList col = (ArrayList) rows.get(row);
		for (int k = 0; k < col.size(); ++k) {
			table.addCell((PdfPCell) col.get(k));
		}
	}
	return table;
}
 
Example 14
Source File: ComPDFServiceImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
private void writeUserTableHeaders(PdfPTable table) {
    table.addCell("Username");
    table.addCell("Firstname");
    table.addCell("Lastname");
    table.addCell("Email");
    table.addCell("UserGroup");
}
 
Example 15
Source File: ImageChunksTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Images wrapped in a Chunk.
 */
@Test
public void main() throws Exception {

	// step 1: creation of a document-object
	Document document = new Document();
	// step 2:
	// we create a writer that listens to the document
	// and directs a PDF-stream to a file
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("imageChunks.pdf"));
	// step 3: we open the document
	document.open();
	// step 4: we create a table and add it to the document
	Image img = Image.getInstance(PdfTestBase.RESOURCES_DIR + "pngnow.png");
	img.scalePercent(70);
	Chunk ck = new Chunk(img, 0, -5);
	PdfPTable table = new PdfPTable(3);
	PdfPCell cell = new PdfPCell();
	cell.addElement(new Chunk(img, 5, -5));
	cell.setBackgroundColor(new Color(0xC0, 0xC0, 0xC0));
	cell.setHorizontalAlignment(Element.ALIGN_CENTER);
	table.addCell("I see an image\non my right");
	table.addCell(cell);
	table.addCell("I see an image\non my left");
	table.addCell(cell);
	table.addCell("I see images\neverywhere");
	table.addCell(cell);
	table.addCell("I see an image\non my right");
	table.addCell(cell);
	table.addCell("I see an image\non my left");

	Phrase p1 = new Phrase("This is an image ");
	p1.add(ck);
	p1.add(" just here.");
	document.add(p1);
	document.add(p1);
	document.add(p1);
	document.add(p1);
	document.add(p1);
	document.add(p1);
	document.add(p1);
	document.add(table);

	// step 5: we close the document
	document.close();
}
 
Example 16
Source File: BulkReceivingPdf.java    From kfs with GNU Affero General Public License v3.0 4 votes vote down vote up
private PdfPTable createVendorAndDeliveryDetailsTable(){
    
    PdfPCell cell;
    Paragraph p = new Paragraph();

    float[] infoWidths = { 0.50f, 0.50f };
    PdfPTable infoTable = new PdfPTable(infoWidths);

    infoTable.setWidthPercentage(100);
    infoTable.setHorizontalAlignment(Element.ALIGN_CENTER);
    infoTable.setSplitLate(false);
    
    infoTable.addCell(getPDFCell("Vendor", getFormattedVendorAddress()));
    infoTable.addCell(getPDFCell("Delivery", getFormattedDeliveryAddress()));
    infoTable.addCell(getPDFCell("Reference Number\n", blkRecDoc.getShipmentReferenceNumber()));
    
    if (blkRecDoc.getCarrier() != null){
        infoTable.addCell(getPDFCell("Carrier\n", blkRecDoc.getCarrier().getCarrierDescription()));
    }else{
        infoTable.addCell(getPDFCell("Carrier\n", StringUtils.EMPTY));
    }
    
    infoTable.addCell(getPDFCell("Tracking/Pro Number\n", blkRecDoc.getTrackingNumber()));
    
    if (blkRecDoc.getPurchaseOrderIdentifier() != null){
        infoTable.addCell(getPDFCell("PO\n", blkRecDoc.getPurchaseOrderIdentifier().toString()));
    }else{
        infoTable.addCell(getPDFCell("PO\n", StringUtils.EMPTY));
    }
    
    infoTable.addCell(getPDFCell("# of Pieces\n", "" + blkRecDoc.getNoOfCartons()));
    infoTable.addCell(getPDFCell("Shipment Received Date\n", blkRecDoc.getShipmentReceivedDate().toString()));

    if (blkRecDoc.getShipmentWeight() != null){
        infoTable.addCell(getPDFCell("Weight\n", blkRecDoc.getShipmentWeight().toString()));
    }else{
        infoTable.addCell(getPDFCell("Weight\n", StringUtils.EMPTY));
    }
    
    infoTable.addCell(getPDFCell("\n", StringUtils.EMPTY));

    return infoTable;
}
 
Example 17
Source File: SimpleTable.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Creates a PdfPTable object based on this TableAttributes object.
 * @return a com.lowagie.text.pdf.PdfPTable object
 * @throws DocumentException
 */
public PdfPTable createPdfPTable() throws DocumentException {
	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];
	PdfPTable table = new PdfPTable(columns);
	table.setTableEvent(this);
	table.setHorizontalAlignment(alignment);
	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();
			if (Float.isNaN(cell.getSpacing_left()))	{
				cell.setSpacing_left(cellspacing / 2f);
			}
			if (Float.isNaN(cell.getSpacing_right()))	{
				cell.setSpacing_right(cellspacing / 2f);
			}
			if (Float.isNaN(cell.getSpacing_top()))	{
				cell.setSpacing_top(cellspacing / 2f);
			}
			if (Float.isNaN(cell.getSpacing_bottom()))	{
				cell.setSpacing_bottom(cellspacing / 2f);
			}
			cell.setPadding(cellpadding);
			table.addCell(cell.createPdfPCell(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.setTotalWidth(sumWidths);
		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.setTotalWidth(width);
	}
	if (widthpercentage > 0) {
		table.setWidthPercentage(widthpercentage);
	}
	return table;
}
 
Example 18
Source File: AddBigTableTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Big PdfPTable with document.add().
 * 
 */
@Test
public void main() throws Exception {

	// step1
	Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);
	// step2
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("AddBigTable.pdf"));
	// step3
	document.open();
	// step4
	String[] bogusData = { "M0065920", "SL", "FR86000P", "PCGOLD", "119000", "96 06", "2001-08-13", "4350",
			"6011648299", "FLFLMTGP", "153", "119000.00" };
	int NumColumns = 12;

	PdfPTable datatable = new PdfPTable(NumColumns);
	int headerwidths[] = { 9, 4, 8, 10, 8, 11, 9, 7, 9, 10, 4, 10 }; // percentage
	datatable.setWidths(headerwidths);
	datatable.setWidthPercentage(100); // percentage
	datatable.getDefaultCell().setPadding(3);
	datatable.getDefaultCell().setBorderWidth(2);
	datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
	datatable.addCell("Clock #");
	datatable.addCell("Trans Type");
	datatable.addCell("Cusip");
	datatable.addCell("Long Name");
	datatable.addCell("Quantity");
	datatable.addCell("Fraction Price");
	datatable.addCell("Settle Date");
	datatable.addCell("Portfolio");
	datatable.addCell("ADP Number");
	datatable.addCell("Account ID");
	datatable.addCell("Reg Rep ID");
	datatable.addCell("Amt To Go ");

	datatable.setHeaderRows(1); // this is the end of the table header

	datatable.getDefaultCell().setBorderWidth(1);
	for (int i = 1; i < 750; i++) {
		if (i % 2 == 1) {
			datatable.getDefaultCell().setGrayFill(0.9f);
		}
		for (int x = 0; x < NumColumns; x++) {
			datatable.addCell(bogusData[x]);
		}
		if (i % 2 == 1) {
			datatable.getDefaultCell().setGrayFill(1);
		}
	}
	document.add(datatable);

	// step5
	document.close();
}
 
Example 19
Source File: VerticalTextInCellsTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Example with vertical text in Cells.
 */
@Test
public void main() throws Exception {

	// step1
	Document document = new Document(PageSize.A4, 50, 50, 50, 50);
	// step2
	PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("VerticalText.pdf"));
	// step3
	document.open();
	// step4

	// make a PdfTemplate with the vertical text
	PdfTemplate template = writer.getDirectContent().createTemplate(20, 20);
	BaseFont bf = BaseFont.createFont("Helvetica", "winansi", false);
	String text = "Vertical";
	float size = 16;
	float width = bf.getWidthPoint(text, size);
	template.beginText();
	template.setRGBColorFillF(1, 1, 1);
	template.setFontAndSize(bf, size);
	template.setTextMatrix(0, 2);
	template.showText(text);
	template.endText();
	template.setWidth(width);
	template.setHeight(size + 2);
	// make an Image object from the template
	Image img = Image.getInstance(template);
	img.setRotationDegrees(90);
	PdfPTable table = new PdfPTable(3);
	table.setWidthPercentage(100);
	table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
	table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
	PdfPCell cell = new PdfPCell(img);
	cell.setPadding(4);
	cell.setBackgroundColor(new Color(0, 0, 255));
	cell.setHorizontalAlignment(Element.ALIGN_CENTER);
	table.addCell("I see a template on my right");
	table.addCell(cell);
	table.addCell("I see a template on my left");
	table.addCell(cell);
	table.addCell("I see a template everywhere");
	table.addCell(cell);
	table.addCell("I see a template on my right");
	table.addCell(cell);
	table.addCell("I see a template on my left");
	document.add(table);

	// step5
	document.close();
}
 
Example 20
Source File: SimpleTable.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Creates a PdfPTable object based on this TableAttributes object.
 * 
 * @return a com.lowagie.text.pdf.PdfPTable object
 * @throws DocumentException
 */
public PdfPTable createPdfPTable() throws DocumentException {
	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];
	PdfPTable table = new PdfPTable(columns);
	table.setTableEvent(this);
	table.setHorizontalAlignment(alignment);
	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();
			if (Float.isNaN(cell.getSpacing_left())) {
				cell.setSpacing_left(cellspacing / 2f);
			}
			if (Float.isNaN(cell.getSpacing_right())) {
				cell.setSpacing_right(cellspacing / 2f);
			}
			if (Float.isNaN(cell.getSpacing_top())) {
				cell.setSpacing_top(cellspacing / 2f);
			}
			if (Float.isNaN(cell.getSpacing_bottom())) {
				cell.setSpacing_bottom(cellspacing / 2f);
			}
			cell.setPadding(cellpadding);
			table.addCell(cell.createPdfPCell(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.setTotalWidth(sumWidths);
		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.setTotalWidth(width);
	}
	if (widthpercentage > 0) {
		table.setWidthPercentage(widthpercentage);
	}
	return table;
}