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

The following examples show how to use com.lowagie.text.pdf.PdfPTable#setWidthPercentage() . 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: PdfRequestAndGraphDetailReport.java    From javamelody with Apache License 2.0 6 votes vote down vote up
private void writeGraph() throws IOException, DocumentException {
	final JRobin jrobin = collector.getJRobin(graphName);
	if (jrobin != null) {
		final byte[] img = jrobin.graph(range, 960, 400);
		final Image image = Image.getInstance(img);
		image.scalePercent(50);

		final PdfPTable table = new PdfPTable(1);
		table.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.setWidthPercentage(100);
		table.getDefaultCell().setBorder(0);
		table.addCell("\n");
		table.addCell(image);
		table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
		table.addCell(new Phrase(getString("graph_units"), cellFont));
		addToDocument(table);
	} else {
		// just in case request is null and collector.getJRobin(graphName) is null, we must write something in the document
		addToDocument(new Phrase("\n", cellFont));
	}
}
 
Example 2
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 3
Source File: PdfMBeansReport.java    From javamelody with Apache License 2.0 5 votes vote down vote up
private static PdfPTable createAttributesTable() {
	final PdfPTable table = new PdfPTable(3);
	table.setWidthPercentage(100);
	final PdfPCell defaultCell = table.getDefaultCell();
	defaultCell.setPaddingLeft(2);
	defaultCell.setPaddingRight(2);
	defaultCell.setVerticalAlignment(Element.ALIGN_TOP);
	defaultCell.setBorder(0);
	return table;
}
 
Example 4
Source File: PdfRuntimeDependenciesReport.java    From javamelody with Apache License 2.0 5 votes vote down vote up
private void writeHeader() throws DocumentException {
	final List<String> headers = new ArrayList<String>();
	headers.add("Beans");
	headers.addAll(calledBeans);
	final int[] relativeWidths = new int[headers.size()];
	Arrays.fill(relativeWidths, 0, headers.size(), 1);
	relativeWidths[0] = 4;

	final PdfPTable table = new PdfPTable(headers.size());
	table.setWidthPercentage(100);
	table.setWidths(relativeWidths);
	table.setHeaderRows(1);
	final PdfPCell defaultCell = table.getDefaultCell();
	defaultCell.setGrayFill(0.9f);
	defaultCell.setHorizontalAlignment(Element.ALIGN_CENTER);
	defaultCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
	defaultCell.setPaddingLeft(0);
	defaultCell.setPaddingRight(0);
	for (final String header : headers) {
		table.addCell(new Phrase(header, boldCellFont));
		// pas la première entête de colonne
		defaultCell.setRotation(90);
	}
	defaultCell.setRotation(0);
	defaultCell.setPaddingLeft(2);
	defaultCell.setPaddingRight(2);
	currentTable = table;
}
 
Example 5
Source File: PdfJavaInformationsReport.java    From javamelody with Apache License 2.0 5 votes vote down vote up
private static PdfPTable createJavaInformationsTable() throws DocumentException {
	final PdfPTable table = new PdfPTable(2);
	table.setHorizontalAlignment(Element.ALIGN_LEFT);
	table.setWidthPercentage(100);
	table.setWidths(new int[] { 2, 8 });
	table.getDefaultCell().setBorder(0);
	return table;
}
 
