com.itextpdf.text.pdf.PdfPCell Java Examples

The following examples show how to use com.itextpdf.text.pdf.PdfPCell. 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: DynamicFooter.java    From testarea-itext5 with GNU Affero General Public License v3.0 11 votes vote down vote up
public PdfPTable generateFooter() {
    try {
        BaseFont baseFont = BaseFont.createFont(/*"resources/ARIAL.TTF"*/ "c:/Windows/Fonts/arial.ttf", BaseFont.IDENTITY_H, true);
        footerTable = new PdfPTable(1);
        footerTable.setTotalWidth(440);
        footerTable.setLockedWidth(true);

        Font pageNumberFont = new Font(baseFont, 9, Font.BOLD);
        Paragraph pageNumberP = new Paragraph(titleIndex+"-"+ pageNumber, pageNumberFont);
        PdfPCell pageNumberCell = new PdfPCell(pageNumberP);
        pageNumberCell.setBorder(0);
        pageNumberCell.setPaddingTop(20);
        footerTable.addCell(pageNumberCell);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return footerTable;
}
 
Example #2
Source File: PDFSampleMain.java    From tutorials with MIT License 7 votes vote down vote up
private static void addCustomRows(PdfPTable table) throws URISyntaxException, BadElementException, IOException {
    Path path = Paths.get(ClassLoader.getSystemResource("Java_logo.png").toURI());
    Image img = Image.getInstance(path.toAbsolutePath().toString());
    img.scalePercent(10);

    PdfPCell imageCell = new PdfPCell(img);
    table.addCell(imageCell);

    PdfPCell horizontalAlignCell = new PdfPCell(new Phrase("row 2, col 2"));
    horizontalAlignCell.setHorizontalAlignment(Element.ALIGN_CENTER);
    table.addCell(horizontalAlignCell);

    PdfPCell verticalAlignCell = new PdfPCell(new Phrase("row 2, col 3"));
    verticalAlignCell.setVerticalAlignment(Element.ALIGN_BOTTOM);
    table.addCell(verticalAlignCell);
}
 
Example #3
Source File: ParseHtml.java    From xiaoyaoji with GNU General Public License v3.0 7 votes vote down vote up
public void createPdf(String file) throws IOException, DocumentException {
    // step 1
    Document document = new Document();
    // step 2
    PdfWriter.getInstance(document, new FileOutputStream(file));
    // step 3
    document.open();
    // step 4
    StringBuilder sb = new StringBuilder();
    sb.append("<div>\n<p align=\"center\">");
    sb.append("<font size=\"5\">");
    sb.append("<b>&nbsp;<font color=\"#32cd32\">My centered Para</font></b>");
    sb.append("</font>");
    sb.append("<font color=\"#32cd32\">&nbsp;</font>");
    sb.append("</p>\n</div>");
    
    PdfPTable table = new PdfPTable(1);
    PdfPCell cell = new PdfPCell();
    ElementList list = XMLWorkerHelper.parseToElementList(sb.toString(), null);
    for (Element element : list) {
        cell.addElement(element);
    }
    table.addCell(cell);
    document.add(table);
    
    // step 5
    document.close();
}
 
Example #4
Source File: PageHeaderFooterEvent.java    From ureport with Apache License 2.0 7 votes vote down vote up
private PdfPCell buildPdfPCell(HeaderFooter phf,String text,int type){
	PdfPCell cell=new PdfPCell();
	cell.setPadding(0);
	cell.setBorder(Rectangle.NO_BORDER);
	Font font=FontBuilder.getFont(phf.getFontFamily(), phf.getFontSize(), phf.isBold(), phf.isItalic(),phf.isUnderline());
	String fontColor=phf.getForecolor();
	if(StringUtils.isNotEmpty(fontColor)){
		String[] color=fontColor.split(",");
		font.setColor(Integer.valueOf(color[0]), Integer.valueOf(color[1]), Integer.valueOf(color[2]));			
	}
	Paragraph graph=new Paragraph(text,font);
	cell.setPhrase(graph);
	switch(type){
	case 1:
		cell.setHorizontalAlignment(Element.ALIGN_LEFT);
		break;
	case 2:
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		break;
	case 3:
		cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
		break;
	}
	cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
	return cell;
}
 
Example #5
Source File: PercentileCellBackground.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
    public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) {
        PdfContentByte canvas = canvases[PdfPTable.BACKGROUNDCANVAS];

        float xTransition = position.getLeft() + (position.getRight() - position.getLeft()) * (percent/100.0f);
        float yTransition = (position.getTop() + position.getBottom()) / 2f;
        float radius = (position.getRight() - position.getLeft()) * 0.025f;
        PdfShading axial = PdfShading.simpleAxial(canvas.getPdfWriter(),
                xTransition - radius, yTransition, xTransition + radius, yTransition, leftColor, rightColor);
        PdfShadingPattern shading = new PdfShadingPattern(axial);

        canvas.saveState();
        canvas.setShadingFill(shading);
        canvas.rectangle(position.getLeft(), position.getBottom(), position.getWidth(), position.getHeight());
//        canvas.clip();
        canvas.fill();
        canvas.restoreState();
    }
 
