标题java用itextPDF生成PDF文件保存至本地并上传至ftp服务器
所需jar :itext-asian-5.2.0.jar,itextpdf-5.5.5.jar,commons-net-3.3.jar 因为上传不了只能这样了
设置页面上的属性,比如页眉页脚之类的
package com.ibm.business.util;
import java.io.IOException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;
/import com.sign.system.PathCons;
import com.sign.util.PathUtil;
/
/
- 设置页面附加属性
*/
public class PDFBuilder extends PdfPageEventHelper {
/**
* 页眉
*/
public String header = "";
/**
* 文档字体大小,页脚页眉最好和文本大小一致
*/
public int presentFontSize = 12;
/**
* 文档页面大小,最好前面传入,否则默认为A4纸张
*/
public Rectangle pageSize = PageSize.A4;
// 模板
public PdfTemplate total;
// 基础字体对象
public BaseFont bf = null;
// 利用基础字体生成的字体对象,一般用于生成中文文字
public Font fontDetail = null;
public PDFBuilder() {
}
/**
*
* Creates a new instance of PdfReportM1HeaderFooter 构造方法.
*
* @param yeMei
* 页眉字符串
* @param presentFontSize
* 数据体字体大小
* @param pageSize
* 页面文档大小,A4,A5,A6横转翻转等Rectangle对象
*/
public PDFBuilder( int presentFontSize, Rectangle pageSize) {
this.presentFontSize = presentFontSize;
this.pageSize = pageSize;
}
public void setHeader(String header) {
this.header = header;
}
public void setPresentFontSize(int presentFontSize) {
this.presentFontSize = presentFontSize;
}
/**
*
* TODO 文档打开时创建模板
*
* @see com.itextpdf.text.pdf.PdfPageEventHelper#onOpenDocument(com.itextpdf.text.pdf.PdfWriter,
* com.itextpdf.text.Document)
*/
public void onOpenDocument(PdfWriter writer, Document document) {
total = writer.getDirectContent().createTemplate(50, 50);// 共 页 的矩形的长宽高
}
/**
*
* TODO 关闭每页的时候,写入页眉,写入'第几页共'这几个字。
*
* @see com.itextpdf.text.pdf.PdfPageEventHelper#onEndPage(com.itextpdf.text.pdf.PdfWriter,
* com.itextpdf.text.Document)
*/
public void onEndPage(PdfWriter writer, Document document) {
this.addPage(writer, document);
// this.addWatermark(writer);
}
//加分页
public void addPage(PdfWriter writer, Document document){
try {
if (bf == null) {
bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
}
if (fontDetail == null) {
fontDetail = new Font(bf, presentFontSize, Font.NORMAL);// 数据体字体
}
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 2.写入前半部分的 第 X页/共
int pageS = writer.getPageNumber();
String foot1 = "第 " + pageS + " 页 /共";
Phrase footer = new Phrase(foot1, fontDetail);
// 3.计算前半部分的foot1的长度,后面好定位最后一部分的'Y页'这俩字的x轴坐标,字体长度也要计算进去 = len
float len = bf.getWidthPoint(foot1, presentFontSize);
// 4.拿到当前的PdfContentByte
PdfContentByte cb = writer.getDirectContent();
// 5.写入页脚1,x轴就是(右margin+左margin + right() -left()- len)/2.0F
// 再给偏移20F适合人类视觉感受,否则肉眼看上去就太偏左了
// ,y轴就是底边界-20,否则就贴边重叠到数据体里了就不是页脚了;注意Y轴是从下往上累加的,最上方的Top值是大于Bottom好几百开外的。
ColumnText
.showTextAligned(
cb,
Element.ALIGN_CENTER,
footer,
(document.rightMargin() + document.right()
+ document.leftMargin() - document.left() - len) / 2.0F + 20F,
document.bottom() - 20, 0);
// 6.写入页脚2的模板(就是页脚的Y页这俩字)添加到文档中,计算模板的和Y轴,X=(右边界-左边界 - 前半部分的len值)/2.0F +
// len , y 轴和之前的保持一致,底边界-20
cb.addTemplate(total, (document.rightMargin() + document.right()
+ document.leftMargin() - document.left()) / 2.0F + 20F,
document.bottom() - 20); // 调节模版显示的位置
}
/**
*
* TODO 关闭文档时,替换模板,完成整个页眉页脚组件
*
* @see com.itextpdf.text.pdf.PdfPageEventHelper#onCloseDocument(com.itextpdf.text.pdf.PdfWriter,
* com.itextpdf.text.Document)
*/
public void onCloseDocument(PdfWriter writer, Document document) {
// 7.最后一步了,就是关闭文档的时候,将模板替换成实际的 Y 值,至此,page x of y 制作完毕,完美兼容各种文档size。
total.beginText();
total.setFontAndSize(bf, presentFontSize);// 生成的模版的字体、颜色
String foot2 = " " + (writer.getPageNumber()-1) + " 页";
total.showText(foot2);// 模版显示的内容
total.endText();
total.closePath();
}
}
二, 生成PDF的方法
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import com.ibm.business.util.PDFBuilder;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class pdf {
private static FTPClient ftp = new FTPClient();
/**
* 生成PDF内容
*/
public static ByteArrayOutputStream T_LOG_RECORD_PREPAIDPDF(String burks,String gonssi,String date){
Document document = new Document();
Rectangle pageSize = new Rectangle(PageSize.A4.getHeight(), PageSize.A4.getWidth());
pageSize.rotate();
document.setPageSize(pageSize);//设置文件纸张大小
PdfWriter writer=null;
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);//设置字体
Font titlefont = new Font(bfChinese,14,Font.BOLD);//字体样式
Font companyfont = new Font(bfChinese,10,Font.NORMAL);//字体样式
Font rowfont = new Font(bfChinese,10,Font.NORMAL);//字体样式
PDFBuilder pdfBuilder = new PDFBuilder();
writer = PdfWriter.getInstance(document,os);
writer.setPageEvent(pdfBuilder);
document.open();
Double TAX_FREE_AMT=0.0;
Double AMORTIZE_MONTH_ACCOUNT=0.0;
Double CURRENT_MONTH_ACCOUNT=0.0;
Double TOTAL_AMORTIZE_ACCOUNT=0.0;
Double AMORTIZE_BALANCE=0.0;
PdfPTable pdfPTable2 = new PdfPTable(13);
float[] columnWidth={55,50,50,110,50,50,50,85,50,50,60,80,80};
pdfPTable2.setTotalWidth(columnWidth);
pdfPTable2.setLockedWidth(true);
document.newPage();
//抬头信息
document.add( pdfPTable2.addCell(createCell("费用明细表", 1, 13, titlefont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.0f)));
document.add( pdfPTable2.addCell(createCell("公司名称", 1, 1, companyfont,Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.0f)));
document.add( pdfPTable2.addCell(createCell(gonssi, 1, 12, companyfont,Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.0f)));
//表头数据
pdfPTable2.addCell(createCell("单据号", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell("凭证编号", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell("凭证日期", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell("费用明细名称", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell("开始日期", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell("结束日期", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell("待摊期间", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell("发票无税金额", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell("月摊销额", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell("本月摊销", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell("已摊销月数", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell("累计摊销金额", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell("待摊余额", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
//表体数据
pdfPTable2.addCell(createCell("123456", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell("123456", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell("123456".toString(), 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell("123456", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell("123456", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell("123456", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell("123456", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell("123456", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));//发票无税金额
TAX_FREE_AMT+=Double.parseDouble("123456");
pdfPTable2.addCell(createCell("123456", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));//月摊销金额
AMORTIZE_MONTH_ACCOUNT+=Double.parseDouble("123456");
pdfPTable2.addCell(createCell("123456", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));//本月摊销金额
CURRENT_MONTH_ACCOUNT+=Double.parseDouble("123456");
pdfPTable2.addCell(createCell("123456", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell("123456", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));//累计摊销金额
TOTAL_AMORTIZE_ACCOUNT+=Double.parseDouble("123456");
pdfPTable2.addCell(createCell("123456", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));//待摊余额
AMORTIZE_BALANCE+=Double.parseDouble("123456");
pdfPTable2.addCell(createCell("合计", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell(" ", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell(" ", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell(" ", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell(" ", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell(" ", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell(" ", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell(TAX_FREE_AMT.toString(), 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell(AMORTIZE_MONTH_ACCOUNT.toString(), 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell(CURRENT_MONTH_ACCOUNT.toString(), 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell(" ", 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell(TOTAL_AMORTIZE_ACCOUNT.toString(), 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
pdfPTable2.addCell(createCell(AMORTIZE_BALANCE.toString(), 1, 1, rowfont, Element.ALIGN_LEFT, Element.ALIGN_CENTER,0.5f));
document.add(pdfPTable2);
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return os;
}
/**
* 多要求创建一行一列
* @param cellName
* @param row
* @param col
* @param font
* @param shuiping
* @param chuizhi
* @param f
* @return
* @throws DocumentException
* @throws IOException
*/
public static PdfPCell createCell(String cellName,Integer row,Integer col,Font font,int shuiping,int chuizhi,float f) throws DocumentException, IOException{
PdfPCell cell = new PdfPCell(new Phrase(cellName, font));
cell.setUseBorderPadding(true);
cell.setBorderWidth(f);
cell.setVerticalAlignment(chuizhi);//垂直居中
System.out.println(col);
if(row!=null){
cell.setRowspan(row);
}
if(col!=null&&col>1){
cell.setHorizontalAlignment(shuiping);//水平居中
cell.setColspan(col);
}else{
cell.setHorizontalAlignment(shuiping);
}
return cell;
}
/**
* Description: 向FTP服务器上传文件
* @param host FTP服务器hostname
* @param port FTP服务器端口
* @param username FTP登录账号
* @param password FTP登录密码
* @param basePath FTP服务器基础目录
* @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath
* @param filename 上传到FTP服务器上的文件名
* @param input 输入流
* @return 成功返回true,否则返回false
*/
public static boolean uploadFile( String basePath,String filePath, String filename, InputStream input) {
boolean result = false;
try{
if (!ftp.changeWorkingDirectory("F://")) {
String[] dirs = filePath.split("/");
String tempPath = basePath;
for (String dir : dirs) {
if (null == dir || "".equals(dir)) continue;
tempPath += "/" + dir;
if (!ftp.changeWorkingDirectory(tempPath)) {
if (!ftp.makeDirectory(tempPath)) {
return result;
} else {
ftp.changeWorkingDirectory(tempPath);
}
}
}
}
ftp.setFileType(FTP.BINARY_FILE_TYPE);
if (!ftp.storeFile(filename, input)) {
return result;
}else{
result=true;
System.out.println("上传成功");
}
}catch(Exception e){
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
ByteArrayOutputStream OS = T_LOG_RECORD_PREPAIDPDF("1","123","456");
//保存文件到本地
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream("F:\\aaaaa.pdf");
fileOutputStream.write(OS.toByteArray());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//上传至ftp服务器
//登陆ftp服务器
try {
connect();
InputStream Input = new ByteArrayInputStream(OS.toByteArray());
uploadFile("","","",Input);
} catch (Exception e) {
e.printStackTrace();
}
try {
ftp.logout();
System.out.println("FTP服务器退出成功");
} catch (IOException e) {
System.out.println("FTP服务器退出失败");
e.printStackTrace();
}finally{
if(ftp.isConnected()){
try {
ftp.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 登陆ftp服务器
* @throws Exception
*/
public static void connect() throws Exception {
try {
ftp.setDefaultPort(8080);//port
ftp.connect("127.0.0.1");//host
ftp.setDataTimeout(60000000);// 10分钟超时
ftp.setConnectTimeout(60000000);
ftp.login("FTP_USER", "FTP_PWD");
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
// throw new RuntimeException(“FTP拒绝访问”);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}