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

The following examples show how to use com.itextpdf.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: CreateTableDirectContent.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
     * <a href="http://stackoverflow.com/questions/43807931/creating-table-in-pdf-on-last-page-bottom-wrong-official-solution">
     * Creating table in pdf on last page bottom (wrong official solution)
     * </a>
     * <p>
     * Helper method for {@link #testCreateTableLikeUser7968180()}.
     * </p>
     */
    private static PdfPTable createFooterTable() throws DocumentException
    {
        int[] columnWidths = new int[] { 1, 1, 1, 1, 1, 1, 1, 1, 1 };
        PdfPTable datatable = new PdfPTable(columnWidths.length);
        datatable.setKeepTogether(true);
        datatable.setWidthPercentage(100);
        datatable.setWidths(columnWidths);
        datatable.getDefaultCell().setPadding(5);

//        datatable.getDefaultCell().setHorizontalAlignment(horizontalAlignment);
//        datatable.getDefaultCell().setVerticalAlignment(verticalAlignment);

        for (int i = 0; i < 100; i++)
        {
            datatable.addCell("Přehledová tabulka");
//            addCellToTable(datatable, horizontalAlignmentLeft, verticalAlignmentMiddle, "Přehledová tabulka",
//                    columnWidths.length, 1, fontTypeBold, fontSizeRegular, cellLayout_Bottom);
        }

        return datatable;
    }
 
Example 2
Source File: AbstractPdfReportBuilder.java    From bdf3 with Apache License 2.0 6 votes vote down vote up
protected PdfPTable createGridTable(ReportDataModel dataModel, boolean isRepeatHeader) throws Exception {
	PdfPTable table = new PdfPTable(calculateGridColumnCount(dataModel.getTopColumnHeaders()));
	table.setWidthPercentage(100);
	Collection<ColumnHeader> topHeaders = dataModel.getTopColumnHeaders();
	List<Integer> widths = new ArrayList<Integer>();
	generateGridColumnWidths(topHeaders, widths);
	int[] values = new int[widths.size()];
	for (int i = 0; i < widths.size(); i++) {
		values[i] = widths.get(i);
	}
	table.setWidths(values);
	int maxHeaderLevel = getGridMaxColumngroup(topHeaders);
	createGridColumnHeader(table, topHeaders, maxHeaderLevel);
	createGridTableDatas(table, dataModel.getReportData());
	if (isRepeatHeader) {
		table.setHeaderRows(maxHeaderLevel);
	}
	return table;
}
 
Example 3
Source File: AddField.java    From testarea-itext5 with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
     * <a href="http://stackoverflow.com/questions/35630320/itext-java-android-adding-fields-to-existing-pdf">
     * iText - Java Android - Adding fields to existing pdf
     * </a>
     * <p>
     * There actually are two issues in the OP's code:
     * </p>
     * <ol>
     * <li>he creates the fields with empty names
     * <li>he doesn't set border colors for his fields
     * </ol>
     * <p>
     * These issues are fixed in {@link #testAddLikePasquierCorentin()},
     * {@link CheckboxCellEvent}, and {@link MyCellField} below.
     * </p>
     */
    @Test
    public void testAddLikePasquierCorentin() throws IOException, DocumentException
    {
        File myFile = new File(RESULT_FOLDER, "preface-withField.pdf");
        
        try (   InputStream resource = getClass().getResourceAsStream("/mkl/testarea/itext5/extract/preface.pdf");
                OutputStream output = new FileOutputStream(myFile)  )
        {
            PdfReader pdfReader = new PdfReader(resource);

            pdfStamper = new PdfStamper(pdfReader, output);

            PdfContentByte canvas1;
            PdfContentByte canvas2;

            canvas1 = pdfStamper.getOverContent(1);
            canvas2 = pdfStamper.getOverContent(2);

            PdfPCell cellFillFieldPage1 = new PdfPCell();
// change: Use a non-empty name
            cellFillFieldPage1.setCellEvent(new MyCellField("A", 1));
            cellFillFieldPage1.setFixedHeight(15);
            cellFillFieldPage1.setBorder(Rectangle.NO_BORDER);
            cellFillFieldPage1.setVerticalAlignment(Element.ALIGN_MIDDLE);

            PdfPCell cellCheckBoxPage2 = new PdfPCell();
// change: Use a non-empty name different from the one above
            cellCheckBoxPage2.setCellEvent(new CheckboxCellEvent("B", false, 2));
            cellCheckBoxPage2.setBorder(Rectangle.NO_BORDER);

            // ************** PAGE 1 ************** //

            // SET TABLE
            PdfPTable tableSection1Page1 = new PdfPTable(1);
            tableSection1Page1.setTotalWidth(136);
            tableSection1Page1.setWidthPercentage(100.0f);
            tableSection1Page1.setLockedWidth(true);

            // ADD CELLS TO TABLE
            tableSection1Page1.addCell(cellFillFieldPage1);


            // PRINT TABLES
            tableSection1Page1.writeSelectedRows(0, -1, 165, 530, canvas1);


            // ************ PAGE 2 ************ //

            // SET TABLES
            PdfPTable tableSection1Page2 = new PdfPTable(1);
            tableSection1Page2.setTotalWidth(10);
            tableSection1Page2.setWidthPercentage(100.0f);
            tableSection1Page2.setLockedWidth(true);

            // ADD CELLS TO TABLE
            tableSection1Page2.addCell(cellCheckBoxPage2);

            // PRINT TABLES
            tableSection1Page2.writeSelectedRows(0, -1, 182, 536, canvas2);

            // I tried this, but it didn't change anything
            pdfStamper.setFormFlattening(false);

            pdfStamper.close();
            pdfReader.close();
        }
    }
 
Example 4
Source File: HRPDFBuilderImpl.java    From Spring-MVC-Blueprints with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected void buildPdfDocument(Map<String, Object> model, Document doc,
        PdfWriter writer, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    // get data model which is passed by the Spring container
    List<HrmsLogin> users = (List<HrmsLogin>) model.get("allUsers");
     
    doc.add(new Paragraph("Master List of Users"));
     
    PdfPTable table = new PdfPTable(4);
    table.setWidthPercentage(100.0f);
    table.setWidths(new float[] {3.0f, 2.0f, 2.0f, 2.0f});
    table.setSpacingBefore(10);
     
    // define font for table header row
    Font font = FontFactory.getFont(FontFactory.HELVETICA);
    font.setColor(BaseColor.WHITE);
     
    // define table header cell
    PdfPCell cell = new PdfPCell();
    cell.setBackgroundColor(BaseColor.BLUE);
    cell.setPadding(5);
     
    // write table header
    cell.setPhrase(new Phrase("Employee ID", font));
    table.addCell(cell);
     
    cell.setPhrase(new Phrase("Username", font));
    table.addCell(cell);
	 
    cell.setPhrase(new Phrase("Password", font));
    table.addCell(cell);
     
    cell.setPhrase(new Phrase("Role", font));
    table.addCell(cell);
     
   
     
    // write table row data
    for (HrmsLogin user : users) {
        table.addCell(user.getHrmsEmployeeDetails().getEmpId()+"");
        table.addCell(user.getUsername());
        table.addCell(user.getPassword());
        table.addCell(user.getRole());
        
    }
     
    doc.add(table);
     
}
 
Example 5
Source File: PersonalReportPdfCommand.java    From bamboobsc with Apache License 2.0 4 votes vote down vote up
private String createPdf(Context context) throws Exception {
	BscReportPropertyUtils.loadData();
	String visionOid = (String)context.get("visionOid");
	VisionVO vision = null;
	BscStructTreeObj treeObj = (BscStructTreeObj)this.getResult(context);
	for (VisionVO visionObj : treeObj.getVisions()) {
		if (visionObj.getOid().equals(visionOid)) {
			vision = visionObj;
		}
	}		
	FontFactory.register(BscConstants.PDF_ITEXT_FONT);
	String fileName = SimpleUtils.getUUIDStr() + ".pdf";
	String fileFullPath = Constants.getWorkTmpDir() + "/" + fileName;
	OutputStream os = new FileOutputStream(fileFullPath);
	Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);	
	document.left(100f);
	document.top(150f);
	PdfWriter writer = PdfWriter.getInstance(document, os);
	document.open();  
	
	PdfPTable table = new PdfPTable(MAX_COLSPAN);
	table.setWidthPercentage(100f);	
	PdfPTable signTable = new PdfPTable( 1 );
	signTable.setWidthPercentage(100f);
	
	this.createHead(table, vision, context);
	this.createBody(table, vision);
	this.createFoot(table, context);
	this.putSignature(signTable, context);
	
	document.add(table);
	document.add(signTable);
	document.close();
	writer.close();			
	
	os.flush();
	os.close();
	os = null;
	
	File file = new File(fileFullPath);
	String oid = UploadSupportUtils.create(
			Constants.getSystem(), UploadTypes.IS_TEMP, false, file, "personal-report.pdf");
	file = null;
	return oid;
}
 
Example 6
Source File: KpiReportPdfCommand.java    From bamboobsc with Apache License 2.0 4 votes vote down vote up
private String createPdf(Context context) throws Exception {
	BscReportPropertyUtils.loadData();
	BscReportSupportUtils.loadExpression(); // 2015-04-18 add
	String visionOid = (String)context.get("visionOid");
	VisionVO vision = null;
	BscStructTreeObj treeObj = (BscStructTreeObj)this.getResult(context);
	for (VisionVO visionObj : treeObj.getVisions()) {
		if (visionObj.getOid().equals(visionOid)) {
			vision = visionObj;
		}
	}		
	FontFactory.register(BscConstants.PDF_ITEXT_FONT);
	String fileName = SimpleUtils.getUUIDStr() + ".pdf";
	String fileFullPath = Constants.getWorkTmpDir() + "/" + fileName;
	OutputStream os = new FileOutputStream(fileFullPath);
	//Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);
	Document document = new Document(PageSize.A4, 10, 10, 10, 10);		
	document.left(100f);
	document.top(150f);
	PdfWriter writer = PdfWriter.getInstance(document, os);
	document.open();  
	
	int dateRangeRows = 4 + vision.getPerspectives().get(0).getObjectives().get(0).getKpis().get(0).getDateRangeScores().size();
	PdfPTable table = new PdfPTable(MAX_COLSPAN);
	PdfPTable dateRangeTable = new PdfPTable( dateRangeRows );
	PdfPTable chartsTable = new PdfPTable( 2 );
	PdfPTable signTable = new PdfPTable( 1 );
	table.setWidthPercentage(100f);	
	dateRangeTable.setWidthPercentage(100f);
	chartsTable.setWidthPercentage(100f);
	signTable.setWidthPercentage(100f);
	
	this.createHead(table, vision);
	this.createBody(table, vision);
	this.createDateRange(dateRangeTable, vision, context, dateRangeRows);		
	this.putCharts(chartsTable, context);
	this.putSignature(signTable, context);
	
	document.add(chartsTable);
	document.add(table);  
	document.add(dateRangeTable);  
	document.add(signTable);
	document.close();
	writer.close();			
	
	os.flush();
	os.close();
	os = null;
	
	File file = new File(fileFullPath);
	String oid = UploadSupportUtils.create(
			Constants.getSystem(), UploadTypes.IS_TEMP, false, file, "kpi-report.pdf");
	file = null;
	return oid;
}
 
Example 7
Source File: OrganizationReportPdfCommand.java    From bamboobsc with Apache License 2.0 4 votes vote down vote up
private String createPdf(Context context) throws Exception {
	BscReportPropertyUtils.loadData();
	String visionOid = (String)context.get("visionOid");
	VisionVO vision = null;
	BscStructTreeObj treeObj = (BscStructTreeObj)this.getResult(context);
	for (VisionVO visionObj : treeObj.getVisions()) {
		if (visionObj.getOid().equals(visionOid)) {
			vision = visionObj;
		}
	}		
	FontFactory.register(BscConstants.PDF_ITEXT_FONT);
	String fileName = SimpleUtils.getUUIDStr() + ".pdf";
	String fileFullPath = Constants.getWorkTmpDir() + "/" + fileName;
	OutputStream os = new FileOutputStream(fileFullPath);
	Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);	
	document.left(100f);
	document.top(150f);
	PdfWriter writer = PdfWriter.getInstance(document, os);
	document.open();  
	
	PdfPTable table = new PdfPTable(MAX_COLSPAN);
	table.setWidthPercentage(100f);	
	PdfPTable signTable = new PdfPTable( 1 );
	signTable.setWidthPercentage(100f);		
	
	this.createHead(table, vision, context);
	this.createBody(table, vision);
	
	this.putSignature(signTable, context);		
	
	document.add(table); 
	document.add(signTable);
	document.close();
	writer.close();			
	
	os.flush();
	os.close();
	os = null;
	
	File file = new File(fileFullPath);
	String oid = UploadSupportUtils.create(
			Constants.getSystem(), UploadTypes.IS_TEMP, false, file, "department-report.pdf");
	file = null;
	return oid;		
}
 
