본문

JAVA EXCEL을 PDF로 변환하기

반응형

이 글은 java에서 excel 파일을 pdf로 변환하는 방법을 정리한다.

 

 

1. 라이브러리 추가

-. apache POI 3.8, iText v5.3.4

<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>itextpdf</artifactId>
	<version>5.3.4</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
	<groupId>org.apache.poi</groupId>
	<artifactId>poi</artifactId>
	<version>3.15</version>
</dependency>


2. Java Apache POI Excel save as PDF

Try this Example to convert XLS to PDF

The complete Java code that accepts Excel spreadsheet data as an input and transforms that to a PDF table data is provided below:

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"));
		
		// Read workbook into HSSFWorkbook
		HSSFWorkbook my_xls_workbook = new HSSFWorkbook(input_document); 
		
		// Read worksheet into HSSFSheet
		HSSFSheet 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("Excel2PDF_Output.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 my_table = new PdfPTable(2);
		
		// We will use the object below to dynamically add new data to the table
		PdfPCell table_cell;
		
		// Loop through rows.
		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
					//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
                        			//feel free to move the code below to suit to your needs
						table_cell=new PdfPCell(new Phrase(cell.getStringCellValue()));
						my_table.addCell(table_cell);
						break;
				}
			}

		}
		
		// Finally add the table to PDF document
		iText_xls_2_pdf.add(my_table);                       
		iText_xls_2_pdf.close();                
		
		// we created our pdf file..
		input_document.close(); //close xls
	}
}

 

 

 

 

 


💡 참고

https://stackoverflow.com/questions/26056485/java-apache-poi-excel-save-as-pdf

 

 

반응형

공유

댓글