Example 6
Source File: PdfRequestAndGraphDetailReport.java    From javamelody with Apache License 2.0 5 votes vote down vote up
private void writeRequestRumData() throws DocumentException {
	final CounterRequestRumData rumData = request.getRumData();
	final DecimalFormat percentFormat = I18N.createPercentFormat();
	final int networkTimeMean = rumData.getNetworkTimeMean();
	final int serverMean = request.getMean();
	final int domProcessingMean = rumData.getDomProcessingMean();
	final int pageRenderingMean = rumData.getPageRenderingMean();
	final int totalTime = networkTimeMean + serverMean + domProcessingMean + pageRenderingMean;
	final double networkPercent = 100d * networkTimeMean / totalTime;
	final double serverPercent = 100d * serverMean / totalTime;
	final double domProcessingPercent = 100d * domProcessingMean / totalTime;
	final double pageRenderingPercent = 100d * pageRenderingMean / totalTime;

	final PdfPTable table = new PdfPTable(2);
	table.setHorizontalAlignment(Element.ALIGN_LEFT);
	table.setWidthPercentage(25);
	table.getDefaultCell().setBorderWidth(0);
	table.addCell(new Phrase(I18N.getString("Network"), cellFont));
	table.addCell(new Phrase(integerFormat.format(networkTimeMean) + " ms ("
			+ percentFormat.format(networkPercent) + "%)", cellFont));
	table.addCell(new Phrase(I18N.getString("Server"), cellFont));
	table.addCell(new Phrase(integerFormat.format(serverMean) + " ms ("
			+ percentFormat.format(serverPercent) + "%)", cellFont));
	table.addCell(new Phrase(I18N.getString("DOM_processing"), cellFont));
	table.addCell(new Phrase(integerFormat.format(domProcessingMean) + " ms ("
			+ percentFormat.format(domProcessingPercent) + "%)", cellFont));
	table.addCell(new Phrase(I18N.getString("Page_rendering"), cellFont));
	table.addCell(new Phrase(integerFormat.format(pageRenderingMean) + " ms ("
			+ percentFormat.format(pageRenderingPercent) + "%)", cellFont));
	addToDocument(table);
	addToDocument(new Phrase("\n", cellFont));
}
 
Example 7
Source File: GridUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void toPdfInternal( Grid grid, Document document, float spacing )
{
    if ( grid == null || grid.getVisibleWidth() == 0 )
    {
        return;
    }

    PdfPTable table = new PdfPTable( grid.getVisibleWidth() );

    table.setHeaderRows( 1 );
    table.setWidthPercentage( 100F );
    table.setKeepTogether( false );
    table.setSpacingAfter( spacing );

    table.addCell( resetPaddings( getTitleCell( grid.getTitle(), grid.getVisibleWidth() ), 0, 30, 0, 0 ) );

    if ( StringUtils.isNotEmpty( grid.getSubtitle() ) )
    {
        table.addCell( getSubtitleCell( grid.getSubtitle(), grid.getVisibleWidth() ) );
        table.addCell( getEmptyCell( grid.getVisibleWidth(), 30 ) );
    }

    for ( GridHeader header : grid.getVisibleHeaders() )
    {
        table.addCell( getItalicCell( header.getColumn() ) );
    }

    table.addCell( getEmptyCell( grid.getVisibleWidth(), 10 ) );

    for ( List<Object> row : grid.getVisibleRows() )
    {
        for ( Object col : row )
        {
            table.addCell( getTextCell( col ) );
        }
    }

    addTableToDocument( document, table );
}
 
Example 8
Source File: PdfExamGridTable.java    From unitime with Apache License 2.0 5 votes vote down vote up
private void createTable(boolean keepTogether) {
    iPdfTable = new PdfPTable(getNrColumns());
    iPdfTable.setWidthPercentage(100);
    iPdfTable.getDefaultCell().setPadding(3);
    iPdfTable.getDefaultCell().setBorderWidth(1);
    iPdfTable.setSplitRows(false);
    iPdfTable.setSpacingBefore(10);
    iPdfTable.setKeepTogether(keepTogether);
}
 
Example 9
Source File: PdfTimetableGridTable.java    From unitime with Apache License 2.0 5 votes vote down vote up
private void createTable() {
	iPdfTable = new PdfPTable(getNrColumns());
	iPdfTable.setWidthPercentage(100);
	iPdfTable.getDefaultCell().setPadding(3);
	iPdfTable.getDefaultCell().setBorderWidth(1);
	iPdfTable.setSplitRows(false);
	iPdfTable.setSpacingBefore(10);
	if (iTable.isDispModePerWeek()) {
		iPdfTable.setKeepTogether(true);
	}
}
 
