com.itextpdf.text.pdf.PdfPTable Java Examples

The following examples show how to use com.itextpdf.text.pdf.PdfPTable. 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: PDFExport.java    From MtgDesktopCompanion with GNU General Public License v3.0 8 votes vote down vote up
@Override
public void exportDeck(MagicDeck deck, File f) throws IOException {
	PdfPTable table = new PdfPTable(3);
	table.setHorizontalAlignment(Element.ALIGN_CENTER);

	try {
		document = new Document(PageSize.A4, 5, 5, 10, 5);
		document.addAuthor(getString("AUTHOR"));
		document.addCreationDate();
		document.addCreator(MTGConstants.MTG_APP_NAME);
		document.addTitle(deck.getName());

		PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(f));
		document.open();
		document.add(new Chunk(""));
		for (MagicCard card : deck.getMainAsList()) {
			table.addCell(getCells(card));
			notify(card);
		}
		document.add(table);
		document.close();
		writer.close();
	} catch (Exception e) {
		logger.error("Error in pdf creation " + f, e);
	}
}
 
Example #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
Source File: DoubleSpace.java    From testarea-itext5 with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/35699167/double-space-not-being-preserved-in-pdf">
 * Double space not being preserved in PDF
 * </a>
 * <p>
 * Indeed, the double space collapses into a single one when copying&pasting from the
 * generated PDF displayed in Adobe Reader. On the other hand the gap for the double
 * space is twice as wide as for the single space. So this essentially is a quirk of
 * copy&paste of Adobe Reader (and some other PDF viewers, too).
 * </p>
 */
@Test
public void testDoubleSpace() throws DocumentException, IOException
{
    try (   OutputStream pdfStream = new FileOutputStream(new File(RESULT_FOLDER, "DoubleSpace.pdf")))
    {
        PdfPTable table = new PdfPTable(1);
        table.getDefaultCell().setBorderWidth(0.5f);
        table.getDefaultCell().setBorderColor(BaseColor.LIGHT_GRAY);

        table.addCell(new Phrase("SINGLE SPACED", new Font(BaseFont.createFont(), 36)));
        table.addCell(new Phrase("DOUBLE  SPACED", new Font(BaseFont.createFont(), 36)));
        table.addCell(new Phrase("TRIPLE   SPACED", new Font(BaseFont.createFont(), 36)));

        Document pdfDocument = new Document(PageSize.A4.rotate(), 0, 0, 0, 0);
        PdfWriter.getInstance(pdfDocument, pdfStream);
        pdfDocument.open();
        pdfDocument.add(table);
        pdfDocument.close();
    }
}
 
