export resultset to a text file in java with dialog - java

i am having a resultset and i have to write all the data available in resultset to a text file and populate the same to user for downloading.
i have done the below code to export to excel using poi, same way how to do for text file.
if(exportTo.equals("excel"))
{
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment; filename=\"" + reportName + ".xls\"");
try {
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet(reportName);
HSSFRow row = null;
HSSFHeader header = sheet.getHeader();
header.setCenter("POC");
header.setLeft("POC");
header.setRight(HSSFHeader.font("Stencil-Normal", "Italic") +
HSSFHeader.fontSize((short) 16) + reportName);
//to add water mark
/*HSSFPatriarch dp = sheet.createDrawingPatriarch();
HSSFClientAnchor anchor = new HSSFClientAnchor
(0, 0, 1023, 255, (short) 2, 4, (short) 13, 26);
HSSFTextbox txtbox = dp.createTextbox(anchor);
HSSFRichTextString rtxt = new HSSFRichTextString("POC");
HSSFFont draftFont = hwb.createFont();
draftFont.setColor((short) 27);
draftFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
draftFont.setFontHeightInPoints((short) 192);
draftFont.setFontName("Verdana");
rtxt.applyFont(draftFont);
txtbox.setString(rtxt);
txtbox.setLineStyle(HSSFShape.LINESTYLE_NONE);
txtbox.setNoFill(true);*/
HSSFCellStyle style = hwb.createCellStyle();
style.setBorderTop((short) 6); // double lines border
style.setBorderBottom((short) 1); // single line border
style.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);
HSSFFont font = hwb.createFont();
font.setBoldweight((short) 700);
// Create Styles for sheet.
HSSFCellStyle headerStyle = hwb.createCellStyle();
headerStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
headerStyle.setFont(font);
headerStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
headerStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
headerStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
headerStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
headerStyle.setAlignment((short) 2);
// create Title for the sheet
HSSFCellStyle titleStyle = hwb.createCellStyle();
HSSFFont titleFont = hwb.createFont();
titleFont.setFontName(HSSFFont.FONT_ARIAL);
titleFont.setFontHeightInPoints((short) 15);
titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
titleFont.setColor(HSSFColor.BLUE.index);
titleStyle.setFont(titleFont);
titleStyle.setAlignment((short)2);
row = sheet.createRow((short)1);
HSSFCell secondCell = row.createCell((short) 0);
secondCell.setCellValue(new HSSFRichTextString(reportName).toString());
secondCell.setCellStyle(titleStyle);
sheet.addMergedRegion(new Region(1, (short)0, 1, (short)headerCount));
int sno=0;
HSSFRow rowhead = sheet.createRow((short)4);
for (Iterator it = headerMap.keySet().iterator(); it.hasNext();) {
String headerName = (String) headerMap.get(it.next());
HSSFCell headerCell = rowhead.createCell((short)sno);
headerCell.setCellStyle(headerStyle);
headerCell.setCellValue(headerName);
sno++;
}
HSSFCellStyle rowStyle=hwb.createCellStyle();
rowStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
rowStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
rowStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
rowStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
rowStyle.setAlignment((short) 2);
row = custDAO.creadExcelTable(query, sheet, row,rowStyle);
hwb.write(response.getOutputStream());
response.flushBuffer();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public HSSFRow creadExcelTable(String query,HSSFSheet sheet,HSSFRow row,HSSFCellStyle rowStyle ){
int numberOfColumns=0,sno=0,index=5,iterator=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();
int i =0;
while (reportTable_rst.next()) {
row = sheet.createRow((short)index);
sheet.setColumnWidth((short)index, (short)100);
/* if(i == 0){
i = 1;
rowStyle.setFillForegroundColor(HSSFColor.BLUE_GREY.index);
rowStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
System.out.println("BLUE_GREY");
}
else {
i = 0;
System.out.println("LEMON");
rowStyle.setFillForegroundColor(HSSFColor.LEMON_CHIFFON.index);
rowStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
}*/
HSSFCell serialCell = row.createCell((short)sno);
serialCell.setCellStyle(rowStyle);
serialCell.setCellValue(iterator);
for (int columnIterator = 1; columnIterator <= numberOfColumns; columnIterator++) {
String column = reportTable_rst.getString(columnIterator);
sheet.setColumnWidth((short)columnIterator, (short)3000);
HSSFCell rowCell = row.createCell((short)columnIterator);
rowCell.setCellStyle(rowStyle);
rowCell.setCellValue(column);
}
index++;
iterator++;
}
} catch (Exception ex) {
ex.printStackTrace();
}finally {
try {
closeConnection(connection, null, null);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return row;
}
now i have done updto this and really don't know how to go about
if(exportTo.equals("text")){
response.setContentType("text/plain");
response.setHeader("Content-disposition", "attachment; filename=\"" + reportName + ".txt\"");
try {
} catch (Exception e) {
// TODO: handle exception
}
}
this one for creating file in a specified location
Writer writer = null;
try {
String text = "This is a text file";
File file = new File("write.txt");
writer = new BufferedWriter(new FileWriter(file));
writer.write(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
but i want to export the file with dialog, Please help me how to go about.
Regards

I suppose you don't get a dialog box, because your browser can handle text files by itself.
The browser reads the MIME type of the http response (which has been set with response.setContentType("text/plain");)
Most browsers open html, images and text themselves and redirect other file types like audio, pdf's or Office documents to other applications.
So you may need to adjust your browser settings.

Related

Export Java Swing JTable header to Excel

In my application, I have exported the table content to Excel already, but the result excludes the table header. Wondering how to export JTable to Excel include the table header? I tried couple ways, but still can not see the table header in excel, the following is my code:
defautTableModel = new DefaultTableModel(null,columnNames){
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
// the jTable row are generated dynamically.
final JTable jTable = new JTable(defautTableModel);
jTable.setLocation(20,60);
jTable.setSize(950,450);
jTable.setRowHeight(25);
JTableHeader jTableHeader = jTable.getTableHeader();
jTableHeader.setLocation(20,30);
jTableHeader.setSize(950,30);
jTableHeader.setFont(new Font(null, Font.BOLD, 16));
jTableHeader.setResizingAllowed(true);
jTableHeader.setReorderingAllowed(true);
jTable.add(jTableHeader);
JScrollPane tablePanel = new JScrollPane(jTable);
tablePanel.setLocation(10,10);
tablePanel.setSize(960,400);
// export data to excel method
public void exportToExcel(){
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
for (int i = 0; i < defautTableModel.getRowCount(); i++) {
Row = sheet.createRow(i);
for (int j = 0; j < defautTableModel.getColumnCount(); j++) {
Cell = Row.createCell(j);
try {
if (defautTableModel.getValueAt(i,j) != null){
Cell.setCellValue(defautTableModel.getValueAt(i,j).toString());
FileOutputStream fileOut = new FileOutputStream(Constant.Path_TestData_Output);
wb.write(fileOut);
fileOut.flush();
fileOut.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
You are only accessing the data columns and you need to get the header ones first.
You can acheive it by different means, either you use the method getColumnName
as ThomasEdwin mentioned in his comment or use columnNames variable that you have provided to your model constructor: new DefaultTableModel(null,columnNames)
Hope it helps
Export Java Swing JTable header with JTable index to Excel
private static void writeToExcell(DefaultTableModel TabR ,TableColumnModel tableM) throws IOException {
try
{
JFileChooser fileChooser = new JFileChooser();
int retval = fileChooser.showSaveDialog(fileChooser);
if (retval == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (file != null) {
if (!file.getName().toLowerCase().endsWith(".xls")) {
file = new File(file.getParentFile(), file.getName() + ".xls");
#SuppressWarnings("resource")
Workbook wb = new HSSFWorkbook();
#SuppressWarnings("unused")
CreationHelper createhelper = wb.getCreationHelper();
org.apache.poi.ss.usermodel.Sheet sheet = wb.createSheet();
org.apache.poi.ss.usermodel.Row row = null;
org.apache.poi.ss.usermodel.Cell cell = null;
for (int a=0;a<TabR.getRowCount();a++)
{
row = sheet.createRow(a+1); /* We create an Excel layer Row.
We understand how many rows are in
TabR with GetRowCount from TabR, the
DefaultTableModel of the current JTable,
and add one to it.*/
for (int b=0;b<tableM.getColumnCount();b++)
{
cell = row.createCell(b);/* With the GetColumnCount
function of the existing JTable's
TableColumnModel, we create more
Column in the JTable.*/
cell.setCellValue(TabR.getValueAt(a, b).toString()); /*we give the value of the cell. */
}
}
for (int c=0;c<cell.getRowIndex();c++)
{
row = sheet.createRow(c);
for (int d=0;d<tableM.getColumnCount();d++)
{
cell = row.createCell(d);
cell.setCellValue(tableM.getColumn(d).getHeaderValue().toString());
}
}
FileOutputStream out = new FileOutputStream(file);
wb.write(out);
out.close();
}
}
}
} catch (FileNotFoundException ex) {
Logger.getLogger(B_anaEk.class.getName()).log(Level.ALL, null, ex);
} catch (IOException ex) {
Logger.getLogger(B_anaEk.class.getName()).log(Level.ALL, null, ex);
}

Opening Excel documents as soon as they are created using POI in Android

I've made a document using POI and its name is"Budget.xls". It gets saved in the Android folder of my phone. specifically Android/data/com.playmaker.BudgetOh/files/. But i want it to open as soon as it is created. But it doesnt seem to be working. Please help me out. Thank you.
saveExcelFile(this,"Budget.xls");// This is a method that creates the file
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()
+ "/Budget.xls/");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "Budget.xls");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
//startActivity(Intent.createChooser(intent, "Open folder"));
}
catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "No Application Available to View Excel", Toast.LENGTH_SHORT).show();
}
this is my code for the saveExcelFile()
private boolean saveExcelFile(Context context, String fileName) {
// check if available and not read only
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
Log.e(TAG, "Storage not available or read only");
Toast.makeText(MainActivity.this, "Storage not available or read only", Toast.LENGTH_LONG).show();
return false;
}
boolean success = false;
//New Workbook
Workbook wb = new HSSFWorkbook();
Cell c = null;
//Cell style for header row
CellStyle cs = wb.createCellStyle();
cs.setFillForegroundColor(HSSFColor.LIME.index);
cs.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
//New Sheet
Sheet sheet1 = null;
sheet1 = wb.createSheet("myOrder");
// Generate column headings
Row row = sheet1.createRow(0);
//Row row2 = sheet1.createRow(1);
c = row.createCell(0);
c.setCellValue("Expense Title");
c.setCellStyle(cs);
c = row.createCell(1);
c.setCellValue("Expense Amount");
c.setCellStyle(cs);
c = row.createCell(2);
c.setCellValue("Categories");
c.setCellStyle(cs);
c = row.createCell(3);
c.setCellValue("Date");
c.setCellStyle(cs);
c = row.createCell(4);
c.setCellValue("Time");
c.setCellStyle(cs);
c = row.createCell(5);
c.setCellValue("Location");
c.setCellStyle(cs);
String title;
int counter=0;
allExpenses = expenseManager.getAllExpenses();
for (Expense expense : allExpenses) {
allTitles.add(expense.getTitle());
counter++;
}
Row row2 = sheet1.createRow(1);
int k=1;
for ( int i=0; i < counter; i++) {
title=allTitles.get(i);
//Toast.makeText(getApplicationContext(),i, Toast.LENGTH_SHORT).show();
expense = expenseManager.getExpense(title);
int j = 0;
c = row2.createCell(j);
c.setCellValue(expense.getTitle());
// c.setCellStyle(cs);
c = row2.createCell(j+1);
c.setCellValue(expense.getAmount());
//c.setCellStyle(cs);
c = row2.createCell(j+2);
c.setCellValue(expense.getCategory());
// c.setCellStyle(cs);
c = row2.createCell(j+3);
c.setCellValue(expense.getDate());
//c.setCellStyle(cs);
c = row2.createCell(j+4);
c.setCellValue(expense.getTime());
//c.setCellStyle(cs);
c = row2.createCell(j+5);
c.setCellValue(expense.getComment());
// c.setCellStyle(cs);
row2 = sheet1.createRow(k++);
}
sheet1.setColumnWidth(0, (15 * 500));
sheet1.setColumnWidth(1, (15 * 500));
sheet1.setColumnWidth(2, (15 * 500));
// Create a path where we will place our List of objects on external storage
File file = new File(context.getExternalFilesDir(null), fileName);
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
wb.write(os);
Log.w("FileUtils", "Writing file" + file);
Toast.makeText(MainActivity.this, "Writing file", Toast.LENGTH_LONG).show();
success = true;
} catch (IOException e) {
Log.w("FileUtils", "Error writing " + file, e);
Toast.makeText(MainActivity.this, "Error writing", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.w("FileUtils", "Failed to save file", e);
Toast.makeText(MainActivity.this, "Error writing", Toast.LENGTH_LONG).show();
} finally {
try {
if (null != os)
os.close();
} catch (Exception ex) {
}
}
return success;
}
intent.setDataAndType(uri, "Budget.xls");
Budget.xls is not a valid MIME type. Use application/vnd.ms-excel for the MIME type for Excel spreadsheets.
Also, replace:
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()
+ "/Budget.xls/");
with:
Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "Budget.xls"));
Partly, this gets rid of the invalid trailing /. Partly, this adds the file scheme that your approach lacks.

How to open a excel file that has been exported from java arraylist

I've a web project, where grid view is displayed from database. Arraylist name is leadSchoolList. So, I kept a button, when clicked it runs a method(named:-actionExportToExcel) in Struts action class. Right now I am able to export list elements to excel.
But the problem I'm facing is opening up that exported excel Sheet on window. So another method(named:-open) is called inside actionExportToExcel. But I don't know where I'm wrong, so can anyone help me?
public String actionExportToExcel(){
try {
FileOutputStream fileOut = new FileOutputStream("D:/poi-test.xls");
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
leadSchoolList = leadSchoolService.getAllLeadSchool();
for(int rowNum = 0; rowNum < leadSchoolList.size(); rowNum++){
HSSFRow row = sheet.createRow(rowNum);
//for(int colNum = 0; colNum < 5; colNum++ ){
HSSFCell cell1 = row.createCell(0);
LeadSchool leadSchool = leadSchoolList.get(rowNum);
cell1.setCellValue(leadSchool.getLeadSchool_String_LSchool_ID());
HSSFCell cell2 = row.createCell(1);
cell2.setCellValue(leadSchool.getLeadSchool_String_Name());
HSSFCell cell3 = row.createCell(2);
cell3.setCellValue(leadSchool.getLeadSchool_String_Address());
HSSFCell cell4 = row.createCell(3);
cell4.setCellValue(leadSchool.getLeadSchool_String_Phone_No());
HSSFCell cell5 = row.createCell(4);
cell5.setCellValue(leadSchool.getLeadSchool_String_Remarks());
System.out.println("Successfully exported to Excel");
}
try {
wb.write(fileOut);
// fileOut.flush();
open(fileOut);
//fileOut.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
addActionError("The process cannot access the file because it is being used by another process");
e.printStackTrace();
}
return SUCCESS;
}
private void open(FileOutputStream f) {
String[] cmd = new String[4];
try{
cmd[0] = "cmd.exe";
cmd[1] = "/C";
cmd[2] = "start";
cmd[3] = "D:/poi-test.xls";
Runtime.getRuntime().exec(cmd);
//Runtime.getRuntime().exec("cmd.exe /c start D:/poi-test.xls");
System.out.print("file opened");
}
catch(Exception e){
e.printStackTrace();
}
}
Fortunately found the solution myself. .First need to run flush() and close() method and then the second(named:-open) method. Inside open method, instead of R
Runtime.getRuntime().exec(cmd);
i expanded it into two lines:-
Runtime run = Runtime.getRuntime();
Run.exec(cmd);
Thats it..:D

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