Example 10
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 11
Source File: PdfExportService.java    From fredbet with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
private <T> PdfPTable createTable(List<T> data, RowCallback<T> rowCallback, PdfTableData pdfTableData) {
    PdfPTable table = new PdfPTable(pdfTableData.getColumnWidths());
    table.setWidthPercentage(100);

    addRowToTable(table, pdfTableData.getHeaderColumns(), true);

    data.forEach(dataEntry -> {
        RowContentAdder rowContentAdder = new RowContentAdder();
        rowCallback.onRow(rowContentAdder, dataEntry);
        List<String> rowContent = rowContentAdder.getRowContent();
        addRowToTable(table, rowContent, false);
    });
    return table;
}
 
Example 12
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 13
Source File: CellWidthsTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Width manipulations of cells.
 * 
 */
@Test
public void main() throws Exception {
	// step1
	Document document = new Document(PageSize.A4, 36, 36, 36, 36);
	// step2
	PdfWriter.getInstance(document, PdfTestBase.getOutputStream("CellWidths.pdf"));
	// step3
	document.open();
	// step4
	float[] widths = { 0.1f, 0.1f, 0.05f, 0.75f };
	PdfPTable table = new PdfPTable(widths);
	table.addCell("10%");
	table.addCell("10%");
	table.addCell("5%");
	table.addCell("75%");
	table.addCell("aa");
	table.addCell("aa");
	table.addCell("a");
	table.addCell("aaaaaaaaaaaaaaa");
	table.addCell("bb");
	table.addCell("bb");
	table.addCell("b");
	table.addCell("bbbbbbbbbbbbbbb");
	table.addCell("cc");
	table.addCell("cc");
	table.addCell("c");
	table.addCell("ccccccccccccccc");
	document.add(table);
	document.add(new Paragraph("We change the percentages:\n\n"));
	widths[0] = 20f;
	widths[1] = 20f;
	widths[2] = 10f;
	widths[3] = 50f;
	table.setWidths(widths);
	document.add(table);
	widths[0] = 40f;
	widths[1] = 40f;
	widths[2] = 20f;
	widths[3] = 300f;
	Rectangle r = new Rectangle(PageSize.A4.getRight(72), PageSize.A4.getTop(72));
	table.setWidthPercentage(widths, r);
	document.add(new Paragraph("We change the percentage using absolute widths:\n\n"));
	document.add(table);
	document.add(new Paragraph("We use a locked width:\n\n"));
	table.setTotalWidth(300);
	table.setLockedWidth(true);
	document.add(table);

	// step5
	document.close();
}
 
Example 14
Source File: DefaultPdfDataEntryFormService.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void setMainTable( PdfPTable mainTable )
{
    mainTable.setWidthPercentage( 100.0f );
    mainTable.setHorizontalAlignment( Element.ALIGN_LEFT );
}
 