Example #6
Source File: ThemeImpl.java    From ganttproject with GNU General Public License v3.0 6 votes vote down vote up
private void writeResources() throws Exception {
  ColumnList visibleFields = getUIFacade().getResourceTree().getVisibleFields();
  final ArrayList<Column> orderedColumns = new ArrayList<>();
  final PdfPTable table = createTableHeader(visibleFields, orderedColumns);
  List<HumanResource> resources = getProject().getHumanResourceManager().getResources();

  PropertyFetcher propFetcher = new PropertyFetcher(getProject());
  for (HumanResource resource : resources) {
    HashMap<String, String> id2value = new HashMap<>();
    propFetcher.getResourceAttributes(resource, id2value);
    HashMap<String, PdfPCell> id2cell = new HashMap<>();
    writeProperties(orderedColumns, id2value, table, id2cell);
  }
  myDoc.add(table);

}
 
Example #7
Source File: PDFExport.java    From MtgDesktopCompanion with GNU General Public License v3.0 6 votes vote down vote up
private PdfPCell getCells(MagicCard card) throws BadElementException, IOException {

		Image image1 = null;
		try {
			image1 = Image.getInstance(MTGControler.getInstance().getEnabled(MTGPictureProvider.class).getPicture(card, null),
					null);
		} catch (Exception e) {
			image1 = Image.getInstance(MTGControler.getInstance().getEnabled(MTGPictureProvider.class).getBackPicture(), null);
		}

		int h = getInt("CARD_HEIGHT");
		int w = getInt("CARD_WIDTH");

		image1.scaleAbsolute(w, h);

		PdfPCell cell = new PdfPCell(image1, false);
		cell.setBorder(0);
		cell.setPadding(5);
	
		return cell;
	}
 
Example #8
Source File: OrganizationReportPdfCommand.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
private void putSignature(PdfPTable table, Context context) throws Exception {
	String uploadOid = (String)context.get("uploadSignatureOid");
	if ( StringUtils.isBlank(uploadOid) ) {
		return;
	}
	byte[] imageBytes = UploadSupportUtils.getDataBytes( uploadOid );
	if ( null == imageBytes ) {
		return;
	}
	Image signatureImgObj = Image.getInstance( imageBytes );
	signatureImgObj.setWidthPercentage(40f);
	PdfPCell cell = new PdfPCell();
	cell.setBorder( Rectangle.NO_BORDER );
	cell.addElement(signatureImgObj);
	table.addCell(cell);		
}
 