Example #14
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 #15
Source File: PDFSampleMain.java    From tutorials with MIT License 6 votes vote down vote up
public static void main(String[] args) {
    
    try {
        
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream("iTextTable.pdf"));

        document.open();

        PdfPTable table = new PdfPTable(3);
        addTableHeader(table);
        addRows(table);
        addCustomRows(table);

        document.add(table);
        document.close();
        
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #16
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 #17
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 #18
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 #19
Source File: ThemeImpl.java    From ganttproject with GNU General Public License v3.0 5 votes vote down vote up
private void writeColontitle(String topLeft, String topRight, String bottomLeft, String bottomRight) {
  final Document document = myDoc;
  final PdfWriter writer = myWriter;
  Rectangle page = document.getPageSize();
  PdfPTable colontitleTable = createColontitleTable(topLeft, topRight, bottomLeft, bottomRight);
  colontitleTable.writeSelectedRows(0, -1, document.leftMargin(), page.getHeight() - document.topMargin()
      + colontitleTable.getTotalHeight(), writer.getDirectContent());

}
 
Example #20
Source File: PdfExportGenerator.java    From axelor-open-suite with GNU Affero General Public License v3.0 5 votes vote down vote up
public PdfExportGenerator(AdvancedExport advancedExport) throws AxelorException {
  this.advancedExport = advancedExport;
  exportFileName = advancedExport.getMetaModel().getName() + ".pdf";
  document = new Document();
  table = new PdfPTable(advancedExport.getAdvancedExportLineList().size());
  try {
    exportFile = File.createTempFile(advancedExport.getMetaModel().getName(), ".pdf");
    FileOutputStream outStream = new FileOutputStream(exportFile);
    PdfWriter.getInstance(document, outStream);
  } catch (IOException | DocumentException e) {
    TraceBackService.trace(e);
    throw new AxelorException(e, TraceBackRepository.CATEGORY_CONFIGURATION_ERROR);
  }
  document.open();
}
 
Example #21
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 #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: CellBorderEvent.java    From ureport with Apache License 2.0 5 votes vote down vote up
private PdfContentByte bulidCellBorder(PdfContentByte[] canvases,Border border){
	PdfContentByte cb=canvases[PdfPTable.LINECANVAS];
	cb.saveState();
	BigDecimal w=new BigDecimal(border.getWidth());
	cb.setLineWidth(w.divide(new BigDecimal(2),10,RoundingMode.HALF_UP).floatValue());
	if(border.getStyle().equals(BorderStyle.dashed)){
		cb.setLineDash(new float[]{2f,3f,1f},2);
	}
	String borderColor[]=border.getColor().split(",");
	cb.setColorStroke(new BaseColor(Integer.valueOf(borderColor[0]),Integer.valueOf(borderColor[1]),Integer.valueOf(borderColor[2])));
	return cb;
}
 
Example #24
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 #25
Source File: TableKeepTogether.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
private void printPage3(Document document, PdfContentByte canvas) throws DocumentException {
    int cols = 3;
    int rows = 15;

    PdfPTable table = new PdfPTable(cols);
    for (int row = 0; row < rows; row++) {
        for (int col = 0; col < cols; col++) {
            table.addCell(new Phrase("Cell " + row + ", " + col));
        }
    }
    table.setSpacingBefore(5);

    Rectangle docBounds = document.getPageSize();
    Rectangle upper = new Rectangle(docBounds.getLeft(20), docBounds.getTop(20) - 200, docBounds.getRight(20), docBounds.getTop(20));
    upper.setBackgroundColor(new BaseColor(23, 142, 255, 20));
    Rectangle lower = new Rectangle(docBounds.getLeft(20), docBounds.getBottom(20), docBounds.getRight(20), docBounds.getBottom(20) + 600);
    lower.setBackgroundColor(new BaseColor(255, 142, 23, 20));
    Rectangle[] rectangles = new Rectangle[] { upper, lower };

    for (Rectangle bounds : rectangles)
    {
        bounds.setBorder(Rectangle.BOX);
        bounds.setBorderColor(BaseColor.BLACK);
        bounds.setBorderWidth(1);

        canvas.rectangle(bounds);
    }

    rectangles = drawKeepTogether(new Paragraph("This table should keep together!"), canvas, rectangles);
    rectangles = drawKeepTogether(table, canvas, rectangles);
}
 
Example #26
Source File: CreateTableDirectContent.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 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>
 * Indeed, there is an error in the official sample which effectively
 * applies the margins twice.
 * </p>
 */
@Test
public void testCreateTableLikeUser7968180() throws FileNotFoundException, DocumentException
{
    Document document = new Document(PageSize.A4);
    PdfWriter writer = PdfWriter.getInstance(document,
            new FileOutputStream(new File(RESULT_FOLDER, "calendarUser7968180.pdf")));
    document.open();

    PdfPTable datatable = null;//createHeaderTable();
    //document.add(datatable);
    datatable = createFooterTable();

    drawTableAtTheEndOfPage(document, writer, datatable);

    // Marking the border
    PdfContentByte canvas = writer.getDirectContentUnder();
    canvas.setColorStroke(BaseColor.RED);
    canvas.setColorFill(BaseColor.PINK);
    canvas.rectangle(document.left(), document.bottom(), document.right() - document.left(), document.top() - document.bottom());
    Rectangle pageSize = document.getPageSize(); 
    canvas.rectangle(pageSize.getLeft(), pageSize.getBottom(), pageSize.getWidth(), pageSize.getHeight());
    canvas.eoFillStroke();

    document.close();
    System.out.println("done");
}
 
Example #27
Source File: CreateTableDirectContent.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 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()}. Here the error
     * is corrected.
     * </p>
     */
    private static void drawTableAtTheEndOfPage(Document document, PdfWriter writer, PdfPTable datatable)
    {
        datatable.setTotalWidth(document.right() - document.left());
//        datatable.setTotalWidth(document.right(document.rightMargin()) - document.left(document.leftMargin()));

        datatable.writeSelectedRows(0, -1, document.left(),
                datatable.getTotalHeight() + document.bottom(), writer.getDirectContent());
//        datatable.writeSelectedRows(0, -1, document.left(document.leftMargin()),
//                datatable.getTotalHeight() + document.bottom(document.bottomMargin()), writer.getDirectContent());
    }
 
