PdfPTable table = new PdfPTable(4); // 4 columns.
PdfPCell cell1 = new PdfPCell(new Paragraph("Medicine Name"));
PdfPCell cell2 = new PdfPCell(new Paragraph("Quantity"));
PdfPCell cell3 = new PdfPCell(new Paragraph("Price"));
PdfPCell cell4 = new PdfPCell(new Paragraph("Total"));
table.addCell(cell1);
table.addCell(cell2);
table.addCell(cell3);
table.addCell(cell4);
while(rs.next()) // fetch & writing records in pdf files
{
quan=rs.getInt("quantity");
pric=rs.getDouble("price");
total=quan*pric;
cell1 = new PdfPCell(new Paragraph(rs.getString("prodt_name")));
cell2 = new PdfPCell(new Paragraph(quan));
cell3 = new PdfPCell(new Paragraph(rs.getString("price")));
cell4 = new PdfPCell(new Paragraph(total));
table.addCell(cell1);
table.addCell(cell2);
table.addCell(cell3);
table.addCell(cell4);
}
total is double value and Paragraph consturctor doesn't accept double value.
so how can i insert double value in pdfpcell
Try String.valueOf
cell4 = new PdfPCell(new Paragraph(String.valueOf(total)));
String.valueOf(double) returns the string representation of the double argument. Please see the official documentation for more information.
Related
I'm using iText to create a PDF in my java spring mvc web project. I'm new to iText 5. Could anyone tell me how to add a text field under a paragraph? Based on my current code, the text field is not displayed under the paragraph. I may add more questions to the PDF so I want to display each text field under the paragraph.
try {
List<FormQuestionBean> questions = formBuilderBean.getQuestions();
MyHeaderAndFooter event = new MyHeaderAndFooter();
Document pdfDocument = new Document(PageSize.A4);
pdfDocument.setMargins(20, 20, 20, 30);
ByteArrayOutputStream pdfBaos = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(pdfDocument, pdfBaos);
writer.setPageEvent(event);
pdfDocument.open();
Paragraph paragraph1 = new Paragraph(FORM_NAME + " : " + formBuilderBean.getName(), HEADING);
paragraph1.setSpacingAfter(20);
pdfDocument.add(paragraph1);
for (FormQuestionBean formQuestionBean: questions) {
if (formQuestionBean.getFieldImplementation().contentEquals("Text Field")) {
Paragraph p = new Paragraph(formQuestionBean.getName());
pdfDocument.add(p);
TextField text = new TextField(writer, new Rectangle(36, 788, 559, 806), "text" );
text.setBackgroundColor(BaseColor.WHITE);
PdfFormField field = text.getTextField();
writer.addAnnotation(field);
}
}
pdfDocument.close();
response.reset();
response.setHeader("Content-Length", String.valueOf(pdfBaos.size()));
response.setContentType("application/pdf");
response.setContentLength(pdfBaos.size());
String downloadName = getFormFileName(".pdf");
response.setHeader("Content-Disposition", "attachment; filename=\"" + downloadName + "\"");
OutputStream outputStream = response.getOutputStream();
pdfBaos.writeTo(outputStream);
outputStream.flush();
outputStream.close();
return true;
} catch (Exception e) {
logger.error(e);
e.printStackTrace();
return false;
}
I figured out using table and cell. Below is the code:
try {
List<FormQuestionBean> questions = formBuilderBean.getQuestions();
MyHeaderAndFooter event = new MyHeaderAndFooter();
Document pdfDocument = new Document(PageSize.A4);
pdfDocument.setMargins(20, 20, 20, 30);
ByteArrayOutputStream pdfBaos = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(pdfDocument, pdfBaos);
writer.setPageEvent(event);
pdfDocument.open();
Paragraph paragraph1 = new Paragraph(FORM_NAME + " : " + formBuilderBean.getName(), HEADING);
paragraph1.setSpacingAfter(20);
pdfDocument.add(paragraph1);
for (FormQuestionBean formQuestionBean: questions) {
if (formQuestionBean.getFieldImplementation().contentEquals("Text Field")) {
PdfPTable table = new PdfPTable(1);
table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
PdfPCell c1 = new PdfPCell(new Phrase(formQuestionBean.getName()));
c1.setFixedHeight(30);
table.addCell(c1);
PdfPCell c2 = new PdfPCell();
TextField text = new TextField(writer, c2, "text" );
text.setBackgroundColor(BaseColor.WHITE);
FieldPositioningEvents events = new FieldPositioningEvents(writer, text.getTextField());
c2.setCellEvent(events);
c2.setFixedHeight(30);
table.addCell(c2);
pdfDocument.add(table);
}
}
pdfDocument.close();
response.reset();
response.setHeader("Content-Length", String.valueOf(pdfBaos.size()));
response.setContentType("application/pdf");
response.setContentLength(pdfBaos.size());
String downloadName = getFormFileName(".pdf");
response.setHeader("Content-Disposition", "attachment; filename=\"" + downloadName + "\"");
OutputStream outputStream = response.getOutputStream();
pdfBaos.writeTo(outputStream);
outputStream.flush();
outputStream.close();
return true;
} catch (Exception e) {
logger.error(e);
e.printStackTrace();
return false;
}
I have a requirement to generated the PDF using itext in java
Need to generate the table with 3 rows and 2 columns , able to create the table.
Country Langugage
USA English
Canada French
When I was trying to read the pdf VIA NVDA Desktop App , the table is not reading the cells properly , say when I want to focus the pointer on Canada , it should the Country - Canada
Following is the code
public class Test {
public static final String CSS = "tr { text-align: center; } th { background-color: lightgreen; padding: 3px; } td {background-color: lightblue; padding: 3px; }";
public static void main(String sunil[])
{
String pFileName = "Test.pdf";
String pFilePath = "C:/local/home/dna/pushlive/" + pFileName;
try {
FileOutputStream baosPDF = new FileOutputStream(pFilePath);
com.itextpdf.text.Rectangle pageSize = new com.itextpdf.text.Rectangle(1836, 2376);
com.itextpdf.text.Document document = new com.itextpdf.text.Document(pageSize, 36, 36, 36, 36);
PdfWriter writer = PdfWriter.getInstance(document, baosPDF);
writer.setTagged();
document.open();
PdfPTable bannerTable = new PdfPTable(4);
document.add(createFirstTable());
document.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static PdfPTable createFirstTable() {
// a table with three columns
PdfPTable table = new PdfPTable(2);
// the cell object
PdfPCell cell;
// we add a cell with colspan 3
//create header cell for first row
// now we add a cell with rowspan 2
//add metadata for each cell in the body.
// we add the four remaining cells with addCell()
cell = new PdfPCell(new Phrase("Country"));
table.addCell(cell);
cell = new PdfPCell(new Phrase("Language"));
table.addCell(cell);
cell = new PdfPCell(new Phrase("USA"));
table.addCell(cell);
cell = new PdfPCell(new Phrase("English"));
table.addCell(cell);
cell = new PdfPCell(new Phrase("Canada"));
table.addCell(cell);
cell = new PdfPCell(new Phrase("French"));
table.addCell(cell);
//set header row for the table
table.setHeaderRows(1);
return table;
}
the following code does produce the table and the nested table.
However, the nested table is always aligned in the middle.
I have no clue how to achieve horizontal alignment properly.
The following method is simply looping through a list.
when it's a simple question, I will add an TextField.
if it's a question containing multiple answers, i will inject a nested table with the checkboxes and the values.
private PdfPTable CreateQuestionTable(RLQuestionRecordList questions)
{
PdfPCell cell;
PdfPTable table = new PdfPTable(2);
//table.SetWidths(new int[]{ 50, 50 });
table.WidthPercentage = 100;
table.SpacingBefore = 20;
table.SpacingAfter = 20;
table.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
foreach (RCQuestionRecord q in questions)
{
//add question to the table
cell = new PdfPCell(new Phrase(q.ssSTQuestion.ssName, _Normal));
cell.Border = Rectangle.NO_BORDER;
cell.Padding = 5.0f;
table.AddCell(cell);
//add answer to the table.
//add generate time we don;t know where the table will be,
//hence textfields will be generated after the pdf has been generated..
if (q.ssSTQuestion.ssListOfAnswers.Length > 0)
{
// we have radiobuttons, so we add a table inside the cell
cell = new PdfPCell();
cell.Border = Rectangle.NO_BORDER;
cell.Padding = 5.0f;
//we cannot align the table to the left in the cell for some weird reason...
cell.HorizontalAlignment = Element.ALIGN_LEFT;
cell.AddElement(CreateCheckboxTable(q));
table.AddCell(cell);
}
else
{
// we have simple textfield, so add that to the cell
cell = new PdfPCell();
cell.Border = Rectangle.NO_BORDER;
cell.Padding = 5.0f;
cell.HorizontalAlignment = Element.ALIGN_LEFT;
//simple textfield
cell.CellEvent = new OOMTextField(string.Format("question_{0}", q.ssSTQuestion.ssQuestionId), q.ssSTQuestion.ssLength, q.ssSTQuestion.ssValue, bf);
table.AddCell(cell);
}
}
return table;
}
This is the nested table I want to insert into the cell above.
/// <summary>
///
/// </summary>
/// <param name="question"></param>
/// <returns></returns>
private PdfPTable CreateCheckboxTable(RCQuestionRecord question)
{
PdfPCell cell;
int numCells = question.ssSTQuestion.ssListOfAnswers.Length;
PdfPTable table = new PdfPTable(numCells);
float[] widths = new float[numCells];
int currentColumn = 0;
//table.SetWidths(new int[]{ 50, 50 });
foreach (RCAnswerRecord a in question.ssSTQuestion.ssListOfAnswers) {
//checkbox
cell = new PdfPCell(new Phrase(a.ssSTAnswer.ssLabel, _Normal));
cell.Border = Rectangle.NO_BORDER;
cell.Padding = 0.0f;
cell.PaddingLeft = 20.0f;
cell.HorizontalAlignment = Element.ALIGN_LEFT;
cell.VerticalAlignment = Element.ALIGN_CENTER;
cell.CellEvent = new OOMCheckBox(string.Format("question_{0}", question.ssSTQuestion.ssQuestionId), a.ssSTAnswer.ssIsSelected, a.ssSTAnswer.ssLabel, bf);
//checkbox
table.AddCell(cell);
widths[currentColumn++] = 20.0f + bf.GetWidthPoint(a.ssSTAnswer.ssLabel, 11);
}
table.SetTotalWidth(widths);
table.LockedWidth = true;
table.SpacingBefore = 0;
return table;
}
What am I missing to align the nested tables totally to the left inside the cell?
Please take a look at the PDF document named nested_tables_aligned.pdf:
The outer table in this example has three columns and one row. Each cell in this outer table contains an inner table. The first inner table is left aligned, the second one is center aligned, the third one is right aligned.
This PDF was created with the Java example named NestedTablesAligned:
public void createPdf(String dest) throws IOException, DocumentException {
Document document = new Document(PageSize.A4.rotate());
PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
float[] columnWidths = {200f, 200f, 200f};
PdfPTable table = new PdfPTable(columnWidths);
table.setTotalWidth(600f);
table.setLockedWidth(true);
buildNestedTables(table);
document.add(table);
document.close();
}
private void buildNestedTables(PdfPTable outerTable) {
PdfPTable innerTable1 = new PdfPTable(1);
innerTable1.setTotalWidth(100f);
innerTable1.setLockedWidth(true);
innerTable1.setHorizontalAlignment(Element.ALIGN_LEFT);
innerTable1.addCell("Cell 1");
innerTable1.addCell("Cell 2");
outerTable.addCell(innerTable1);
PdfPTable innerTable2 = new PdfPTable(2);
innerTable2.setTotalWidth(100f);
innerTable2.setLockedWidth(true);
innerTable2.setHorizontalAlignment(Element.ALIGN_CENTER);
innerTable2.addCell("Cell 3");
innerTable2.addCell("Cell 4");
outerTable.addCell(innerTable2);
PdfPTable innerTable3 = new PdfPTable(2);
innerTable3.setTotalWidth(100f);
innerTable3.setLockedWidth(true);
innerTable3.setHorizontalAlignment(Element.ALIGN_RIGHT);
innerTable3.addCell("Cell 5");
innerTable3.addCell("Cell 6");
outerTable.addCell(innerTable3);
}
As you can see, I define the alignment of the table at the level of the table, not at the level of the cell. The sample principle applies to iTextSharp. In you C# example, you define the aligned for the PdfPCell instead of for the PdfPTable. Change this and your problem will be solved.
I need to render each cell values in a new page.
I am using the following code :
List<string> values = getValues(); // getValues() method returns a list of strings
Document doc = new Document();
....
PdfPTable table = new PdfPTable(1);
foreach(var s in values)
{
table.AddCell(s);
doc.NewPage();
}
...
But I am getting the output in a single page.
Add a one-cell table on each page:
List<string> values = getValues(); // getValues() method returns a list of strings
Document doc = new Document();
....
foreach(var s in values)
{
PdfPTable table = new PdfPTable(1);
table.AddCell(s);
doc.add(table);
doc.NewPage();
}
...
I'm producing PDF reports using the iTextSharp library. I have a paragraph as title with a line underneath.
When I add an PdfPageEventHelper class as PageEventListener to my writer which handles the background and page numbering on each page, the line disappears. I think it's about the alignment of the background and the line so the line is behind the background but I can't seem to arrange it in front.
Document code:
using (Document doc = new Document())
{
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=IVIPS_report.pdf");
doc.SetPageSize(PageSize.A4.Rotate());
doc.SetMargins(36f, 36f, 36f, 70f);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
bckgr = Image.GetInstance(Request.MapPath(PDF_BACKGROUND_LANDSCAPE_PATH));
bckgr.Alignment = Image.UNDERLYING;
bckgr.SetAbsolutePosition(0, 0);
bckgr.ScaleToFit(doc.PageSize);
PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);
MyPdfPageEventHelpPageNo PdfPageEvent = new MyPdfPageEventHelpPageNo();
writer.PageEvent = PdfPageEvent;
doc.Open();
Font title = new Font(Font.FontFamily.HELVETICA, 16f, Font.BOLD, BaseColor.DARK_GRAY);
Paragraph p = new Paragraph("Overzicht chauffeurs", title);
p.Alignment = Element.ALIGN_LEFT;
LineSeparator line = new LineSeparator(1f, 100f, BaseColor.DARK_GRAY, Element.ALIGN_CENTER, -27f);
doc.Add(p);
doc.Add(line);
}
PdfPageEvent code:
public class MyPdfPageEventHelpPageNo : iTextSharp.text.pdf.PdfPageEventHelper
{
public override void OnEndPage(PdfWriter writer, Document document)
{
document.Add(bckgr);
Font fFooter = new Font(Font.FontFamily.HELVETICA, 9f, Font.NORMAL, BaseColor.GRAY);
Rectangle page = document.PageSize;
PdfPTable pageFooter = new PdfPTable(1);
pageFooter.TotalWidth = page.Width;
Phrase pagenr = new Phrase("Gegenereerd op " + DateTime.Now.ToString("dd/MM/yyyy") + " - Pagina " + document.PageNumber, fFooter);
PdfPCell c = new PdfPCell(pagenr);
c.Border = Rectangle.NO_BORDER;
c.VerticalAlignment = Element.ALIGN_BOTTOM;
c.HorizontalAlignment = Element.ALIGN_CENTER;
pageFooter.AddCell(c);
pageFooter.WriteSelectedRows(0, -1, 0, 25, writer.DirectContent);
}
}