Example #9
Source File: KpiReportPdfCommand.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
private void putSignature(PdfPTable table, Context context) throws Exception {
	String uploadOid = (String)context.get("uploadSignatureOid");
	if ( StringUtils.isBlank(uploadOid) ) {
		return;
	}
	byte[] imageBytes = UploadSupportUtils.getDataBytes( uploadOid );
	if ( null == imageBytes ) {
		return;
	}
	Image signatureImgObj = Image.getInstance( imageBytes );
	signatureImgObj.setWidthPercentage(40f);
	PdfPCell cell = new PdfPCell();
	cell.setBorder( Rectangle.NO_BORDER );
	cell.addElement(signatureImgObj);
	table.addCell(cell);		
}
 
Example #10
Source File: PersonalReportPdfCommand.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
private void putSignature(PdfPTable table, Context context) throws Exception {
	String uploadOid = (String)context.get("uploadSignatureOid");
	if ( StringUtils.isBlank(uploadOid) ) {
		return;
	}
	byte[] imageBytes = UploadSupportUtils.getDataBytes( uploadOid );
	if ( null == imageBytes ) {
		return;
	}
	Image signatureImgObj = Image.getInstance( imageBytes );
	signatureImgObj.setWidthPercentage(40f);
	PdfPCell cell = new PdfPCell();
	cell.setBorder( Rectangle.NO_BORDER );
	cell.addElement(signatureImgObj);
	table.addCell(cell);		
}
 
Example #11
Source File: AbstractPdfReportBuilder.java    From bdf3 with Apache License 2.0 6 votes vote down vote up
private void createGridTableDatas(PdfPTable table, Collection<ReportData> datas) {
	for (ReportData data : datas) {
		PdfPCell cell = new PdfPCell(createParagraph(data.getTextChunk()));
		cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
		int level = this.calculateIndentationCount(data.getTextChunk().getText());
		if (data.getBgColor() != null) {
			int[] colors = data.getBgColor();
			cell.setBackgroundColor(new BaseColor(colors[0], colors[1], colors[2]));
		}
		if (level == 0) {
			cell.setHorizontalAlignment(data.getAlign());
		} else {
			cell.setIndent(20 * level);
		}
		table.addCell(cell);
	}
}
 
Example #12
Source File: AbstractPdfReportBuilder.java    From bdf3 with Apache License 2.0 6 votes vote down vote up
private void createGridColumnHeader(PdfPTable table, Collection<ColumnHeader> topHeaders, int maxHeaderLevel) throws Exception {
	for (int i = 1; i < 50; i++) {
		List<ColumnHeader> result = new ArrayList<ColumnHeader>();
		generateGridHeadersByLevel(topHeaders, i, result);
		for (ColumnHeader header : result) {
			PdfPCell cell = new PdfPCell(createParagraph(header));
			if (header.getBgColor() != null) {
				int[] colors = header.getBgColor();
				cell.setBackgroundColor(new BaseColor(colors[0], colors[1], colors[2]));
			}
			cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
			cell.setHorizontalAlignment(header.getAlign());
			cell.setColspan(header.getColspan());
			if (header.getColumnHeaders().size() == 0) {
				int rowspan = maxHeaderLevel - (header.getLevel() - 1);
				if (rowspan > 0) {
					cell.setRowspan(rowspan);
				}
			}
			table.addCell(cell);
		}
	}
}
 
Example #13
Source File: PdfTableExcel.java    From excel2pdf with Apache License 2.0 6 votes vote down vote up
protected void addImageByPOICell(PdfPCell pdfpCell , Cell cell , float cellWidth) throws BadElementException, MalformedURLException, IOException{
        POIImage poiImage = new POIImage().getCellImage(cell);
        byte[] bytes = poiImage.getBytes();
        if(bytes != null){
//           double cw = cellWidth;
//           double ch = pdfpCell.getFixedHeight();
//
//           double iw = poiImage.getDimension().getWidth();
//           double ih = poiImage.getDimension().getHeight();
//
//           double scale = cw / ch;
//
//           double nw = iw * scale;
//           double nh = ih - (iw - nw);
//
//           POIUtil.scale(bytes , nw  , nh);
            pdfpCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            pdfpCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            Image image = Image.getInstance(bytes);
            pdfpCell.setImage(image);
        }
    }
 
