How to provide alignment to chunk or phrases in itext? - java

I have two chunks, added in phrases and then in paragraph.
Chunk reportTitle= new Chunk("Candidate Login Report ",catFont);
Chunk divisiontitle = new Chunk("Division : \t\t"+divisionName);
Phrase phrase = new Phrase();
phrase.add(reportTitle);
phrase.add(divisiontitle);
Paragraph para = new Paragraph();
para.add(phrase);
I have to set chunk divisiontitle to right aligned. Is there any provision to do this in iIext?

You really answered yourself in your comment.
Chunk reportTitle= new Chunk("Candidate Login Report ",catFont);
Chunk divisiontitle = new Chunk("Division : \t\t"+divisionName);
Phrase phrase = new Phrase();
phrase.add(reportTitle);
phrase.add(divisiontitle);
Paragraph para = new Paragraph();
para.add(phrase);
para.setAlignment(Element.ALIGN_RIGHT);
Then you can add it to any cell and it will be correctly aligned.

bajrangi,
You might want to use ColumnText.showTextAligned() to align your text. Try the following:
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
PdfContentByte canvas = writer.getDirectContent();
ColumnText.showTextAligned(canvas, Element.ALIGN_RIGHT, phrase, xPosition, yPosition, 0);
Cheers!
-Eric