Example 15
Source File: DefaultPdfDataEntryFormService.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void insertTable_DataSetSections( PdfPTable mainTable, PdfWriter writer, Rectangle rectangle,
    Collection<DataElement> dataElements, String sectionName )
    throws IOException, DocumentException
{
    boolean hasBorder = true;

    // Add Section Name and Section Spacing
    insertTable_TextRow( writer, mainTable, TEXT_BLANK );

    if ( sectionName != null && !sectionName.isEmpty() )
    {
        insertTable_TextRow( writer, mainTable, sectionName,
            pdfFormFontSettings.getFont( PdfFormFontSettings.FONTTYPE_SECTIONHEADER ) );
    }

    // Create A Table To Add For Each Section
    PdfPTable table = new PdfPTable( 2 );

    table.setWidths( new int[]{ 2, 1 } );
    table.setWidthPercentage( 100.0f );
    table.setHorizontalAlignment( Element.ALIGN_LEFT );


    // For each DataElement and Category Combo of the dataElement, create
    // row.
    for ( DataElement dataElement : dataElements )
    {
        for ( CategoryOptionCombo categoryOptionCombo : dataElement.getSortedCategoryOptionCombos() )
        {
            String categoryOptionComboDisplayName = "";

            // Hide Default category option combo name
            if ( !categoryOptionCombo.isDefault() )
            {
                categoryOptionComboDisplayName = categoryOptionCombo.getDisplayName();
            }

            addCell_Text( table, PdfDataEntryFormUtil.getPdfPCell( hasBorder ), dataElement.getFormNameFallback() + " " +
                categoryOptionComboDisplayName, Element.ALIGN_RIGHT );

            String strFieldLabel = PdfDataEntryFormUtil.LABELCODE_DATAENTRYTEXTFIELD + dataElement.getUid() + "_"
                + categoryOptionCombo.getUid();

            ValueType valueType = dataElement.getValueType();

            // Yes Only case - render as check-box
            if ( ValueType.TRUE_ONLY == valueType )
            {
                addCell_WithCheckBox( table, writer, PdfDataEntryFormUtil.getPdfPCell( hasBorder ), strFieldLabel );
            }
            else if ( ValueType.BOOLEAN == valueType )
            {
                // Create Yes - true, No - false, Select..
                String[] optionList = new String[]{ "[No Value]", "Yes", "No" };
                String[] valueList = new String[]{ "", "true", "false" };

                // addCell_WithRadioButton(table, writer, strFieldLabel);
                addCell_WithDropDownListField( table, rectangle, writer, PdfDataEntryFormUtil.getPdfPCell( hasBorder ), strFieldLabel, optionList, valueList );
            }
            else if ( valueType.isNumeric() )
            {
                Rectangle rectNum = new Rectangle( TEXTBOXWIDTH_NUMBERTYPE, PdfDataEntryFormUtil.CONTENT_HEIGHT_DEFAULT );

                addCell_WithTextField( table, rectNum, writer, PdfDataEntryFormUtil.getPdfPCell( hasBorder ), strFieldLabel, PdfFieldCell.TYPE_TEXT_NUMBER );
            }
            else
            {
                addCell_WithTextField( table, rectangle, writer, PdfDataEntryFormUtil.getPdfPCell( hasBorder ), strFieldLabel );
            }
        }
    }

    PdfPCell cell_withInnerTable = new PdfPCell( table );
    cell_withInnerTable.setBorder( Rectangle.NO_BORDER );

    mainTable.addCell( cell_withInnerTable );
}
 
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: BarcodesTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * List with different Barcode types.
 */
@Test
public void main() throws Exception {

	// step 1: creation of a document-object
	Document document = new Document(PageSize.A4, 50, 50, 50, 50);

	// step 2: creation of the writer
	PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("barcodes.pdf"));

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

	// step 4: we add content to the document
	PdfContentByte cb = writer.getDirectContent();
	Barcode39 code39 = new Barcode39();
	code39.setCode("CODE39-1234567890");
	code39.setStartStopText(false);
	Image image39 = code39.createImageWithBarcode(cb, null, null);
	Barcode39 code39ext = new Barcode39();
	code39ext.setCode("The willows.");
	code39ext.setStartStopText(false);
	code39ext.setExtended(true);
	Image image39ext = code39ext.createImageWithBarcode(cb, null, null);
	Barcode128 code128 = new Barcode128();
	code128.setCode("1Z234786 hello");
	Image image128 = code128.createImageWithBarcode(cb, null, null);
	BarcodeEAN codeEAN = new BarcodeEAN();
	codeEAN.setCodeType(Barcode.EAN13);
	codeEAN.setCode("9780201615883");
	Image imageEAN = codeEAN.createImageWithBarcode(cb, null, null);
	BarcodeInter25 code25 = new BarcodeInter25();
	code25.setGenerateChecksum(true);
	code25.setCode("41-1200076041-001");
	Image image25 = code25.createImageWithBarcode(cb, null, null);
	BarcodePostnet codePost = new BarcodePostnet();
	codePost.setCode("12345");
	Image imagePost = codePost.createImageWithBarcode(cb, null, null);
	BarcodePostnet codePlanet = new BarcodePostnet();
	codePlanet.setCode("50201402356");
	codePlanet.setCodeType(Barcode.PLANET);
	Image imagePlanet = codePlanet.createImageWithBarcode(cb, null, null);
	BarcodeEAN codeSUPP = new BarcodeEAN();
	codeSUPP.setCodeType(Barcode.SUPP5);
	codeSUPP.setCode("54995");
	codeSUPP.setBaseline(-2);
	BarcodeEANSUPP eanSupp = new BarcodeEANSUPP(codeEAN, codeSUPP);
	Image imageEANSUPP = eanSupp.createImageWithBarcode(cb, null, Color.blue);
	PdfPTable table = new PdfPTable(2);
	table.setWidthPercentage(100);
	table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
	table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
	table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);
	table.getDefaultCell().setFixedHeight(70);
	table.addCell("CODE 39");
	table.addCell(new Phrase(new Chunk(image39, 0, 0)));
	table.addCell("CODE 39 EXTENDED");
	table.addCell(new Phrase(new Chunk(image39ext, 0, 0)));
	table.addCell("CODE 128");
	table.addCell(new Phrase(new Chunk(image128, 0, 0)));
	table.addCell("CODE EAN");
	table.addCell(new Phrase(new Chunk(imageEAN, 0, 0)));
	table.addCell("CODE EAN\nWITH\nSUPPLEMENTAL 5");
	table.addCell(new Phrase(new Chunk(imageEANSUPP, 0, 0)));
	table.addCell("CODE INTERLEAVED");
	table.addCell(new Phrase(new Chunk(image25, 0, 0)));
	table.addCell("CODE POSTNET");
	table.addCell(new Phrase(new Chunk(imagePost, 0, 0)));
	table.addCell("CODE PLANET");
	table.addCell(new Phrase(new Chunk(imagePlanet, 0, 0)));
	document.add(table);

	// step 5: we close the document
	document.close();
}
 