Example #14
Source File: UseRowspan.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/44005834/changing-rowspans">
 * Changing rowspans
 * </a>
 * <p>
 * Helper method of the OP.
 * </p>
 * @see #testUseRowspanLikeUser7968180()
 * @see #testUseRowspanLikeUser7968180Fixed()
 * @see #createPdf(String)
 * @see #createPdfFixed(String)
 */
private static void addCellToTableCzech(PdfPTable table, int horizontalAlignment,
        int verticalAlignment, String value, int colspan, int rowspan,
        String fontType, float fontSize) {
    BaseFont base = null;
    try {
        base = BaseFont.createFont(fontType, BaseFont.CP1250, BaseFont.EMBEDDED);
    } catch (Exception e) {
        e.printStackTrace();
    }
    Font font = new Font(base, fontSize);
    PdfPCell cell = new PdfPCell(new Phrase(value, font));
    cell.setColspan(colspan);
    cell.setRowspan(rowspan);
    cell.setHorizontalAlignment(horizontalAlignment);
    cell.setVerticalAlignment(verticalAlignment);
    cell.setBorder(PdfPCell.NO_BORDER);
    table.addCell(cell);
}
 
Example #15
Source File: AddField.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
public void cellLayout(PdfPCell cell, Rectangle position,
                               PdfContentByte[] canvases) {
            PdfWriter writer = canvases[0].getPdfWriter();
            float x = position.getLeft();
            float y = position.getBottom();
            Rectangle rect = new Rectangle(x-5, y-5, x+5, y+5);
            RadioCheckField checkbox = new RadioCheckField(
                    writer, rect, name, "Yes");
            checkbox.setCheckType(RadioCheckField.TYPE_CROSS);
            checkbox.setChecked(check);
// change: set border color
            checkbox.setBorderColor(BaseColor.BLACK);

            try {
                pdfStamper.addAnnotation(checkbox.getCheckField(), page);
            } catch (Exception e) {
                throw new ExceptionConverter(e);
            }
        }
 
Example #16
Source File: PdfExportDialogFragment.java    From geopaparazzi with GNU General Public License v3.0 5 votes vote down vote up
private void addKeyValueToTableRow(PdfPTable table, String key, String value) {
    PdfPCell keyCell = new PdfPCell(new Paragraph(key));
    keyCell.setHorizontalAlignment(Element.ALIGN_CENTER);
    keyCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    keyCell.setPadding(10);
    table.addCell(keyCell);

    PdfPCell valueCell = new PdfPCell(new Phrase(value));
    valueCell.setHorizontalAlignment(Element.ALIGN_CENTER);
    valueCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
    valueCell.setPadding(10);
    table.addCell(valueCell);
}
 
Example #17
Source File: PdfTableExcel.java    From excel2pdf with Apache License 2.0 5 votes vote down vote up
protected void addBorderByExcel(PdfPCell cell , CellStyle style) {
    Workbook wb = excel.getWorkbook();
    cell.setBorderColorLeft(new BaseColor(POIUtil.getBorderRBG(wb,style.getLeftBorderColor())));
    cell.setBorderColorRight(new BaseColor(POIUtil.getBorderRBG(wb,style.getRightBorderColor())));
    cell.setBorderColorTop(new BaseColor(POIUtil.getBorderRBG(wb,style.getTopBorderColor())));
    cell.setBorderColorBottom(new BaseColor(POIUtil.getBorderRBG(wb,style.getBottomBorderColor())));
}
 
Example #18
Source File: PdfReportPageNumber.java    From bdf3 with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a header to every page
 * @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(
 *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document)
 */