add multiple Chunk and Phrase in itextpdf
package com.pdf.hl;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.html.WebColors;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class GraphicsStateOperators {
public static final String RESULT = "d:/graphics_state.pdf";
static Font.FontFamily ff = Font.FontFamily.HELVETICA;
static float size = 10;
static float size1 = 8;
public void createPdf(String filename) throws Exception {
Font bold = new Font(Font.FontFamily.HELVETICA, 8f, Font.BOLD);
Font normal = new Font(Font.FontFamily.HELVETICA, 8f, Font.NORMAL);
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(filename));
document.open();
// /////////////////////////////////////////////
PdfPTable tabletmp = new PdfPTable(1);
tabletmp.getDefaultCell().setBorder(Rectangle.NO_BORDER);
tabletmp.setWidthPercentage(100);
PdfPTable table = new PdfPTable(2);
float[] colWidths = { 45, 55 };
table.setWidths(colWidths);
String imageUrl = "http://logo.com/content1/images/logo_heartSmart.jpg";
Image image2 = Image.getInstance(new URL(imageUrl));
image2.setWidthPercentage(60);
table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);
PdfPCell cell = new PdfPCell();
cell.setBorder(Rectangle.NO_BORDER);
cell.addElement(image2);
table.addCell(cell);
String receiptNo = "123455555555555555";
String collectionDate = "09/09/09";
Chunk chunk1 = new Chunk("Date: ", normal);
Phrase ph1 = new Phrase(chunk1);
Chunk chunk2 = new Chunk(collectionDate, bold);
Phrase ph2 = new Phrase(chunk2);
Chunk chunk3 = new Chunk("\nReceipt No: ", normal);
Phrase ph3 = new Phrase(chunk3);
Chunk chunk4 = new Chunk(receiptNo, bold);
Phrase ph4 = new Phrase(chunk4);
Paragraph ph = new Paragraph();
ph.add(ph1);
ph.add(ph2);
ph.add(ph3);
ph.add(ph4);
table.addCell(ph);
tabletmp.addCell(table);
PdfContentByte canvas = writer.getDirectContent();
canvas.saveState();
canvas.setLineWidth((float) 10 / 10);
canvas.moveTo(40, 806 - (5 * 10));
canvas.lineTo(555, 806 - (5 * 10));
canvas.stroke();
document.add(tabletmp);
canvas.restoreState();
PdfPTable tabletmp1 = new PdfPTable(1);
tabletmp1.getDefaultCell().setBorder(Rectangle.NO_BORDER);
tabletmp1.setWidthPercentage(100);
PdfPTable table1 = new PdfPTable(2);
table1.getDefaultCell().setBorder(Rectangle.NO_BORDER);
table1.getDefaultCell().setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
table1.getDefaultCell().setVerticalAlignment(Element.ALIGN_JUSTIFIED);
float[] colWidths1 = { 60, 40 };
table1.setWidths(colWidths1);
String Patient = "abcddd";
String Email = "test#test.com";
String Phone = "89890099890890";
PdfPCell cell3 = new PdfPCell();
cell3.setBorder(Rectangle.NO_BORDER);
Chunk chunkPatientLabal = new Chunk("Patient: ", normal);
Phrase phPatientLabal = new Phrase(chunkPatientLabal);
Chunk chunkPatient = new Chunk(Patient, bold);
Phrase phPatient = new Phrase(chunkPatient);
Chunk chunkEmailLabal = new Chunk("\nEmail: ", normal);
Phrase phEmailLabal = new Phrase(chunkEmailLabal);
Chunk chunkEmail = new Chunk(Email, bold);
Phrase phEmail = new Phrase(chunkEmail);
Chunk chunkPhoneLabal = new Chunk("\nPhone: ", normal);
Phrase phPhoneLabal = new Phrase(chunkPhoneLabal);
Chunk chunkPhone = new Chunk(Phone, bold);
Phrase phPhone = new Phrase(chunkPhone);
Paragraph phN = new Paragraph();
phN.add(phPatientLabal);
phN.add(phPatient);
phN.add(phEmailLabal);
phN.add(phEmail);
phN.add(phPhoneLabal);
phN.add(phPhone);
cell3.addElement(phN);
table1.addCell(cell3);
PdfPCell cell4 = new PdfPCell();
cell4.getBorderWidthRight();
cell4.setBorder(Rectangle.NO_BORDER);
String ReferingPhysician = "phy Patient";
Chunk chunkRefPhyLabal = new Chunk("Refering Physician: ", normal);
Phrase phRefPhyLabal = new Phrase(chunkRefPhyLabal);
Chunk chunkRefPhy = new Chunk(ReferingPhysician, bold);
Phrase phRefPhy = new Phrase(chunkRefPhy);
Paragraph phN1 = new Paragraph();
phN1.add(phRefPhyLabal);
phN1.setAlignment(com.itextpdf.text.Element.ALIGN_RIGHT);
phN1.add(phRefPhy);
cell4.addElement(phN1);
table1.addCell(cell4);
tabletmp1.addCell(table1);
tabletmp1.setSpacingAfter(10);
document.add(tabletmp1);
PdfPTable table7 = new PdfPTable(1);
table7.setWidthPercentage(100);
PdfPCell c7 = new PdfPCell(new Phrase("Payment Summry", new Font(ff,
size, Font.BOLD)));
BaseColor headingColor7 = WebColors.getRGBColor("#989898");
c7.setBackgroundColor(headingColor7);
c7.setHorizontalAlignment(com.itextpdf.text.Element.ALIGN_LEFT);
table7.addCell(c7);
table7.setSpacingAfter(2f);
document.add(table7);
// ////////////////////////////////////////////////////////
PdfPTable tabletmp2 = new PdfPTable(1);
BaseColor headingColor8 = WebColors.getRGBColor("#F0F0F0");
tabletmp2.setWidthPercentage(100);
PdfPTable table8 = new PdfPTable(2);
table8.getDefaultCell().setBorder(Rectangle.NO_BORDER);
table8.getDefaultCell().setHorizontalAlignment(Element.ALIGN_JUSTIFIED);
table8.getDefaultCell().setVerticalAlignment(Element.ALIGN_JUSTIFIED);
float[] colWidths8 = { 50, 50 };
table8.setWidths(colWidths8);
PdfPCell cellPaymentSummry = new PdfPCell();
cellPaymentSummry.setBackgroundColor(headingColor8);
cellPaymentSummry.setBorder(Rectangle.NO_BORDER);
Chunk chunkPaymentInvoiceLabal = new Chunk("Invoice Id", normal);
Phrase phPaymentInvoiceLabal = new Phrase(chunkPaymentInvoiceLabal);
Chunk chunkPaymentModeLabal = new Chunk("\nPayment Mode", normal);
Phrase phPaymentModeLabal = new Phrase(chunkPaymentModeLabal);
Chunk chunkAmountReceivedLabal = new Chunk("\nAmount Received", normal);
Chunk chunkAmountDueLabal = new Chunk("\nAmount Due", normal);
Phrase phAmountDueLabal = new Phrase(chunkAmountDueLabal);
Phrase phAmountReceivedLabal = new Phrase(chunkAmountReceivedLabal);
Paragraph phPaymentSummry = new Paragraph();
phPaymentSummry.add(phPaymentInvoiceLabal);
phPaymentSummry.add(phPaymentModeLabal);
phPaymentSummry.add(phAmountReceivedLabal);
phPaymentSummry.add(phAmountDueLabal);
cellPaymentSummry.addElement(phPaymentSummry);
table8.addCell(cellPaymentSummry);
PdfPCell cellPaymentSummry1 = new PdfPCell();
cellPaymentSummry1.setBackgroundColor(headingColor8);
cellPaymentSummry1.getBorderWidthRight();
cellPaymentSummry1.setBorder(Rectangle.NO_BORDER);
String PaymentMode = "rannnnnnnnnnnnnnnnn";
String amountReceived = "2.33";
String amountDue = "28.00";
String invoice = "123";
Chunk chunkPaymentInvoicel = new Chunk(invoice, bold);
Phrase phPaymentInvoice = new Phrase(chunkPaymentInvoicel);
Chunk chunkPaymentMode = new Chunk("\n" + PaymentMode, bold);
Phrase phPaymentMode = new Phrase(chunkPaymentMode);
Chunk chunkAmountReceived = new Chunk("\n$" + amountReceived, bold);
Phrase phAmountReceived = new Phrase(chunkAmountReceived);
Chunk chunkAmountDue = new Chunk("\n$" + amountDue, bold);
Phrase phAmountDue = new Phrase(chunkAmountDue);
Paragraph phPaymentSummry1 = new Paragraph();
phPaymentSummry1.add(phPaymentInvoice);
phPaymentSummry1.add(phPaymentMode);
phPaymentSummry1.setAlignment(com.itextpdf.text.Element.ALIGN_RIGHT);
phPaymentSummry1.add(phAmountReceived);
phPaymentSummry1.add(phAmountDue);
cellPaymentSummry1.addElement(phPaymentSummry1);
table8.addCell(cellPaymentSummry1);
tabletmp2.addCell(table8);
document.add(tabletmp2);
document.close();
}
/**
* Main method.
*
* #param args
* no arguments needed
* #throws DocumentException
* #throws IOException
*/
public static void main(String[] args) throws Exception {
new GraphicsStateOperators().createPdf(RESULT);
System.out.println("Done Please check........");
}
}

