Prithwin Kumar
Prithwin Kumar

Reputation: 41

Excel to PDF conversion in java

Guys I'm trying to print a report page in java. Here I have an excel file with print format, I have to fill the data to excel and then convert it to pdf for display purpose.

Excel data is successfully edited and saved to a new file. but when I trying to convert the edited file to PDF it lost its format and col span and alignments are not affecting.

Here is my code:

import java.io.FileInputStream;
import java.io.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.usermodel.*;
import java.util.Iterator;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

public class excel2pdf {  
    public static void main(String[] args) throws Exception{
        FileInputStream input_document = new FileInputStream(new File("C:\\excel_to_pdf.xls"));
        HSSFWorkbook my_xls_workbook = new HSSFWorkbook(input_document);
        HSSFSheet my_worksheet = my_xls_workbook.getSheetAt(0); 
        Iterator<Row> rowIterator = my_worksheet.iterator();
        Document iText_xls_2_pdf = new Document();
        PdfWriter.getInstance(iText_xls_2_pdf, new 
        FileOutputStream("Excel2PDF_Output.pdf"));
        iText_xls_2_pdf.open();
        PdfPTable my_table = new PdfPTable(2);
        PdfPCell table_cell;
        while(rowIterator.hasNext()) {
           Row row = rowIterator.next(); 
           Iterator<Cell> cellIterator = row.cellIterator();
           while(cellIterator.hasNext()) {
                Cell cell = cellIterator.next(); //Fetch CELL
                switch(cell.getCellType()) { //Identify CELL type
                case Cell.CELL_TYPE_STRING:
                    table_cell=new PdfPCell(new Phrase(cell.getStringCellValue()));
                    my_table.addCell(table_cell);
                    break;
                }
            }
        }
        iText_xls_2_pdf.add(my_table);                       
        iText_xls_2_pdf.close();                
        input_document.close(); 
    }
}

Upvotes: 1

Views: 1912

Answers (1)

Burak Demirbilek
Burak Demirbilek

Reputation: 89

If you want to keep your table style, I think you should set the style related things in the cell like colspan, border, alignment etc.

Here is an example code to set some style properties to the cell, for example if you want no borders you should set the border to NO_BORDER, I dont know what is like your table so you should set the style properties by yourself.

Also you can check iText5 tables and fonts example page or iText7 tables and fonts example page to get more information.

PdfPTable table = new PdfPTable(10);
PdfPCell cell = new PdfPCell(docTitle);
cell.setColspan(3);
cell.setBorder(PdfPCell.NO_BORDER);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(cell);

Upvotes: 2

Related Questions