Example #28
Source File: UseRowspan.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/44005834/changing-rowspans">
 * Changing rowspans
 * </a>
 * <p>
 * The original code used by the OP. This code adds the second cell
 * with rowspan 2 too early. Fixed in {@link #createPdfFixed(String)}.
 * </p>
 * @see #testUseRowspanLikeUser7968180()
 * @see #addCellToTableCzech(PdfPTable, int, int, String, int, int, String, float)
 */
public void createPdf(String dest) throws IOException, DocumentException {
    int horizontalAlignmentCenter = Element.ALIGN_CENTER;
    int verticalAlignmentMiddle = Element.ALIGN_MIDDLE;
    String fontTypeRegular = "c:/Windows/Fonts/arial.ttf";
    float fontSizeRegular = 10f;

    float[] columns = { 100, 50, 100, 50, 50, 50, 50, 50, 75, 50, 50, 50 };
    int numberOfColumns = columns.length;
    Document document = new Document(PageSize.A4.rotate(), 36, 36, 36, 36);
    PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();

    PdfPTable subTableZkouska = new PdfPTable(numberOfColumns);
    subTableZkouska.setTotalWidth(columns);
    subTableZkouska.setLockedWidth(true);

    addCellToTableCzech(subTableZkouska, horizontalAlignmentCenter,
            verticalAlignmentMiddle, "Brno �pit�lka 8 Brno H�jeck� 1068/14 CZ5159", 1,
            2, fontTypeRegular, fontSizeRegular);

    addCellToTableCzech(subTableZkouska, horizontalAlignmentCenter,
            verticalAlignmentMiddle, "38", 1, 2, fontTypeRegular, fontSizeRegular);

    for (int i = 0; i < 19; i++) {
        addCellToTableCzech(subTableZkouska, horizontalAlignmentCenter,
                verticalAlignmentMiddle, "38", 1, 1, fontTypeRegular,
                fontSizeRegular);
    }
    addCellToTableCzech(subTableZkouska, horizontalAlignmentCenter,
            verticalAlignmentMiddle, "38", 1, 1, fontTypeRegular, fontSizeRegular);

    document.add(subTableZkouska);
    document.close();
}
 
Example #29
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 #30
Source File: UseRowspan.java    From testarea-itext5 with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * <a href="http://stackoverflow.com/questions/44005834/changing-rowspans">
 * Changing rowspans
 * </a>
 * <p>
 * The fixed code. This code adds the second cell with rowspan 2
 * in twelfth place. Fixed of {@link #createPdf(String)}.
 * </p>
 * @see #testUseRowspanLikeUser7968180Fixed()
 * @see #addCellToTableCzech(PdfPTable, int, int, String, int, int, String, float)
 */
public void createPdfFixed(String dest) throws IOException, DocumentException {
    int horizontalAlignmentCenter = Element.ALIGN_CENTER;
    int verticalAlignmentMiddle = Element.ALIGN_MIDDLE;
    String fontTypeRegular = "c:/Windows/Fonts/arial.ttf";
    float fontSizeRegular = 10f;

    float[] columns = { 100, 50, 100, 50, 50, 50, 50, 50, 75, 50, 50, 50 };
    int numberOfColumns = columns.length;
    Document document = new Document(PageSize.A4.rotate(), 36, 36, 36, 36);
    PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();

    PdfPTable subTableZkouska = new PdfPTable(numberOfColumns);
    subTableZkouska.setTotalWidth(columns);
    subTableZkouska.setLockedWidth(true);

    addCellToTableCzech(subTableZkouska, horizontalAlignmentCenter,
            verticalAlignmentMiddle, "Brno �pit�lka 8 Brno H�jeck� 1068/14 CZ5159", 1,
            2, fontTypeRegular, fontSizeRegular);

    for (int i = 2; i < 12; i++) {
        addCellToTableCzech(subTableZkouska, horizontalAlignmentCenter,
                verticalAlignmentMiddle, "38", 1, 1, fontTypeRegular,
                fontSizeRegular);
    }

    addCellToTableCzech(subTableZkouska, horizontalAlignmentCenter,
            verticalAlignmentMiddle, "38", 1, 2, fontTypeRegular, fontSizeRegular);

    for (int i = 13; i < 23; i++) {
        addCellToTableCzech(subTableZkouska, horizontalAlignmentCenter,
                verticalAlignmentMiddle, "38", 1, 1, fontTypeRegular,
                fontSizeRegular);
    }

    document.add(subTableZkouska);
    document.close();
}