基本原理
將excel單元格的值讀取出來,然後生成一份pdf,並將單元格數據寫進去。
用到的庫
<!-- 寫入pdf用的庫 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<!-- 讓PDF支持中文寫入 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<!-- 操作excel的庫 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.0</version>
</dependency>
具體操作
package com.example.demo;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
public class DemoApplication {
public static void main(String[] args) throws Exception{
//excel文件路徑
String excelFile = "C:\\Users\\admin\\Desktop\\source1.xls";
//pdf文件輸出路徑
String out = "C:\\Users\\admin\\Desktop\\out.pdf";
//設置中文
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
BaseFont.NOT_EMBEDDED);
//普通字體
Font fontChinese = new Font(bfChinese, 12, Font.NORMAL);
//讀取excel
FileInputStream input_document = new FileInputStream(new File(excelFile));
HSSFWorkbook my_xls_workbook = new HSSFWorkbook(input_document);
HSSFSheet my_worksheet = my_xls_workbook.getSheetAt(0);
//獲取excel總列數
int totalCol = my_worksheet.getRow(0).getPhysicalNumberOfCells();
//準備遍歷excel
Iterator<Row> rowIterator = my_worksheet.iterator();
//生成一個pdf
Document iText_xls_2_pdf = new Document();
PdfWriter.getInstance(iText_xls_2_pdf, new FileOutputStream(out));
iText_xls_2_pdf.open();
//在pdf中創建一個表格
PdfPTable my_table = new PdfPTable(totalCol);
//遍歷excel, 將數據輸出到pdf的表格中
PdfPCell table_cell = null;
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next(); //Fetch CELL
if(cell.getCellType() == CellType.STRING){
//Push the data from Excel to PDF Cell
table_cell=new PdfPCell(new Phrase(cell.getStringCellValue(), usedFont));
}
if(cell.getCellType() == CellType.NUMERIC){
//Push the data from Excel to PDF Cell
table_cell=new PdfPCell(new Phrase(String.valueOf(cell.getNumericCellValue()), usedFont));
}
my_table.addCell(table_cell);
}
}
iText_xls_2_pdf.add(my_table);
iText_xls_2_pdf.close();
input_document.close(); //close xls
}
}