Example 8
Source File: Metodos.java    From ExamplesAndroid with Apache License 2.0 4 votes vote down vote up
public void GeneratePDF()
{
    Document document = new Document();
    try
    {
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("/sdcard/TutorialesHackro/hoja.pdf"));

        document.open();

        PdfPTable table = new PdfPTable(3); // 3 columns.
        table.setWidthPercentage(100); //Width 100%
        table.setSpacingBefore(10f); //Space before table
        table.setSpacingAfter(10f); //Space after table

        //Set Column widths
        float[] columnWidths = {1f, 1f, 1f};
        table.setWidths(columnWidths);

        PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1"));
        cell1.setBorderColor(BaseColor.BLUE);
        cell1.setPaddingLeft(10);
        cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);

        PdfPCell cell2 = new PdfPCell(new Paragraph("Cell 2"));
        cell2.setBorderColor(BaseColor.GREEN);
        cell2.setPaddingLeft(10);
        cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);

        PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 3"));
        cell3.setBorderColor(BaseColor.RED);
        cell3.setPaddingLeft(10);
        cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);

        //To avoid having the cell border and the content overlap, if you are having thick cell borders
        //cell1.setUserBorderPadding(true);
        //cell2.setUserBorderPadding(true);
        //cell3.setUserBorderPadding(true);

        table.addCell(cell1);
        table.addCell(cell2);
        table.addCell(cell3);

        document.add(table);

        createDirectoryAndSaveFile(writer, "david");
        document.close();
        writer.close();
    } catch (Exception e)
    {
        e.printStackTrace();
        Log.e("ewdfhyfafedyatfawytedfytew b",e.getMessage());
    }

}
 
