package com.jerry.examagency;
import com.itextpdf.text.*;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by guoy on 2017/2/10.
* jar版本:poi-3.9-20121203.jar, poi-ooxml-3.9-20121203.jar,
* poi-ooxml-schemas-3.9-20121203.jar, itextpdf-5.5.9.jar, itext-asian-5.2.0.jar
* 初步实现IText转pdf的功能
* 注:由于excel中style样式和itext中样式映射上有区别,
* 比如excel读出来字体是20,设置itext对象为20,然而生成出来的字体却偏大到22的样子
*/
public class ITextPdfUtil {
public static void main(String[] args) {
String filepath = "C:\\Users\\igiroad\\Desktop\\申请汇总表 (3).xls";
String pdffilepath = doConvertPdf(filepath, "testtitle", "me", "me write", "me me", "me", true);
doAddWaterMark(pdffilepath, "我是谁?我是谁?我是谁?我是谁?我是谁?", 38, "255, 200, 0", "200, 150", 10);
doAddPicMark(pdffilepath, "D:\\Documents\\Pictures\\cry.jpg", "110, 110", "595, 842");
System.out.println(pdffilepath);
}
public static String doConvertPdf(String excelFilePath, String title, String author, String subject,
String keyword, String creator, boolean isA4Rotate) {
StringBuilder sb = new StringBuilder();
InputStream is = null;
try {
File excelFile = new File(excelFilePath);
if (!excelFile.exists()) {
return null;
}
String folderName = excelFile.getName().substring(0, excelFile.getName().lastIndexOf("."));
File folderFile = new File(excelFile.getParentFile().getAbsolutePath() + File.separator + folderName);
if (!folderFile.exists()) {
folderFile.mkdirs();
}
is = new FileInputStream(excelFilePath);
Workbook wb = WorkbookFactory.create(is);
int sheetNum = wb.getNumberOfSheets();
for (int m = 0; m < sheetNum; m++) {
Sheet sheet = wb.getSheetAt(m);
String pdfFilePath = folderFile.getAbsolutePath() + File.separator
+ excelFile.getName() + "-" + (m + 1) + ".pdf";
excelSheetToPdf(m, sheet, pdfFilePath, title, author, subject, keyword, creator, isA4Rotate);
sb.append(sb.length() == 0 ? "" : ",").append(pdfFilePath);
}
return sb.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
private static void excelSheetToPdf(int sheetIndex, Sheet sheet, String pdfFilePath,
String title, String author, String subject, String keyword,
String creator, boolean isA4Rotate)
throws IOException, DocumentException, InvalidFormatException {
Document document = new Document();
OutputStream os = new FileOutputStream(pdfFilePath);
PdfWriter.getInstance(document, os);
document.addTitle(title);//标题
document.addAuthor(author);//作者
document.addSubject(subject);//主题
document.addKeywords(keyword);//关键词
document.addCreator(creator); //创建者
if (isA4Rotate) {
document.setPageSize(PageSize.A4.rotate());//横向
} else {
document.setPageSize(PageSize.A4);//纵向
}
document.open();
//开始转换并添加内容到document
PdfPTable table = sheetToPdfTable(sheetIndex, sheet);
document.add(table);
//关闭文档对象
document.close();
os.close();
}
private static PdfPTable sheetToPdfTable(int sheetIndex, Sheet sheet)
throws BadElementException, IOException {
int rowLength = sheet.getLastRowNum() + 1;//行数
//计算最大总列数
int totalCNum = 0;
for (int i = 0; i < rowLength; i++) {
Row row = sheet.getRow(i);//当前行
if (row == null) {
continue;
}
totalCNum = row.getLastCellNum() > totalCNum ? row.getLastCellNum() : totalCNum;
}
System.out.println("sheetIndex=" + (sheetIndex + 1) + " rowLength=" + rowLength + " colLeng=" + totalCNum);
float[] widths = new float[totalCNum];//每列宽度组合
List<PdfPCell> cells = new ArrayList<PdfPCell>();
//依次循环每一行,添加单元格信息
for (int i = 0; i < rowLength; i++) {
Row row = sheet.getRow(i);//当前行
if (row == null) {
for (int j = 0; j < totalCNum; j++) {
int rowspan = 1;
int colspan = 1;
PdfPCell pdfpCell = new PdfPCell();
pdfpCell.setColspan(colspan);
pdfpCell.setRowspan(rowspan);
pdfpCell.setPhrase(new Paragraph(" "));
cells.add(pdfpCell);
}
continue;
}
// System.out.println("totalCNum = " + totalCNum + " row.getLastCellNum() = " + row.getLastCellNum());
for (int j = 0; j < totalCNum; j++) {
Cell cell = row.getCell(j);
int rowspan = 1;
int colspan = 1;
if (cell == null) {
PdfPCell pdfpCell = new PdfPCell();
pdfpCell.setColspan(colspan);
pdfpCell.setRowspan(rowspan);
pdfpCell.setPhrase(new Paragraph(" "));
cells.add(pdfpCell);
continue;
}
if (isUsed(cell, row.getRowNum(), cell.getColumnIndex())) {//该单元格被合并,则跳过
continue;
}
//读取该单元格的信息
cell.setCellType(Cell.CELL_TYPE_STRING);
CellRangeAddress range = getColspanRowspanByExcel(cell, row.getRowNum(), cell.getColumnIndex());
if (range != null) {
rowspan = range.getLastRow() - range.getFirstRow() + 1;
colspan = range.getLastColumn() - range.getFirstColumn() + 1;
} else {
float cw = getPOIColumnWidth(cell);
widths[j] = cw;
}
//PDF单元格
PdfPCell pdfpCell = new PdfPCell();
pdfpCell.setBackgroundColor(new BaseColor(getBackgroundColorByExcel(cell.getCellStyle())));
pdfpCell.setColspan(colspan);
pdfpCell.setRowspan(rowspan);
pdfpCell.setVerticalAlignment(getVAlignByExcel(cell.getCellStyle().getVerticalAlignment()));//设置单元格垂直方向对其方式
pdfpCell.setHorizontalAlignment(getHAlignByExcel(cell.getCellStyle().getAlig
没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
IText5 Excel转pdf ,带有添加文字水印,图片水印实例。 * jar版本:poi-3.9-20121203.jar, poi-ooxml-3.9-20121203.jar, * poi-ooxml-schemas-3.9-20121203.jar, itextpdf-5.5.9.jar, itext-asian-5.2.0.jar 文件中含有依赖的jar,代码,下载后你直接可以用了,花了2天时间整理完成。 共3个方法,一个是生成pdf,第2个是加文字水印,第3个是加图片水印 public static void main(String[] args) { String filepath = "C:\\Users\\igiroad\\Desktop\\申请汇总表 (3).xls"; String pdffilepath = doConvertPdf(filepath, "testtitle", "me", "me write", "me me", "me", true); doAddWaterMark(pdffilepath, "我是谁?我是谁?我是谁?我是谁?我是谁?", 38, "255, 200, 0", "200, 150", 10); doAddPicMark(pdffilepath, "D:\\Documents\\Pictures\\cry.jpg", "110, 110", "595, 842"); System.out.println(pdffilepath); }
资源推荐
资源详情
资源评论
收起资源包目录
ITextToPdf.rar (6个子文件)
poi-ooxml-schemas-3.9-20121203.jar 4.58MB
ITextPdfUtil.java 24KB
poi-ooxml-3.9-20121203.jar 915KB
itextpdf-5.5.9.jar 2.18MB
poi-3.9-20121203.jar 1.78MB
itext-asian-5.2.0.jar 2.07MB
共 6 条
- 1
资源评论
- weixin_440652072018-12-26感謝LZ收集,谢谢分享.
- qq_168875592022-03-14getRGB 方法报空指针异常,这个怎么处理啊
eastflowing
- 粉丝: 1
- 资源: 15
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功