via https://stackoverflow.com/a/47644620:
Chunk glue = new Chunk(new VerticalPositionMark())
Paragraph p = new Paragraph();
p.Add("Text to the left");
p.Add(glue);
p.Add("Text to the right");
tested as working under iTextSharp.LGPLv2.Core 1.4.5 (iText 4)

#WebServlet(name = "Servlet")
public class PDFServlet extends HttpServlet {
private String RESOURCE = "images/logo-new.png";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
response.setContentType("application/pdf");
Document document = new Document(PageSize.LETTER);
PdfWriter writer = null;
try {
writer = PdfWriter.getInstance(document, response.getOutputStream());
document.open();
document.add(createHeaderTable());
document.add(comapnyNameTable());
document.add(createAddressTable());
document.add(getTable());
document.add(createFooterTable());
PdfContentByte canvas = writer.getDirectContent();
canvas.setLineWidth((float) 10 / 10);
canvas.moveTo(40, 765 - (5 * 10));
canvas.lineTo(570, 770 - (5 * 10));
canvas.stroke();
document.close();
} catch (DocumentException e) {
e.printStackTrace();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
private PdfPTable createHeaderTable(){
Font bold = new Font(Font.FontFamily.HELVETICA, 8f, Font.BOLD);
Font normal = new Font(Font.FontFamily.HELVETICA, 8f, Font.NORMAL);
PdfPTable table = new PdfPTable(2);
try{
table.setWidthPercentage(100f);
table.setHorizontalAlignment(0);;
table.setSpacingBefore(10);
table.setWidths(new int[]{2, 6});
Image img = Image.getInstance(RESOURCE);
img.scalePercent(28f);
PdfPCell pdfPCell = new PdfPCell(img,true);
//pdfPCell.addElement(img);
pdfPCell.setBorder(Rectangle.NO_BORDER);
pdfPCell.setFixedHeight(50);
table.addCell(pdfPCell);
Paragraph paragraph = new Paragraph(10);
paragraph.add(new Chunk("Date:",bold));
paragraph.add(new Chunk("11-09-2015",normal));
paragraph.add(new Chunk("\nOrder Id:",bold));
paragraph.add(new Chunk("OrderId#12345",normal));
paragraph.setIndentationLeft(260);
table.addCell(newPdfPcel(paragraph,50));
}
catch (DocumentException e){
e.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
return table;
}
private PdfPTable createAddressTable(){
PdfPTable table = new PdfPTable(2);
Font bold = new Font(Font.FontFamily.HELVETICA, 8f, Font.BOLD);
Font normal = new Font(Font.FontFamily.HELVETICA, 8f, Font.NORMAL);
try{
table.setWidthPercentage(100f);
table.setHorizontalAlignment(0);;
table.setSpacingBefore(10);
table.setSpacingAfter(10);
table.setWidths(new int[]{2, 6});
Paragraph paragraph = new Paragraph(10);
paragraph.add(new Chunk("Billed To",bold));
paragraph.add(new Chunk("\nOrdered By tdhdghfjghjg fvgfdghgfhg gfhggjdjh ghgfhgjhgjhg gfhghjghj dghgfh ghggfhgfh ghgffgh ghjggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg", normal));
paragraph.setIndentationRight(40);
table.addCell(newPdfPcel(paragraph,60));
Paragraph paragraph2 = new Paragraph(10);
paragraph2.add(new Chunk("Service By ",bold));
paragraph2.add(new Chunk("\nService B gfdsgfdhghhhhy tdhdghfjghjg fvgfdghgfhg gfhggjdjh ghgfhgjhgjhg gfhghjghj dghgfhh ghfddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd",normal));
paragraph2.setIndentationLeft(260);
table.addCell(newPdfPcel(paragraph2,60));
Paragraph paragraph3 = new Paragraph(10);
paragraph3.add(new Chunk("Payment Method:", bold));
paragraph3.add(new Chunk("\nVisa ending with *888888888888888888888888888888888888888888888**********123,\nseeenu#gmail.com",normal));
table.addCell(newPdfPcel(paragraph3,60));
Paragraph paragraph4 = new Paragraph(10);
paragraph4.add(new Chunk("Order Date:",bold));
paragraph4.add(new Chunk("\nMarch 7,2014",normal));
paragraph4.setIndentationLeft(260);
table.addCell(newPdfPcel(paragraph4,60));
}
catch (DocumentException e){
e.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
return table;
}
private PdfPTable comapnyNameTable(){
PdfPTable table = new PdfPTable(1);
Font bold = new Font(Font.FontFamily.HELVETICA, 8f, Font.BOLD);
Font normal = new Font(Font.FontFamily.HELVETICA, 8f, Font.NORMAL);
try{
table.setWidthPercentage(100f);
Paragraph paragraph = new Paragraph(10);
paragraph.add(new Chunk("Travels Company",bold));
paragraph.add(new Chunk("\nOrdered By tdhdghfjghjg fvgfdghgfhg gfhggjdjh ghgfhgjhgjhg gfhghjghj dghgfh ghggfhgfh ghgffgh ghjggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg",normal));
paragraph.setIndentationLeft(200f);
paragraph.setIndentationRight(200f);
table.addCell(newPdfPcel(paragraph,60));
}
catch (Exception e){
e.printStackTrace();
}
return table;
}
private PdfPTable createFooterTable(){
PdfPTable table = new PdfPTable(2);
Font bold = new Font(Font.FontFamily.HELVETICA, 8f, Font.BOLD);
Font normal = new Font(Font.FontFamily.HELVETICA, 8f, Font.NORMAL);
try{
table.setWidthPercentage(100f);
table.setHorizontalAlignment(0);;
table.setSpacingBefore(10);
table.setSpacingAfter(10);
table.setWidths(new int[]{2, 6});
Paragraph paragraph = new Paragraph(10);
paragraph.add(new Chunk("Tearms & Conditions",bold));
paragraph.add(new Chunk("\ngfdhgfhgfh",normal));
Paragraph paragraph2 = new Paragraph(10);
paragraph2.add(new Chunk("Aggrigate Service By",bold));
paragraph2.add(new Chunk("\nTruckWay",normal));
paragraph2.setIndentationLeft(260);
table.addCell(newPdfPcel(paragraph2,0));
}
catch (DocumentException e){
e.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
return table;
}
private Paragraph createParagraph(String text,Font font,float indentationLeft,float indentationRight){
Paragraph paragraph = new Paragraph(10);
paragraph.add(new Chunk(text,font));
paragraph.setIndentationLeft(indentationLeft);
paragraph.setIndentationRight(indentationRight);
return paragraph;
}
private PdfPCell newPdfPcel(Paragraph paragraph,float fixedHight){
PdfPCell pdfPCell = new PdfPCell();
pdfPCell.addElement(paragraph);
pdfPCell.setBorder(Rectangle.NO_BORDER);
pdfPCell.setFixedHeight(fixedHight);
return pdfPCell;
}
public PdfPTable getTable()throws DocumentException, IOException {
// Create a table with 7 columns
PdfPTable table = new PdfPTable(2);
table.setWidthPercentage(100f);
// Add the first header row
PdfPCell cell = new PdfPCell(new Phrase("Order Details", FontFactory.getFont("Arial",10,Font.BOLD,BaseColor.BLACK)));
cell.setBackgroundColor(BaseColor.CYAN);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setColspan(7);
table.addCell(cell);
Font font = new Font();
font.setSize(10);
font.setFamily("Arial");
table.addCell(createCel("From Place",font,Element.ALIGN_LEFT));
table.addCell(createCel("Hyderabad",font,Element.ALIGN_LEFT));
table.addCell(createCel("To Place",font,Element.ALIGN_LEFT));
table.addCell(createCel("Bangolore",font,Element.ALIGN_LEFT));
table.addCell(createCel("Truck RequestDate",font,Element.ALIGN_LEFT));
table.addCell(createCel("09/9/15",font,Element.ALIGN_LEFT));
table.addCell(createCel("Truck Type",font,Element.ALIGN_LEFT));
table.addCell(createCel("6 wheeler",font,Element.ALIGN_LEFT));
table.addCell(createCel("No OfTrucks",font,Element.ALIGN_LEFT));
table.addCell(createCel("1",font,Element.ALIGN_LEFT));
table.addCell(createCel("Total Capacity",font,Element.ALIGN_LEFT));
table.addCell(createCel("8",font,Element.ALIGN_LEFT));
table.addCell(createCel("Total Amount",font,Element.ALIGN_LEFT));
table.addCell(createCel("1000.00",font,Element.ALIGN_LEFT));
table.addCell(createCel("From Addressy",font,Element.ALIGN_LEFT));
table.addCell(createCel("hyd",font,Element.ALIGN_LEFT));
table.addCell(createCel("To Address",font,Element.ALIGN_LEFT));
table.addCell(createCel("Bang",font,Element.ALIGN_LEFT));
table.addCell(createCel("Advance",font,Element.ALIGN_RIGHT));
table.addCell(createCel("1000.00",font,Element.ALIGN_RIGHT));
table.addCell(createCel("Service Charges",font,Element.ALIGN_RIGHT));
table.addCell(createCel("25.00",font,Element.ALIGN_RIGHT));
table.addCell(createCel("Total",font,Element.ALIGN_RIGHT));
table.addCell(createCel("1000.25",font,Element.ALIGN_RIGHT));
return table;
}
private PdfPCell createCel(String text,Font font,int alignment){
PdfPCell pdfPCel = new PdfPCell(new Phrase(text,font));
pdfPCel.setHorizontalAlignment(alignment);
return pdfPCel;
}
}

Related

How to print dynamic string in PDF header using onEndPage method

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)

itext font color gets darker in first page

I'm using iText 2.1.7,i'm adding header and footer at absolute position using writer.getDirectcontent() method.All is working fine except the fonts in first page gets darker than second pages.
Note the Header and Footer in First and second pages
anyhelp?
Here is what i did
Reader stringReader = new StringReader(svgXmlDoc);
Document document = new Document(PageSize.A4.rotate());
ByteArrayOutputStream content = new ByteArrayOutputStream();
try {
PdfWriter writer = PdfWriter.getInstance(document, content);
document.open();
PdfService event = new PdfService();
event.setHeader(date.toString());
event.onOpenDocument(writer, document);
event.onEndPage(writer, document);
event.onCloseDocument(writer, document);
writer.setPageEvent(event);
Image image1 = Image.getInstance("Infinity-Loop.png");
image1.scalePercent(35);
PdfPTable signature = new PdfPTable(numberOfSignature);
signature.setTotalWidth(document.getPageSize().getWidth()
- document.leftMargin() - document.rightMargin());
signature.setLockedWidth(true);
signature.setWidthPercentage(100);
signature.getDefaultCell().setFixedHeight(20);
signature.getDefaultCell().setHorizontalAlignment(
Element.ALIGN_RIGHT);
for (int i = 0; i < numberOfSignature; i++) {
PdfPCell cell = new PdfPCell(new Paragraph(
String.valueOf("____________")));
cell.setBorder(Rectangle.NO_BORDER);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
signature.addCell(cell);
}
PdfPTable header = new PdfPTable(3);
float[] columnWidths = {1f,2f,1f};
header.setWidths(columnWidths);
header.setTotalWidth(document.getPageSize().getWidth()
- document.leftMargin() - document.rightMargin());
header.setLockedWidth(true);
header.setWidthPercentage(100);
header.getDefaultCell().setPadding(15);
header.getDefaultCell().setBorder(Rectangle.NO_BORDER);
PdfPCell logocell = new PdfPCell(image1, false);
logocell.setRowspan(3);
logocell.setFixedHeight(72);
logocell.setBorder(Rectangle.NO_BORDER);
header.addCell(logocell);
PdfPCell Title = new PdfPCell(new Phrase(title,
FontFactory.getFont(FontFactory.TIMES_ROMAN, 18,
Font.PLAIN, new Color(0, 0, 0))));
Title.setBorder(Rectangle.NO_BORDER);
Title.setHorizontalAlignment(Element.ALIGN_CENTER);
header.addCell(Title);
header.addCell("");
header.completeRow();
PdfPCell SubTitle = new PdfPCell(new Phrase(subTitle));
SubTitle.setBorder(Rectangle.NO_BORDER);
SubTitle.setHorizontalAlignment(Element.ALIGN_CENTER);
header.addCell(SubTitle);
header.addCell("");
header.completeRow();
PdfPCell dataRange = new PdfPCell(new Phrase(
dateRange));
dataRange.setBorder(Rectangle.NO_BORDER);
dataRange.setHorizontalAlignment(Element.ALIGN_CENTER);
header.addCell(dataRange);
header.addCell("");
header.completeRow();
ArrayList tmp = header.getRows(0, header.getRows().size());
header.getRows().clear();
header.getRows().addAll(tmp);
int width = (int) ((int) document.getPageSize().getWidth()
- document.leftMargin() - document.rightMargin());
int height = 350;
PdfContentByte cb = writer.getDirectContent();
PdfTemplate template = cb.createTemplate(width, height);
Graphics2D g2 = template.createGraphics(width, height);
PrintTranscoder prm = new PrintTranscoder();
TranscoderInput ti = new TranscoderInput(stringReader);
prm.transcode(ti, null);
PageFormat pg = new PageFormat();
Paper pp = new Paper();
pp.setSize(width, height);
pp.setImageableArea(0, 0, width, height);
pg.setPaper(pp);
prm.print(g2, pg, 0);
g2.dispose();
ImgTemplate img = new ImgTemplate(template);
img.setAbsolutePosition(document.left(), document.topMargin() + 100);
document.add(img);
signature.writeSelectedRows(0, -1, document.left(),
document.bottom() + document.bottomMargin() * 2,
writer.getDirectContent());
header.writeSelectedRows(0, -1, document.left(), document.top(),
writer.getDirectContent());
document.newPage();
PdfPTable statisticsTitle=new PdfPTable(1);
statisticsTitle.setTotalWidth(document.right() - document.left());
statisticsTitle.setWidthPercentage(100);
PdfPCell titleCell= new PdfPCell(new Paragraph("Statistics Report"));
titleCell.setBorder(Rectangle.NO_BORDER);
titleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
statisticsTitle.addCell(titleCell);
statisticsTitle.writeSelectedRows(0, -1, document.left(), document.top()
- document.topMargin() * 2 - 10, writer.getDirectContent());
PdfPTable table;
if(measurementType.equals("Temp")){
table = new PdfPTable(6);
}
else{
table = new PdfPTable(11);
}
table.setTotalWidth(document.right() - document.left());
table.setWidthPercentage(100);
table.setHeaderRows(1);
PdfPCell h1 = new PdfPCell(new Paragraph("Description"));
h1.setGrayFill(0.7f);
h1.setRowspan(2);
h1.setVerticalAlignment(Element.ALIGN_MIDDLE);
h1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(h1);
PdfPCell h2 = new PdfPCell(new Paragraph("Temperature"));
h2.setGrayFill(0.7f);
h2.setColspan(5);
h2.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(h2);
if(measurementType.equals("TempHumi")){
PdfPCell h3 = new PdfPCell(new Paragraph("Humidity"));
h3.setGrayFill(0.7f);
h3.setColspan(5);
h3.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(h3);
}
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
PdfPCell tc1 = new PdfPCell(new Paragraph("Min"));
tc1.setGrayFill(0.7f);
tc1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(tc1);
PdfPCell tc2 = new PdfPCell(new Paragraph("Max"));
tc2.setGrayFill(0.7f);
tc2.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(tc2);
PdfPCell tc3 = new PdfPCell(new Paragraph("Avg"));
tc3.setGrayFill(0.7f);
tc3.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(tc3);
PdfPCell tc4 = new PdfPCell(new Paragraph("Std"));
tc4.setGrayFill(0.7f);
tc4.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(tc4);
PdfPCell tc5 = new PdfPCell(new Paragraph("Mkt"));
tc5.setGrayFill(0.7f);
tc5.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(tc5);
if(measurementType.equals("TempHumi")){
PdfPCell hc1 = new PdfPCell(new Paragraph("Min"));
hc1.setGrayFill(0.7f);
hc1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(hc1);
PdfPCell hc2 = new PdfPCell(new Paragraph("Max"));
hc2.setGrayFill(0.7f);
hc2.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(hc2);
PdfPCell hc3 = new PdfPCell(new Paragraph("Avg"));
hc3.setGrayFill(0.7f);
hc3.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(hc3);
PdfPCell hc4 = new PdfPCell(new Paragraph("Std"));
hc4.setGrayFill(0.7f);
hc4.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(hc4);
PdfPCell hc5 = new PdfPCell(new Paragraph("Mkt"));
hc5.setGrayFill(0.7f);
hc5.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(hc5);
}
ArrayList tmpTable = table.getRows(0, table.getRows().size());
table.getRows().clear();
table.getRows().addAll(tmpTable);
JsonObject listloggerdatastatistics = ReportService
.getStatisticsDetails(serialnumberlist);
System.out.println("Json "+listloggerdatastatistics.get("Sensormodellist"));
for (int row = 0; row < listloggerdatastatistics.get("Sensormodellist").getAsJsonArray().size(); row++) {
JsonObject jsonobj=listloggerdatastatistics.get("Sensormodellist").getAsJsonArray().get(row).getAsJsonObject();
if (row > 20 && row % 21 == 0) {
table.completeRow();
table.writeSelectedRows(0, 22, document.left(),
document.top() - document.topMargin() * 2 - 10,
writer.getDirectContent());
table.deleteBodyRows();
table.setSkipFirstHeader(true);
signature.writeSelectedRows(0, -1, document.left(),
document.bottom() + document.bottomMargin() * 3,
writer.getDirectContent());
header.writeSelectedRows(0, -1, document.left(),
document.top(), writer.getDirectContent());
document.newPage();
}
table.addCell(jsonobj.get("Modeltype").getAsString());
table.addCell(""+jsonobj.get("Mintemperature").getAsBigDecimal().setScale(2, RoundingMode.HALF_UP));
table.addCell(""+jsonobj.get("Maxtemperature").getAsBigDecimal().setScale(2, RoundingMode.HALF_UP));
table.addCell(""+jsonobj.get("Avgtemperature").getAsBigDecimal().setScale(2, RoundingMode.HALF_UP));
table.addCell(""+jsonobj.get("Stdtemperature").getAsBigDecimal().setScale(2, RoundingMode.HALF_UP));
table.addCell(""+jsonobj.get("Mkttemperature").getAsBigDecimal().setScale(2, RoundingMode.HALF_UP));
if(measurementType.equals("TempHumi")){
table.addCell(""+jsonobj.get("Minhumidity").getAsBigDecimal().setScale(2, RoundingMode.HALF_UP));
table.addCell(""+jsonobj.get("Maxhumidity").getAsBigDecimal().setScale(2, RoundingMode.HALF_UP));
table.addCell(""+jsonobj.get("Avghumidity").getAsBigDecimal().setScale(2, RoundingMode.HALF_UP));
table.addCell(""+jsonobj.get("Stdhumidity").getAsBigDecimal().setScale(2, RoundingMode.HALF_UP));
table.addCell("-");
}
}
table.completeRow();
table.writeSelectedRows(0, -1, document.left(), document.top()
- document.topMargin() * 3 - 10, writer.getDirectContent());
signature.writeSelectedRows(0, -1, document.left(),
document.bottom() + document.bottomMargin() * 2,
writer.getDirectContent());
header.writeSelectedRows(0, -1, document.left(), document.top(),
writer.getDirectContent());
} catch (DocumentException e) {
System.err.println(e);
}
document.close();
content.close();
I'm constructing graph image from SVG and table data are populated from database
Event handlers for adding footer with page X of Y
public class PdfService extends PdfPageEventHelper {
/** The header text. */
String header;
/** The template with the total number of pages. */
PdfTemplate total;
/**
* Fills out the total number of pages before the document is closed.
*
* #see com.itextpdf.text.pdf.PdfPageEventHelper#onCloseDocument(com.itextpdf.text.pdf.PdfWriter,
* com.itextpdf.text.Document)
*/
#Override
public void onCloseDocument(PdfWriter writer, Document document) {
total.reset();
ColumnText
.showTextAligned(total, Element.ALIGN_LEFT,
new Phrase(String.valueOf(writer.getPageNumber() - 1)),
2, 2, 0);
}
/**
* Adds a header to every page
*
* #see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(com.itextpdf.text.pdf.PdfWriter,
* com.itextpdf.text.Document)
*/
#Override
public void onEndPage(PdfWriter writer, Document document) {
PdfPTable table = new PdfPTable(4);
try {
table.setWidths(new float[] { (float) (2.25), (float) (1.5), 11, 13 });
table.setTotalWidth(document.getPageSize().getWidth()
- document.leftMargin() - document.rightMargin());
table.setLockedWidth(true);
table.setWidthPercentage(100);
table.getDefaultCell().setFixedHeight(20);
table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell(String.format("Page %d of", writer.getPageNumber()));
Image img = Image.getInstance(total);
Chunk conte = new Chunk(img, 0, 0);
Phrase chunk = new Phrase(conte);
PdfPCell cell = new PdfPCell(chunk);
cell.setBorder(Rectangle.NO_BORDER);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_TOP);
table.addCell(cell);
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell("SuperAdmin");
table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell(header);
table.writeSelectedRows(0, -1, document.leftMargin(),
document.bottom(), writer.getDirectContent());
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}
/**
* Creates the PdfTemplate that will hold the total number of pages.
*
* #see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(com.itextpdf.text.pdf.PdfWriter,
* com.itextpdf.text.Document)
*/
#Override
public void onOpenDocument(PdfWriter writer, Document document) {
total = writer.getDirectContent().createTemplate(15, 14);
// total.setBoundingBox(new Rectangle(-1, 6, 20, 20));
}
/**
* Allows us to change the content of the header.
*
* #param header
* The new header String
*/
public void setHeader(String header) {
this.header = header;
}
}
In old days, when people had one font program for one regular font and no separate font file for a bold font, people found ways to work around this problem, and Adobe Reader was adapted to make this workaround work.
The workaround consists of writing the same content twice (or more) at the same position. When you add "Page 1 of 2" once, the font is presented as a regular font. When you add it twice, the font is presented as a bold font.
This is what happens in your case: you are adding the footer twice. This is wrong:
document.open();
PdfService event = new PdfService();
event.setHeader(date.toString());
event.onOpenDocument(writer, document);
event.onEndPage(writer, document);
event.onCloseDocument(writer, document);
writer.setPageEvent(event);
You invoke event.onEndPage() yourself, adding the footer a first time. When a page is finished, iText calls the onEndPage() method a second time, adding the footer once more, resulting in a bold font.
You should adapt your code like this:
PdfService event = new PdfService();
event.setHeader(date.toString());
writer.setPageEvent(event);
document.open();
You should declare the event to the PdfWriter instance before opening the document. You should not call the onOpenDocument(), onEndPage() and onCloseDocument() methods yourself! They are called internally by iText.
You should also upgrade to the latest version for the reasons explained on the FAQ. Using Open Source and contributing nothing in return is unwise. Supporting your open source communities isn’t charity, it’s good business.

Java iText: text below image

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.

how to add watermark to pdf using itexpdf

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.

how to create pdf file in java with alternate colored rows and picture at the top

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

Categories

Resources