Example 9
Source File: ThemeImpl.java    From ganttproject with GNU General Public License v3.0 4 votes vote down vote up
private PdfPTable createTableHeader(ColumnList tableHeader, ArrayList<Column> orderedColumns) {
  for (int i = 0; i < tableHeader.getSize(); i++) {
    Column c = tableHeader.getField(i);
    if (c.isVisible()) {
      orderedColumns.add(c);
    }
  }
  Collections.sort(orderedColumns, new Comparator<Column>() {
    @Override
    public int compare(Column lhs, Column rhs) {
      if (lhs == null || rhs == null) {
        return 0;
      }
      return lhs.getOrder() - rhs.getOrder();
    }
  });
  float[] widths = new float[orderedColumns.size()];
  for (int i = 0; i < orderedColumns.size(); i++) {
    Column column = orderedColumns.get(i);
    widths[i] = column.getWidth();
  }

  PdfPTable table = new PdfPTable(widths);
  table.setWidthPercentage(95);
  for (Column field : orderedColumns) {
    if (field.isVisible()) {
      PdfPCell cell = new PdfPCell(new Paragraph(field.getName(), getSansRegularBold(12f)));
      cell.setPaddingTop(4);
      cell.setPaddingBottom(4);
      cell.setPaddingLeft(5);
      cell.setPaddingRight(5);
      cell.setBorderWidth(0);
      cell.setBorder(PdfPCell.BOTTOM);
      cell.setBorderWidthBottom(1);
      cell.setBorderColor(SORTAVALA_GREEN);
      table.addCell(cell);
    }
  }
  table.setHeaderRows(1);
  return table;
}