add border to pdf page using itext - java

this is my source code. why am I not able to add border to my pdf page even after enabling borders for all sides? I've set border and its color too still I'm not able to add border.
void create() throws DocumentException,IOException{
// step 1
Document document = new Document();
// step 2
PdfWriter writer=PdfWriter.getInstance(document, new FileOutputStream(RESULT));
document.setPageSize(PageSize.LETTER);
document.setMargins(36, 72, 108, 180);
document.setMarginMirroring(false);
// step 3
document.open();
// step 4
Rectangle rect= new Rectangle(36,108);
rect.enableBorderSide(1);
rect.enableBorderSide(2);
rect.enableBorderSide(4);
rect.enableBorderSide(8);
rect.setBorder(2);
rect.setBorderColor(BaseColor.BLACK);
document.add(rect);
Font font = new Font(Font.FontFamily.TIMES_ROMAN, 26, Font.UNDERLINE, BaseColor.BLACK);
Paragraph title= new Paragraph("CURRICULUM VITAE\n\n",font);
title.setAlignment(Element.ALIGN_CENTER);
document.add(title);
Font f1= new Font (Font.FontFamily.UNDEFINED, 13, Font.NORMAL, BaseColor.BLACK);
Paragraph info= new Paragraph("Name\n\nEmail\n\nContact Number",f1);
Paragraph addr= new Paragraph("Street\n\nCity\n\nPin",f1);
PdfPTable table = new PdfPTable(2);
table.setWidthPercentage(100);
table.spacingAfter();
PdfPCell cell = new PdfPCell(info);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.disableBorderSide(Rectangle.BOX);
cell.setExtraParagraphSpace(1.5f);
table.addCell(cell);
cell = new PdfPCell(addr);
cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
cell.disableBorderSide(Rectangle.BOX);
cell.setExtraParagraphSpace(1.5f);
table.addCell(cell);
document.add(table);
document.add(new Chunk("\n"));
document.add(new LineSeparator(2f,100,BaseColor.DARK_GRAY,Element.ALIGN_CENTER,-1f));

You didn't define a border width.
You're adding the border only once. What if you want the border to appear on every page?
You can fix (1.) by adding:
rect.setBorder(Rectangle.BOX);
rect.setBorderWidth(2);
Note that I would remove the enableBorderSide() calls. You'll notice that you've used the setBorder() method in the wrong way.
To fix (2.), I would use a page event. Note that you can't use document.add() in a page event, so you'll have to do something as described in the DrawRectangle example that was written in answer to the question iText: PdfContentByte.rectangle(Rectangle) does not behave as expected
You didn't define a page size when creating the Document object, which means that iText will be using PageSize.A4. A couple of lines later, you use PageSize.LETTER. These values are immutable Rectangle objects. You can create a new Rectangle using the dimensions/coordinates of PageSize.A4 (or in your case: PageSize.LETTER). You can obtain the dimensions using the getWidth() and getHeight() method and the coordinates using getLeft(), getBottom(), getRight() and getTop().

Rectangle rect= new Rectangle(577,825,18,15); // you can resize rectangle
rect.enableBorderSide(1);
rect.enableBorderSide(2);
rect.enableBorderSide(4);
rect.enableBorderSide(8);
rect.setBorderColor(BaseColor.BLACK);
rect.setBorderWidth(1);
document.add(rect);

Related

Cannot get footer table to be entire width of PDF in iText Java

I am using iText PDF version 5 in Java. I have a table at the bottom of my page that I need to be the entire width of the page up to the margins of the page. Here is my document code with my margins:
Document document = new Document(PageSize.LETTER, 40, 40, 36, 40);
I have other tables on the top and the middle of the page:
PdfPTable headerTable = new PdfPTable(2);
headerTable.setWidthPercentage(100);
headerTable.addCell("Welcome");
headerTable.addCell("Contact Us");
document.add(headerTable);
PdfPTable itemTable = new PdfPTable(3);
itemTable.setWidthPercentage(100);
itemTable.addCell("item name: coding shirt");
itemTable.addCell("item size: medium");
itemTable.addCell("item cost: $10.00");
document.add(itemTable);
I have a table that I am displaying at the bottom of the page:
PdfPTable grandFooterTable = new PdfPTable(1);
grandFooterTable.addCell("Some information here");
grandFooterTable.addCell("Some more information as well");
grandFooterTable.setTotalWidth(document.right(document.rightMargin()) - document.left(document.leftMargin()));
grandFooterTable.setWidthPercentage(100);
grandFooterTable.writeSelectedRows(
0,
-1,
document.left(document.leftMargin()),
grandFooterTable.getTotalHeight() + document.bottom(document.bottomMargin()),
writer.getDirectContent()
);
For some reason this table is not the entire width of the page up to the margins. It is not as wide as the other tables above it.
I've tried:
removing/commenting out grandFooterTable.setWidthPercentage(100);
changing setTotalWidth() to grandFooterTable.setTotalWidth(100);
(I know that is not a percentage parameter but I tried anyway)
moving grandFooterTable.setWidthPercentage(100); to different places:
before setTotalWidth, after writeSelectedRows
None of the above works. How can I get the footer table to be as wide as the other tables on my page, so that the width hits the margins?
You really should try iText7.
The width is set via setWidth(UnitValue.createPercentValue(100)). So, the table will take up the entire possible width. And using setFixedPosition(), it can be placed at the bottom
PdfDocument pdfDocument = new PdfDocument(new PdfWriter("file.pdf"));
Document document = new Document(pdfDocument, PageSize.LETTER);
document.setMargins(40, 40, 36, 40);
Table headerTable = new Table(2);
headerTable.setWidth(UnitValue.createPercentValue(100));
headerTable.addCell("Welcome");
headerTable.addCell("Contact Us");
document.add(headerTable);
Table itemTable = new Table(3);
itemTable.setWidth(UnitValue.createPercentValue(100));
itemTable.addCell("item name: coding shirt");
itemTable.addCell("item size: medium");
itemTable.addCell("item cost: $10.00");
document.add(itemTable);
Table grandFooterTable = new Table(1);
grandFooterTable.addCell("Some information here");
grandFooterTable.addCell("Some more information as well");
grandFooterTable.setWidth(UnitValue.createPercentValue(100));
PageSize ps = pdfDocument.getDefaultPageSize();
grandFooterTable.setFixedPosition(document.getLeftMargin(), document.getBottomMargin(),
ps.getWidth() - document.getLeftMargin() - document.getRightMargin());
document.add(grandFooterTable);
document.close();

How can I Align/ Arrange text fields into two column layout using Apache PDFBox - java

I am using Apache PDFBox(version : 2.0.8) to generate a PDF document from my .jspx page.
In my .jspx page form, there are many fields, so i decided to arrange all the fields as 2 column layout. So, I need suggestion to achieve the layout using PDFbox.
// Sample Code snippet I have used to generate PDF is as below.
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
PDFont font = getFontDef();
PDPageContentStream contentStream =new PDPageContentStream(document, page);
contentStream.beginText();
contentStream.showText("Name: " );
contentStream.setFont(getFontDef().COURIER ,15);
contentStream.showText ("Rajeev");
contentStream.showText("Address: " +"BNG");
contentStream.newLine();
contentStream.showText("State: " +"KAR");
contentStream.showText("Country: " +"INDIA");
contentStream.endText();
contentStream.close();
I need to show label(i.e. Name, Address,State and Country) in bold font and Value(i.e. Rajeev, BNG,KAR,IND respectively) as normal font.
To get bold font for the label, I have tried as shown below
contentStream.setFont(getFontDef().COURIER ,15);
and it is working , but I have to add the above line before each label field. is there any better approaches I can use to set bold font for all the labels?
I am also facing some issue in aligning these form fields into two column layout. Ex
Name: Rajeev      Address: BNG
State: KAR      Country: IND
i.e. Name and Address in first line and Name should be in first column and Address should be in second column. Similarly, State and country in second line and State in first column and country is in second column.
To arrange text in columns, you can use the newLineAtOffset to move horizontally, not or at least not only vertically.
To switch back and forth between bold and normal type faces, you usually do indeed have to set and reset the font again and again. Alternatively you could first draw all bold text and then all normal text (or the other way around), but then you'd have to use more newLineAtOffset calls to jump around. Furthermore, some PDF viewers might follow your jumps when you try to select and copy text.
PDFont fontNormal = PDType1Font.HELVETICA;
PDFont fontBold = PDType1Font.HELVETICA_BOLD;
PDPageContentStream contentStream =new PDPageContentStream(document, page);
contentStream.beginText();
contentStream.newLineAtOffset(100, 600);
contentStream.setFont(fontBold, 15);
contentStream.showText("Name: ");
contentStream.setFont(fontNormal, 15);
contentStream.showText ("Rajeev");
contentStream.newLineAtOffset(200, 00);
contentStream.setFont(fontBold, 15);
contentStream.showText("Address: " );
contentStream.setFont(fontNormal, 15);
contentStream.showText ("BNG");
contentStream.newLineAtOffset(-200, -20);
contentStream.setFont(fontBold, 15);
contentStream.showText("State: " );
contentStream.setFont(fontNormal, 15);
contentStream.showText ("KAR");
contentStream.newLineAtOffset(200, 00);
contentStream.setFont(fontBold, 15);
contentStream.showText("Country: " );
contentStream.setFont(fontNormal, 15);
contentStream.showText ("INDIA");
contentStream.endText();
contentStream.close();
(ArrangeText test testArrangeTextForUser2967784)
I don't know what your method getFontDef() returns, so I chose fixed fonts for bold and normal text here.
The result:

Need to make PDF sample with boxes as table columns by android app

I need to make PDF sample file just like the below image but I didn't find any suitable guide to do exactly like this. I have followed some links
http://itextpdf.com/examples/iia.php?id=102
Is there a way to draw a rectangle into a PdfPCell in iText (the Java version)?
but from the second link I didn't understand how could I make more likely to my requirement.
Thanks in advance.
It is unclear to me why you refer to this example: http://itextpdf.com/examples/iia.php?id=102
The PDF that is created with that example shows me in a Superman outfit. What is the link with creating a table with rounded borders?
Please take a look at the NestedTableRoundedBorder example. It creates a PDF that looks like this: nested_table_rounded_border.pdf
This construction consists of nested tables. The outer table only has one column, but we use it to create the rounded corners:
class RoundRectangle implements PdfPCellEvent {
public void cellLayout(PdfPCell cell, Rectangle rect,
PdfContentByte[] canvas) {
PdfContentByte cb = canvas[PdfPTable.LINECANVAS];
cb.roundRectangle(
rect.getLeft() + 1.5f, rect.getBottom() + 1.5f, rect.getWidth() - 3,
rect.getHeight() - 3, 4);
cb.stroke();
}
}
This cell event is used like this:
cell = new PdfPCell(innertable);
cell.setCellEvent(roundRectangle);
cell.setBorder(Rectangle.NO_BORDER);
cell.setPadding(8);
outertable.addCell(cell);
The inner tables are used to create cells with or without borders, for instance like this:
// inner table 1
PdfPTable innertable = new PdfPTable(5);
innertable.setWidths(new int[]{8, 12, 1, 4, 12});
// first row
// column 1
cell = new PdfPCell(new Phrase("Record Ref:"));
cell.setBorder(Rectangle.NO_BORDER);
innertable.addCell(cell);
// column 2
cell = new PdfPCell(new Phrase("GN Staff"));
cell.setPaddingLeft(2);
innertable.addCell(cell);
// column 3
cell = new PdfPCell();
cell.setBorder(Rectangle.NO_BORDER);
innertable.addCell(cell);
// column 4
cell = new PdfPCell(new Phrase("Date: "));
cell.setBorder(Rectangle.NO_BORDER);
innertable.addCell(cell);
// column 5
cell = new PdfPCell(new Phrase("30/4/2015"));
cell.setPaddingLeft(2);
innertable.addCell(cell);
// spacing
cell = new PdfPCell();
cell.setColspan(5);
cell.setFixedHeight(3);
cell.setBorder(Rectangle.NO_BORDER);
innertable.addCell(cell);
If some of the dimensions are quite like you want, it's sufficient to change parameters such as the widths array, the padding, the fixed height, etc.

PDF Cell Vertical Alignment with com.lowagie.text

I am using com.lowagie.text to create PDF in my code. All is working fine except I am trying to align my cell content vertically. I want cell text to be in the middle of the cell height.
This is my code
PdfPCell cell = new PdfPCell(new Phrase(value, fontValueNew));
cell.setBorder(o);
cell.setBackgroundColor(new Color(233,232,232));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
Here ,horizontal alignment is working fine but vertical alignment is not effective.
I'm not too sure as to why, but this works for me (vertical center alignment):
String headingLabel = "Test";
Paragraph heading = new Paragraph(headingLabel,
new Font(helvetica, 28, Font.NORMAL, new BaseColor(0, 0, 0)));
Float textWidth = ColumnText.getWidth(heading);
Float maxAllowed = 630f;
while (maxAllowed < textWidth) {
fontSize -= 2;
heading = new Paragraph(headingLabel,
new Font(helvetica, fontSize, Font.NORMAL, new BaseColor(0, 0, 0)));
textWidth = ColumnText.getWidth(heading);
}
heading.setAlignment(Element.ALIGN_CENTER);
PdfPCell titleCell = new PdfPCell();
titleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
titleCell.setVerticalAlignment(Element.ALIGN_TOP);
titleCell.addElement(heading);
titleCell.setFixedHeight(65f);
headerTable.addCell(titleCell);
ALIGN_MIDDLE has integer value 5 defined in the the iText code. Please pay attention while you are writing ALIGN_MIDDLE a tip comes up "Possible value for vertical element." It means if your element is in vertical orientation then it will work as it calculates the center of the element. My suggestion is to replace ALIGN_MIDDLE with ALIGN_CENTER so your code will look like:
cell.setVerticalAlignment(Element.ALIGN_CENTER);
Try this:
PdfPCell cell = new PdfPCell(new Phrase(value, fontValueNew));
cell.setBorder(o);
cell.setBackgroundColor(new Color(233,232,232));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_CENTER);