public void onEndPage(PdfWriter writer, Document document) {
	PdfPTable table = new PdfPTable(3);
	try {
		table.setWidths(new int[]{40,5,10});
		table.setTotalWidth(100);
		table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
		table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
		Font font=new Font(chineseFont,8);
		font.setColor(new BaseColor(55,55,55));
		Paragraph paragraph=new Paragraph("第   "+writer.getPageNumber()+" 页   共",font);
		paragraph.setAlignment(Element.ALIGN_RIGHT);
		table.addCell(paragraph);
		Image img=Image.getInstance(total);
		img.scaleAbsolute(28, 28);
		PdfPCell cell = new PdfPCell(img);
		cell.setBorder(Rectangle.NO_BORDER);
		cell.setHorizontalAlignment(Element.ALIGN_CENTER);
		table.addCell(cell);
		PdfPCell c = new PdfPCell(new Paragraph("页",font));
		c.setHorizontalAlignment(Element.ALIGN_LEFT);
		c.setBorder(Rectangle.NO_BORDER);
		table.addCell(c);
		float center=(document.getPageSize().getWidth())/2-120/2;
		table.writeSelectedRows(0, -1,center,30, writer.getDirectContent());
	}
	catch(DocumentException de) {
		throw new ExceptionConverter(de);
	}
}
 
