Code Snippet

Just another Code Snippet site

[Java] Convert Excel file to PDF


    public static void main(String[] args) throws Exception {

        // First we read the Excel file in binary format into FileInputStream
        FileInputStream input_document =
                new FileInputStream(new File("...Report.xlsx"));

        // Read workbook into HSSFWorkbook
        XSSFWorkbook my_xls_workbook = new XSSFWorkbook(input_document);

        // Read worksheet into HSSFSheet
        XSSFSheet my_worksheet = my_xls_workbook.getSheetAt(0);

        // To iterate over the rows
        Iterator<Row> rowIterator = my_worksheet.iterator();

        // We will create output PDF document objects at this point
        Document iText_xls_2_pdf = new Document();
        PdfWriter.getInstance(iText_xls_2_pdf, new FileOutputStream(
                "...Report.pdf"));
        iText_xls_2_pdf.open();

        // we have two columns in the Excel sheet, so we create a PDF table with two columns
        // Note: There are ways to make this dynamic in nature, if you want to.
        PdfPTable pdfTable = new PdfPTable(2);

        // We will use the object below to dynamically add new data to the table
        PdfPCell pdfCell;

        // Loop through rows.
        while (rowIterator.hasNext()) {
            Row excelRow = rowIterator.next();
            Iterator<Cell> cellIterator = excelRow.cellIterator();
            while (cellIterator.hasNext()) {
                Cell excelCell = cellIterator.next(); // Fetch CELL
                switch (excelCell.getCellType()) { // Identify CELL type
                // you need to add more code here based on
                // your requirement / transformations
                    case Cell.CELL_TYPE_STRING:
                        // Push the data from Excel to PDF Cell
                        pdfCell = new PdfPCell(new Phrase(excelCell.getStringCellValue()));
                        // feel free to move the code below to suit to your needs
                        pdfTable.addCell(pdfCell);

                        break;
                }
                // next line
            }
        }

        // Finally add the table to PDF document
        iText_xls_2_pdf.add(pdfTable);

        // close files
        iText_xls_2_pdf.close();
        input_document.close();
    }

dependencies :

	<dependency>
		<groupId>com.itextpdf</groupId>
		<artifactId>itextpdf</artifactId>
		<version>5.3.4</version>
	</dependency>

	<dependency>
		<groupId>org.apache.poi</groupId>
		<artifactId>poi</artifactId>
		<version>3.8</version>
	</dependency>
	
	<dependency>
		<groupId>org.apache.poi</groupId>
		<artifactId>poi-ooxml</artifactId>
		<version>3.8</version>
	</dependency>


Comments are currently closed.