iText - PdfPTable RowSpan using mytable.writeSelectedRows

I'm using iText 5.1.3, and I want to add a header to my Pdf Document. I used the known solution posted here: http://itextpdf.com/examples/iia.php?id=104
This solution used the PdfPageEventHelper class, and overridden the method onEndPage() to add the Header exactly after finishing every page. The example provided in the link above works fine as it adds a table as the Header of the document. I'm trying to do exactly the same with 1 difference, that I want some cells in that table to have Rowspan and/or Colspan.
I tried, and found that using table.writeSelectedRows() differs from document.add(table) when it comes to Rowspan. This is a sample of what I'm trying to do in onEndPage:
PdfPTable mytable = new PdfPTable(3);
mytable.setTotalWidth(527);
PdfPCell cell1 = new PdfPCell(new Phrase("Hello"));
cell1.setColspan(2);
cell1.setRowspan(2);
mytable.addCell(cell1);
PdfPCell cell2 = new PdfPCell(new Phrase("Girls !"));
mytable.addCell(cell2);
PdfPCell cell3 = new PdfPCell(new Phrase("Boys !"));
mytable.addCell(cell3);
mytable.writeSelectedRows(0, -1, 34, 803, writer.getDirectContent());
and instead of having a cell at the left as 2x2 with "Hello", I get the "Hello" cell as 1x2 not 2x2
Any ideas?
well .. I found the solution myself :D It's simply replacing mytable.writeSelectedRows(0, -1, 34, 803, writer.getDirectContent()); with the following:
ColumnText column = new ColumnText(writer.getDirectContent());
column.addElement(mytable);
column.setSimpleColumn(-12, -20, 604, 803); // set LLx, LLy, URx, and URy of the header
column.go();
That's it :) worked :)
iText writeSelectedRows not work with rowSpan when I use iText-2.1.7, The rowSpan cell not grow to other rows,But it has a workaround.
ArrayList tmp = table.getRows(0, table.getRows().size());
table.getRows().clear();
table.getRows().addAll(tmp);
table.writeSelectedRows(0, -1, x, y, directContent);

Categories