I'm trying to vertically align a table in my document to the bottom of the page.
I've set the vertical alignment of the table to BOTTOM but that just makes the cells align to the bottom of the table itself.
How can I make the Document itself vertically aligned to the bottom?
Thanks
After many days of searching.. my solution was to wrap my table in an outer table with 1 cell. Set the cell to the height of the page minus the two margins and set vertical alignment to the bottom. Add all content you want bottom justified to this table.
Full example, error code omitted for brevity
public void run() {
try {
Document document = new Document(PageSize.LETTER, 10.0f, 10.0f, 36.0f, 36.0f);
PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream("test.pdf"));
document.open();
PdfPTable outerTable = new PdfPTable(1);
outerTable.setWidthPercentage(100.0f);
PdfPCell cell = new PdfPCell();
cell.setMinimumHeight(document.getPageSize().getHeight() - 36.0f - 36.0f);
cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
cell.addElement(createTable());
outerTable.addCell(cell);
document.add(outerTable);
document.newPage();
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public PdfPTable leftTable() {
PdfPTable table = new PdfPTable(1);
for (int i = 0; i < 50; i++) {
table.addCell("Cell: " + i);
}
return table;
}
public PdfPTable middleTable() {
PdfPTable table = new PdfPTable(1);
for (int i = 0; i < 10; i++) {
table.addCell("Cell: " + i);
}
return table;
}
public PdfPTable rightTable() {
PdfPTable table = new PdfPTable(1);
for (int i = 0; i < 100; i++) {
table.addCell("Cell: " + i);
}
return table;
}
public PdfPTable createTable() {
PdfPTable table = new PdfPTable(3);
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
table.addCell(leftTable());
table.addCell(middleTable());
table.addCell(rightTable());
return table;
}
Related
I have multiple tables in my pdf document when printing one of the tables in pdf I need the name of the table to be printed in the header section in all the pages that the table is printed. Also, the header value needs to be changed according to the table name.
I have tried set new table name for the header for each table, however only last table name is printed for all pages.
sample code
PdfGenerator.class
public static void main(String[] args) throws FileNotFoundException, DocumentException {
try {
String pdfFilePath = "C:\\Users\\ychitela\\Desktop\\demo\\NewPdf.pdf";
File file = new File(pdfFilePath);
FileOutputStream fileout = new FileOutputStream(file);
Document document = new Document(PageSize.A4.rotate(), 36, 36, 55, 25);
PdfWriter writer = PdfWriter.getInstance(document, fileout);
ReportHeader event = new ReportHeader();
writer.setPageEvent(event);
writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
document.open();
document.addAuthor("Me");
document.addTitle("Table Report");
Font font = FontFactory.getFont("TIMES_ROMAN", 12, BaseColor.BLACK);
document.add(new Paragraph("Intro Page"));
document.newPage();
Chapter chapter = new Chapter(new Paragraph("Table \n\n"), 0);
chapter.setNumberDepth(0);
chapter.add(new Paragraph(" "));
for (int i = 1; i < 5; i++) {
float[] columnWidths = { 1f, 1f };
// create PDF table with the given widths
PdfPTable table = new PdfPTable(columnWidths);
table.setHorizontalAlignment(Element.ALIGN_LEFT);
table.setWidthPercentage(30.0f);
Section subsection = chapter.addSection(new Paragraph("Table "+i+" \n\n"), 0);
event.setTableName("Table header" + i);
writer.setPageEvent(event);
table.addCell(new PdfPCell(new Phrase("Column 1", font)));
table.addCell(new PdfPCell(new Phrase("Column 2", font)));
table.setHeaderRows(1);
for (int j = 0; j < 25; j++) {
table.addCell(new PdfPCell(new Phrase("Hello" + j, font)));
table.addCell(new PdfPCell(new Phrase("World" + j, font)));
}
subsection.add(table);
subsection.newPage();
}
document.add(chapter);
document.close();
System.out.println("Done");
} catch (DocumentException e) {
e.printStackTrace();
}
}
Header.class
public class ReportHeader extends PdfPageEventHelper {
private String tableName;
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
#Override
public void onEndPage(PdfWriter writer, Document document) {
PdfPTable table2 = new PdfPTable(1);
try {
BaseColor basecolour = BaseColor.DARK_GRAY;
Font fontboldHead = FontFactory.getFont("TIMES_ROMAN", 8, basecolour);
table2.setTotalWidth(300);
PdfPCell cell2 = new PdfPCell(new Paragraph(tableName, fontboldHead));
cell2.setBorder(Rectangle.NO_BORDER);
cell2.setHorizontalAlignment(Element.ALIGN_LEFT);
cell2.setVerticalAlignment(Element.ALIGN_BOTTOM);
table2.addCell(cell2);
table2.writeSelectedRows(0, -1, document.left(), 580, writer.getDirectContent());
} catch (Exception e) {
e.printStackTrace();
}
}
}
As you have found out yourself, the problem cause is
I was using chapter and subsection in my actual code and looping and at the end of the loop, I'm adding the chapter to document. so that has been leading to only print only last table name.
To make the dynamic header as is work, you have to add the content more early; in particular you have to add the current contents of the chapter to the document each time you're adding a new table, i.e. each time the header will change.
You can do this by making use of the fact that Chapter implements LargeElement, i.e. you can add a Chapter instance to your document multiple times, and each time only everything new in the chapter since the last time is written to the document. To do so you have to set its Complete property to false at the start and back to true only before adding it the final time. Thus,
Chapter chapter = new Chapter(new Paragraph("Table \n\n"), 0);
// prepare chapter to be set piecewise
chapter.setComplete(false);
chapter.setNumberDepth(0);
chapter.add(new Paragraph(" "));
for (int i = 1; i < 5; i++) {
float[] columnWidths = { 1f, 1f };
// create PDF table with the given widths
PdfPTable table = new PdfPTable(columnWidths);
table.setHorizontalAlignment(Element.ALIGN_LEFT);
table.setWidthPercentage(30.0f);
// add recent chapter additions
document.add(chapter);
Section subsection = chapter.addSection(new Paragraph("Table "+i+" \n\n"), 0);
event.setTableName("Table header" + i);
writer.setPageEvent(event);
table.addCell(new PdfPCell(new Phrase("Column 1", font)));
table.addCell(new PdfPCell(new Phrase("Column 2", font)));
table.setHeaderRows(1);
for (int j = 0; j < 25; j++) {
table.addCell(new PdfPCell(new Phrase("Hello" + j, font)));
table.addCell(new PdfPCell(new Phrase("World" + j, font)));
}
subsection.add(table);
subsection.newPage();
}
// prepare chapter to be completed
chapter.setComplete(true);
// final adding of chapter
document.add(chapter);
(ChapterAndDynamicHeader test testLikeYuvarajChitelaImproved)
How to add an image over a table with Itext?
I'm using the version 5.5.10
implementation 'com.itextpdf:itextg:5.5.10'
Edit: The image can not be inside the row / column, it must be independent to populate any position on the screen
I'm trying to add an image over the columns of a table, but the result is this:
It always lies below the rows of the column.
To add the image I'm doing so:
public void addImg (int dwb, float x, float y, float desc) {
try{
Bitmap bitmap = dwbToBitmap(context, dwb);
ByteArrayOutputStream stream3 = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream3);
Image image = Image.getInstance(stream3.toByteArray());
stream3.close();
image.scaleToFit(sizeImgFit, sizeImgFit);
image.setAbsolutePosition(35.6f + 10f + x, height-y-sizeImg-(height-desc));
document.add(image);
}catch (Exception e){
log("addImg", e);
}
}
I have already tried to change the order, create the first table and then add the images or vise versa, but it does not work.
Does anyone know how to put the images in position Z above all?
I create the table like this:
public void createTable(ArrayList<String> header, ArrayList<String[]> clients){
float height = 569/header.size();
sizeImg = height;
sizeImgFit = sizeImg - 2;
PdfPTable pdfPTable = new PdfPTable(header.size());
pdfPTable.setWidthPercentage(100);
PdfPCell pdfPCell;
int indexC = 0;
while(indexC < header.size()){
pdfPCell = new PdfPCell(new Phrase(header.get(indexC++), fHeaderText));
pdfPCell.setHorizontalAlignment(Element.ALIGN_CENTER);
pdfPCell.setBackgroundColor(BaseColor.GRAY);
pdfPTable.addCell(pdfPCell);
}
int i = 0;
for(String[] row : clients){
int p = 0;
for(String linha : row){
pdfPCell = new PdfPCell(new Phrase(linha, fText));
pdfPCell.setHorizontalAlignment(Element.ALIGN_CENTER);
pdfPCell.setVerticalAlignment(Element.ALIGN_CENTER);
pdfPCell.setFixedHeight(height);
pdfPTable.addCell(pdfPCell);
log("linha - coluna", i + " - " + p);
p++;
}
i++;
}
//paragraph.add(pdfPTable);
try {
document.add(pdfPTable);
}catch (Exception e){
log("paragraph", e);
}
}
These methods mentioned above are in a class:
public class TemplatePDF {
private Context context;
private File pdfFile;
private Document document;
public PdfWriter pdfWriter;
private Paragraph paragraph;
private Rotate event;
private Font fTitle = new Font(Font.FontFamily.TIMES_ROMAN, 20, Font.BOLD);
private Font fSubTitle = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
private Font fHeaderText = new Font(Font.FontFamily.TIMES_ROMAN, 3, Font.NORMAL, BaseColor.WHITE);
private Font fText = new Font(Font.FontFamily.TIMES_ROMAN, 3);
private Font fHText = new Font(Font.FontFamily.TIMES_ROMAN, 8);
private Font fHighText = new Font(Font.FontFamily.TIMES_ROMAN, 15, Font.BOLD, BaseColor.RED);
private float width = PageSize.A4.getWidth();
private float height = PageSize.A4.getHeight();
public float sizeImg;
public float sizeImgFit;
public TemplatePDF(Context context){
this.context = context;
}
public void openDocument(){
createFile();
try{
document = new Document(PageSize.A4);
pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
event = new Rotate();
document.open();
}catch (Exception e){
Log.e("erro", e.toString());
}
}
private void createFile(){
File folder = new File(Environment.getExternalStorageDirectory().toString(), "PDF");
if(!folder.exists()){
folder.mkdirs();
}
pdfFile = new File(folder, key() + ".pdf");
}
public void closeDocument(){
document.close();
}
...
}
To create PDF, I do so:
//Creating the object
TemplatePDF templatePDF = new TemplatePDF(ficha_pre.this);
templatePDF.openDocument();
templatePDF.addMetaData("Relatório", "Situs", "Woton Sampaio");
templatePDF.addTitles("Relatório", "","Data: " + getDate());
//Creating the table
ArrayList<String> header = new ArrayList<>();
for(int i = 0; i < 55; i++){
header.add(forString(i));
}
ArrayList<pdfItens> itens = arrayItens();
ArrayList<String[]> files = array();
templatePDF.createHeaderFicha(itens);
templatePDF.createTable(header, files);
//Adding image
templatePDF.addImg(R.drawable.ic_a, 0, 20, 566);
The cause for this is that an Image added to the Document is added in a virtual layer underneath that of regular text and tables. Apparently iText developers assumed that text and table elements by default are to be drawn in front of images.
But you can explicitly add the Image to a different virtual layer which is in turn above that of text and tables, in addImg you merely have to replace
document.add(image);
by
pdfWriter.getDirectContent().addImage(image);
Your image in addImg has its AbsolutePosition set. This actually is necessary for images you want to add to the DirectContent because the DirectContent has no idea about current insertion positions or page dimensions.
As an aside, there also is a DirectContentUnder for stuff that shall go even below the layer of Images added via the Document.
in a PdfPCell i'd like to put multiple images, and a text below each image.
i tried with this code:
private PdfPTable tabellaRighe() throws BadElementException, MalformedURLException, IOException, DocumentException {
int[] cellWidth = {500, 95};
PdfPTable table = new PdfPTable(2);
table.setWidths(cellWidth);
table.setTotalWidth(PageSize.A4.getWidth() - 45);
table.setLockedWidth(true);
PdfPCell cell;
cell = new PdfPCell();
cell.setBorderWidth(0);
Paragraph p = new Paragraph();
for (int i = 0; i < 4; i++) {
Image image = Image.getInstance(imgNd);
image.scaleToFit(300, 135);
Phrase ph = new Phrase();
ph.add(new Chunk(image, 0, 0, true));
ph.add("CIAO");
p.add(ph);
}
cell.addElement(p);
table.addCell(cell);
cell = new PdfPCell();
cell.setBorderWidthBottom(1);
cell.setBorderWidthLeft(1);
cell.setBorderWidthRight(1);
cell.setBorderWidthTop(1);
table.addCell(cell);
}
but the text is not below the image, but shifted to the right.
how can I put the text below each image?
Add \n before and after text.
ph.add("\nCIAO\n");
\n produce new line.
i am using following code to generate pdf file, everything is fine and working but i need to add watermark with the pdf file also alternate color to rows generated in pdf table.
response.setHeader("Content-disposition", "attachment; filename=\"" + reportName + ".pdf\"");
response.setContentType("application/pdf");
PdfWriter.getInstance(document,response.getOutputStream());
try {
document.open();
addTitlePage(document, reportName,path);
/* Image image = Image.getInstance(path+"images/abi.png");
image.setAbsolutePosition(40f, 770f);
image.scaleAbsolute(70f, 50f);
document.add(image);*/
//float[] colsWidth = {1.5f,3f,4f,4f,2f};
List<Float> colsWidth = new ArrayList<Float>();
int iterator = 1;
while (iterator <= headerMap.size()) {
if(iterator==1){
colsWidth.add(1.5f);
}else{
colsWidth.add(3f);
}
iterator++;
}
float[] floatArray = ArrayUtils.toPrimitive(colsWidth.toArray(new Float[0]), 0.0F);
PdfPTable table = new PdfPTable(floatArray);
table.setWidthPercentage(98);
table.setHorizontalAlignment(Element.ALIGN_CENTER);
PdfPCell c1 = new PdfPCell();
for (Iterator it = headerMap.keySet().iterator(); it.hasNext();) {
String headerName = (String) headerMap.get(it.next());
c1 = new PdfPCell(new Phrase(headerName, headerFont));
c1.setBackgroundColor(BaseColor.LIGHT_GRAY);
table.addCell(c1);
}
table.setHeaderRows(1);
table = custDAO.creadPDFTable(query, table);
document.add(table);
document.addAuthor(userViewModel.getUsername());
document.addCreationDate();
document.addCreator("POC");
document.close();
response.flushBuffer();
private static void addTitlePage(Document document, String reportName,String path) throws DocumentException, MalformedURLException, IOException {
Paragraph preface = new Paragraph();
addEmptyLine(preface, 1);
/**
* Lets write a big header
*/
Paragraph paragraph = new Paragraph(reportName, titleFont);
paragraph.setAlignment(Element.ALIGN_CENTER);
document.add(paragraph);
/**
* Add one empty line
*/
addEmptyLine(preface, 1);
document.add(preface);
Image image = Image.getInstance(path+"/"+"/abilogo.PNG");
image.setAbsolutePosition(40f, 770f);
image.scaleAbsolute(70f, 50f);
document.add(image);
}
private static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
and this the method i use to create pdftable.(rows)
public PdfPTable creadPDFTable(String query,PdfPTable table){
int numberOfColumns=0,sno=1;
Connection connection = getConnection();
if (connection != null) {
try {
PreparedStatement reportTablePS = connection.prepareStatement(query);
ResultSet reportTable_rst = reportTablePS.executeQuery();
ResultSetMetaData reportTable_rsmd = reportTable_rst.getMetaData();
numberOfColumns = reportTable_rsmd.getColumnCount();
while (reportTable_rst.next()) {
table.addCell(new PdfPCell(new Paragraph(String.valueOf(sno), textFont)));
for (int columnIterator = 1; columnIterator <= numberOfColumns; columnIterator++) {
String column = reportTable_rst.getString(columnIterator);
table.addCell(new PdfPCell(new Paragraph(column, textFont)));
}
sno++;
}
} catch (Exception ex) {
ex.printStackTrace();
}finally {
try {
closeConnection(connection, null, null);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return table;
}
my main concern is to add watermark also adding alternate color to rows.
Please help to resolve this as i am unable to fix this for long time.
Regards
If you want add an watermark as a image u can use the code below. An other way to add a text watermark is to use annotations.
PdfReader pdfReader = null;
Stream outputStream = null;
PdfStamper pdfStamper = null;
try
{
pdfReader = GetPdfReaderObject();
outputStream = new FileStream(filePathDestination, FileMode.Create, FileAccess.Write, FileShare.None);
pdfStamper = new PdfStamper(pdfReader, outputStream);
PdfLayer layer = new PdfLayer("watermark", pdfStamper.Writer);
for (int pageIndex = 1; pageIndex <= pdfReader.NumberOfPages; pageIndex++) {
pdfStamper.FormFlattening = false;
iTextSharp.text.Rectangle pageRectangle = pdfReader.GetPageSizeWithRotation(pageIndex);
PdfContentByte pdfData = pdfStamper.GetOverContent(pageIndex);
pdfData.BeginLayer(layer);
PdfGState graphicsState = new PdfGState();
graphicsState.FillOpacity = 0.5F;
pdfData.SetGState(graphicsState);
pdfData.BeginText();
iTextSharp.text.Image watermarkImage = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromFile(watermarkImagePath), ImageFormat.Png);
float width = pageRectangle.Width;
float height = pageRectangle.Height;
watermarkImage.SetAbsolutePosition(width / 2 - watermarkImage.Width / 2, height / 2 - watermarkImage.Height / 2);
pdfData.AddImage(watermarkImage);
pdfData.EndText();
pdfData.EndLayer();
}
}
pdfStamper.Close();
outputStream.Close();
outputStream.Dispose();
pdfReader.Close();
pdfReader.Dispose();
} catch (Exception e) {
....
}
}
And not forget to remove the watermark if you want to add an other watermark.
I am generating pdf file using com.itextpdf.text.* following is my code which creates the pdf file with title and header higlighted and rows, what i wanted to do is, create a pdf file with image on the top and rows with alternate color, how to do this in using com.itextpdf.text.*
response.setHeader("Content-disposition", "attachment; filename=\"" + reportName + ".pdf\"");
response.setContentType("application/pdf");
PdfWriter.getInstance(document,response.getOutputStream());
try {
document.open();
addTitlePage(document, reportName);
//float[] colsWidth = {1.5f,3f,4f,4f,2f};
List<Float> colsWidth = new ArrayList<Float>();
int iterator = 1;
while (iterator <= headerMap.size()) {
if(iterator==1){
colsWidth.add(1.5f);
}else{
colsWidth.add(3f);
}
iterator++;
}
float[] floatArray = ArrayUtils.toPrimitive(colsWidth.toArray(new Float[0]), 0.0F);
PdfPTable table = new PdfPTable(floatArray);
table.setWidthPercentage(98);
table.setHorizontalAlignment(Element.ALIGN_CENTER);
PdfPCell c1 = new PdfPCell();
for (Iterator it = headerMap.keySet().iterator(); it.hasNext();) {
String headerName = (String) headerMap.get(it.next());
c1 = new PdfPCell(new Phrase(headerName, headerFont));
c1.setBackgroundColor(BaseColor.LIGHT_GRAY);
table.addCell(c1);
}
table.setHeaderRows(1);
table = custDAO.creadPDFTable(query, table);
document.add(table);
document.addAuthor(userViewModel.getUsername());
document.addCreationDate();
document.addCreator("POC");
document.close();
response.flushBuffer();
public PdfPTable creadPDFTable(String query,PdfPTable table){
int numberOfColumns=0,sno=1;
Connection connection = getConnection();
if (connection != null) {
try {
PreparedStatement reportTablePS = connection.prepareStatement(query);
ResultSet reportTable_rst = reportTablePS.executeQuery();
ResultSetMetaData reportTable_rsmd = reportTable_rst.getMetaData();
numberOfColumns = reportTable_rsmd.getColumnCount();
while (reportTable_rst.next()) {
table.addCell(new PdfPCell(new Paragraph(String.valueOf(sno), textFont)));
for (int columnIterator = 1; columnIterator <= numberOfColumns; columnIterator++) {
String column = reportTable_rst.getString(columnIterator);
table.addCell(new PdfPCell(new Paragraph(column, textFont)));
}
sno++;
}
} catch (Exception ex) {
ex.printStackTrace();
}finally {
try {
closeConnection(connection, null, null);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return table;
}
private static void addTitlePage(Document document, String reportName) throws DocumentException {
Paragraph preface = new Paragraph();
addEmptyLine(preface, 1);
/**
* Lets write a big header
*/
Paragraph paragraph = new Paragraph(reportName, titleFont);
paragraph.setAlignment(Element.ALIGN_CENTER);
document.add(paragraph);
/**
* Add one empty line
*/
addEmptyLine(preface, 1);
document.add(preface);
}
private static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
when i use the following i get the following exception 'getoutputstream() has already called for this response'
i wanted to use this for inserting image.
Image image = Image.getInstance(path+"images/abi.png");
image.setAbsolutePosition(40f, 770f);
image.scaleAbsolute(70f, 50f);
document.add(image);
so how to go about doing this?
UPDATE :
i want to create a pdf file like this i just want to add image on the top and rows with alternate color like this.
http://what-when-how.com/itext-5/decorating-tables-using-table-and-cell-events-itext-5/
(source: what-when-how.com)
(source: what-when-how.com)
You can use XSLFO and Apache FOP. It worked for me. For adding a image I done changes in XSL.
For reference visit
http://www.codeproject.com/Articles/37663/PDF-Generation-using-XSLFO-and-FOP