Example 18
Source File: TemplateImagesTest.java    From itext2 with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
    * PdfTemplates can be wrapped in an Image.
    */
@Test
   public  void main() throws Exception {
       
           
       // step 1: creation of a document-object
       Rectangle rect = new Rectangle(PageSize.A4);
       rect.setBackgroundColor(new Color(238, 221, 88));
       Document document = new Document(rect, 50, 50, 50, 50);
	// step 2: we create a writer that listens to the document
	PdfWriter writer = PdfWriter.getInstance(document, PdfTestBase.getOutputStream("templateImages.pdf"));
	// step 3: we open the document
	document.open();
	// step 4:
	PdfTemplate template = writer.getDirectContent().createTemplate(20, 20);
	BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI,
			BaseFont.NOT_EMBEDDED);
	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);
	template.sanityCheck();
	Image img = Image.getInstance(template);
	img.setRotationDegrees(90);
	Chunk ck = new Chunk(img, 0, 0);
	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");

	Paragraph p1 = new Paragraph("This is a template ");
	p1.add(ck);
	p1.add(" just here.");
	p1.setLeading(img.getScaledHeight() * 1.1f);
	document.add(p1);
	document.add(table);
	Paragraph p2 = new Paragraph("More templates ");
	p2.setLeading(img.getScaledHeight() * 1.1f);
	p2.setAlignment(Element.ALIGN_JUSTIFIED);
	img.scalePercent(70);
	for (int k = 0; k < 20; ++k)
		p2.add(ck);
	document.add(p2);
	// step 5: we close the document
	document.close();

   }
 
Example 19
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;
}
 
Example 20
Source File: PDFUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
/**
 * <p>
 * Creates a table. Specify the columns and widths by providing one<br>
 * float per column with a percentage value. For instance
 * </p>
 * <p>
 * <p>
 * getPdfPTable( 0.35f, 0.65f )
 * </p>
 * <p>
 * <p>
 * will give you a table with two columns where the first covers 35 %<br>
 * of the page while the second covers 65 %.
 * </p>
 *
 * @param keepTogether Indicates whether the table could be broken across
 *                     multiple pages or should be kept at one page.
 * @param columnWidths The column widths.
 * @return
 */
public static PdfPTable getPdfPTable( boolean keepTogether, float... columnWidths )
{
    PdfPTable table = new PdfPTable( columnWidths );

    table.setWidthPercentage( 100f );
    table.setKeepTogether( keepTogether );

    return table;
}