Creating table in pdf using PDFBOX is the hectic work ever.
Because it don’t have any specific procedure to create table. It uses our hand
drawing table model using scale. If I want
to draw table in A4 size paper, first we have to know the width and height of
A4 sheet and then draw lines based on x-axis y-axis mode. Starting x,y values
and ending x,y values are required to draw line.
Below is the sample code for creating table in PDFBOX for
A4size paper
A4 paper width is 595.27563
and height is 841.8898(in PDFBOX terminology)
In the below code first I created horizontal lines(row-
changing y axis value) and then vertical lines(column- changing x axis value) .
And also I attached output pdf table as image here
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
/**
*
* @author Bharathi
Raja
*/
public class CreatePDFBOXTable {
public static void
main(String[] args) {
try {
createTable();
} catch
(Exception e) {
e.printStackTrace();
}
}
public static void
createTable() throws Exception {
String path =
"d:\\tablepdf.pdf"; //location
to store the pdf file
PDDocument
document = new PDDocument();
PDPage page =
new PDPage(PDPage.PAGE_SIZE_A4);
document.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(document,
page);
PDRectangle
mediabox = page.findMediaBox();
float margin =
50;
float startX =
mediabox.getLowerLeftX() + margin;
float startY =
mediabox.getUpperRightY() - margin;
final int rows = 3;
final float
rowHeight = 20f;
final float
tableWidth = page.findMediaBox().getWidth() - (2 * margin);
//draw the
rows
float nexty =
650;
for (int i =
0; i <= rows; i++) {
if (i == 0
|| i == 1) {
contentStream.drawLine(margin, nexty, margin +
tableWidth, nexty);
}
nexty -=
rowHeight;
}
contentStream.drawLine(margin, 300, margin + tableWidth, 300);
int y = 650;
//drawing
columns the columns
float nextx =
50;
int h = 300;
contentStream.drawLine(nextx, y, nextx, h);
nextx = 100;
contentStream.drawLine(nextx, y, nextx, h);
nextx = 350;
contentStream.drawLine(nextx, y, nextx, h);
nextx = 420;
contentStream.drawLine(nextx, y, nextx, h);
nextx = 475;
contentStream.drawLine(nextx, y, nextx, h);
nextx = 545;
contentStream.drawLine(nextx, y, nextx, h);
//now add the text
contentStream.close();
document.save(path);
document.close();
System.out.println("done");
}
}
No comments:
Post a Comment