Example #19
Source File: JFreeChartTest.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void writeChartToPDF(JFreeChart chart, int width, int height, String fileName)
{
    PdfWriter writer = null;
    Document document = new Document();

    try
    {
        writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
        document.open();
        PdfContentByte pdfContentByte = writer.getDirectContent();
        PdfTemplate pdfTemplateChartHolder = pdfContentByte.createTemplate(50, 50);
        Graphics2D graphics2d = new PdfGraphics2D(pdfTemplateChartHolder, 50, 50);
        Rectangle2D chartRegion = new Rectangle2D.Double(0, 0, 50, 50);
        chart.draw(graphics2d, chartRegion);
        graphics2d.dispose();

        Image chartImage = Image.getInstance(pdfTemplateChartHolder);
        document.add(chartImage);

        PdfPTable table = new PdfPTable(5);
        // the cell object
        // we add a cell with colspan 3

        PdfPCell cellX = new PdfPCell(new Phrase("A"));
        cellX.setBorder(com.itextpdf.text.Rectangle.NO_BORDER);
        cellX.setRowspan(6);
        table.addCell(cellX);

        PdfPCell cellA = new PdfPCell(new Phrase("A"));
        cellA.setBorder(com.itextpdf.text.Rectangle.NO_BORDER);
        cellA.setColspan(4);
        table.addCell(cellA);

        PdfPCell cellB = new PdfPCell(new Phrase("B"));
        table.addCell(cellB);
        PdfPCell cellC = new PdfPCell(new Phrase("C"));
        table.addCell(cellC);
        PdfPCell cellD = new PdfPCell(new Phrase("D"));
        table.addCell(cellD);
        PdfPCell cellE = new PdfPCell(new Phrase("E"));
        table.addCell(cellE);
        PdfPCell cellF = new PdfPCell(new Phrase("F"));
        table.addCell(cellF);
        PdfPCell cellG = new PdfPCell(new Phrase("G"));
        table.addCell(cellG);
        PdfPCell cellH = new PdfPCell(new Phrase("H"));
        table.addCell(cellH);
        PdfPCell cellI = new PdfPCell(new Phrase("I"));
        table.addCell(cellI);

        PdfPCell cellJ = new PdfPCell(new Phrase("J"));
        cellJ.setColspan(2);
        cellJ.setRowspan(3);
        //instead of
        //  cellJ.setImage(chartImage);
        //the OP now uses
        Chunk chunk = new Chunk(chartImage, 20, -50);
        cellJ.addElement(chunk);
        //presumably with different contents of the other cells at hand
        table.addCell(cellJ);

        PdfPCell cellK = new PdfPCell(new Phrase("K"));
        cellK.setColspan(2);
        table.addCell(cellK);
        PdfPCell cellL = new PdfPCell(new Phrase("L"));
        cellL.setColspan(2);
        table.addCell(cellL);
        PdfPCell cellM = new PdfPCell(new Phrase("M"));
        cellM.setColspan(2);
        table.addCell(cellM);

        document.add(table);

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    document.close();
}
 
Example #20
Source File: PdfTable.java    From smartcoins-wallet with MIT License 5 votes vote down vote up
PdfPTable addforCell(String subject, String detail) {
    PdfPTable table = new PdfPTable(2); // 2 columns.
    PdfPCell cell1 = new PdfPCell(new Paragraph(subject));
    PdfPCell cell2 = new PdfPCell(new Paragraph(detail));
    table.addCell(cell1);
    table.addCell(cell2);
    table.completeRow();
    return table;
}
 
Example #21
Source File: TableWithSpan.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
PdfPCell getPiccell(int w, int h)
{
    try
    {
        Image image = Image.getInstance("src/test/resources/mkl/testarea/itext5/content/2x2colored.png");
        image.scaleAbsolute(w, h);
        return new PdfPCell(image);
    }
    catch (BadElementException | IOException e)
    {
        throw new RuntimeException(e);
    }
}
 
Example #22
Source File: PDFSampleMain.java    From tutorials with MIT License 5 votes vote down vote up
private static void addTableHeader(PdfPTable table) {
    Stream.of("column header 1", "column header 2", "column header 3")
    .forEach(columnTitle -> {
        PdfPCell header = new PdfPCell();
        header.setBackgroundColor(BaseColor.LIGHT_GRAY);
        header.setBorderWidth(2);
        header.setPhrase(new Phrase(columnTitle));
        table.addCell(header);
    });
}
 
Example #23
Source File: PDFWriter.java    From Colocalisation_Analysis with GNU General Public License v3.0 5 votes vote down vote up
private void cellStyle(PdfPCell cell) {
	//alignment
	cell.setHorizontalAlignment(Element.ALIGN_CENTER);
	cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
	
	//padding
	cell.setPaddingTop(2f);
			
	//border
	cell.setBorder(0);
	cell.setBorderColor(BaseColor.WHITE);
	
}
 
Example #24
Source File: ThemeImpl.java    From ganttproject with GNU General Public License v3.0 5 votes vote down vote up
private void addEmptyRow(PdfPTable table, float height) {
  PdfPCell emptyCell = new PdfPCell(new Paragraph("  ", getSansRegular(height)));
  emptyCell.setBorderWidth(0);
  for (int i = 0; i < table.getNumberOfColumns(); i++) {
    table.addCell(emptyCell);
  }
}
 
Example #25
Source File: AddField.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
public void cellLayout(PdfPCell cell, Rectangle rectangle, PdfContentByte[] canvases) {
            final PdfWriter writer = canvases[0].getPdfWriter();
            final TextField textField = new TextField(writer, rectangle, fieldname);
// change: set border color
            textField.setBorderColor(BaseColor.BLACK);
            try {
                final PdfFormField field = textField.getTextField();
                pdfStamper.addAnnotation(field, page);
            } catch (final IOException ioe) {
                throw new ExceptionConverter(ioe);
            } catch (final DocumentException de) {
                throw new ExceptionConverter(de);
            }
        }
 
Example #26
Source File: KpiReportPdfCommand.java    From bamboobsc with Apache License 2.0 4 votes vote down vote up
private void setCellBackgroundColor(PdfPCell cell, String color) throws Exception {
	int rgb[] = SimpleUtils.getColorRGB2(color);
	cell.setBackgroundColor(new BaseColor(rgb[0], rgb[1], rgb[2]));
}
 
Example #27
Source File: Helper.java    From mobikul-standalone-pos with MIT License 4 votes vote down vote up
PdfPCell getPdfCell(Paragraph elements) {
    PdfPCell pCell = new PdfPCell();
    pCell.setPadding(5);
    pCell.addElement(elements);
    return pCell;
}
 
Example #28
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 #29
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;
}
 
Example #30
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());
    }

}