To create PDF file we need iText 5 jar. Download iText Jars from iText Website or Maven Repository
RectangleInCell.java
Output
Reference : iText Website
Maven Dependency
2.
<
dependency
>
3.
<
groupid
>com.itextpdf</
groupid
>
4.
<
artifactid
>itextpdf</
artifactid
>
5.
<
version
>5.5.11</
version
>
6.
</
dependency
>
RectangleInCell.java
01.
package
com.javatutorialcorner.itextpdf;
02.
03.
import
com.itextpdf.text.BaseColor;
04.
import
com.itextpdf.text.Document;
05.
import
com.itextpdf.text.DocumentException;
06.
import
com.itextpdf.text.Image;
07.
import
com.itextpdf.text.Paragraph;
08.
import
com.itextpdf.text.pdf.PdfContentByte;
09.
import
com.itextpdf.text.pdf.PdfPCell;
10.
import
com.itextpdf.text.pdf.PdfPTable;
11.
import
com.itextpdf.text.pdf.PdfTemplate;
12.
import
com.itextpdf.text.pdf.PdfWriter;
13.
14.
15.
import
java.io.File;
16.
import
java.io.FileOutputStream;
17.
import
java.io.IOException;
18.
19.
public
class
RectangleInCell {
20.
21.
public
static
final
String DEST =
"C:/JTC/RectangleInCell.pdf"
;
22.
23.
public
static
void
main(String[] args)
throws
IOException,
24.
DocumentException {
25.
File file =
new
File(DEST);
26.
file.getParentFile().mkdirs();
27.
new
RectangleInCell().createPdf(DEST);
28.
}
29.
30.
public
void
createPdf(String dest)
throws
IOException, DocumentException {
31.
Document document =
new
Document();
32.
PdfWriter writer = PdfWriter.getInstance(document,
new
FileOutputStream(dest));
33.
document.open();
34.
document.add(
new
Paragraph(
"Option 1:"
));
35.
PdfPTable table =
new
PdfPTable(
3
);
36.
table.addCell(
"A rectangle:"
);
37.
PdfTemplate template = writer.getDirectContent().createTemplate(
120
,
80
);
38.
template.setColorFill(BaseColor.RED);
39.
template.rectangle(
0
,
0
,
120
,
80
);
40.
template.fill();
41.
writer.releaseTemplate(template);
42.
table.addCell(Image.getInstance(template));
43.
table.addCell(
"The rectangle is scaled to fit inside the cell, you see a padding."
);
44.
document.add(table);
45.
document.add(
new
Paragraph(
"Option 2:"
));
46.
table =
new
PdfPTable(
3
);
47.
table.addCell(
"A rectangle:"
);
48.
PdfPCell cell =
new
PdfPCell(Image.getInstance(template));
49.
table.addCell(cell);
50.
table.addCell(
"The rectangle keeps its original size, but can overlap other cells in the same row."
);
51.
document.add(table);
52.
document.add(
new
Paragraph(
"Option 3:"
));
53.
table =
new
PdfPTable(
3
);
54.
table.addCell(
"A rectangle:"
);
55.
cell =
new
PdfPCell(Image.getInstance(template),
true
);
56.
table.addCell(cell);
57.
table.addCell(
"The rectangle is scaled to fit inside the cell, no padding."
);
58.
document.add(table);
59.
PdfContentByte cb = writer.getDirectContent();
60.
cb.moveTo(
228
,
810
);
61.
cb.lineTo(
338
,
810
);
62.
cb.stroke();
63.
document.close();
64.
}
65.
}
Output
Reference : iText Website
0 comments:
Post a Comment