本篇内容主要讲解“itextpdf怎么生成PDF”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“itextpdf怎么生成PDF”吧!
生成PDF
package com.sw.busi.license.cites.approve.spi.service.impl.approval;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import com.sw.busi.common.log.Logger;
import com.sw.busi.common.utils.SEnv;
public class test {
private static final String HEAD_IMG = "head.jpg";
private static final String SUPERVISE_END_IMG = "supervise_end.jpg";
private static final String FONT = "static/fonts/simfang.ttf";
private static final String FONTHEI = "static/fonts/simhei.ttf";
public static void main(String[] args) {
try {
byte[] byteDate = createCurCitesApprovalPDF("林护许准云【2019】0100007号", new Date());
byteDate=createHeanAndEndRedFile(byteDate);
writeFile("C:/xuexi/", "1.pdf", byteDate);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static byte[] createCurCitesApprovalPDF(String approvNo,Date sendDte) throws Exception{
ByteArrayOutputStream output = new ByteArrayOutputStream();
URL headUrl = getURLTemplate(HEAD_IMG);//页码上的红头标题
URL endUrl = getURLTemplate(SUPERVISE_END_IMG);//每页上的尾部红线
//拿到字库
String FONT_PATH="E:/Git/busi/cites/sw-citesapprove-parent/citesapprove-server/src/main/webapp/static/fonts/"; //这个是仿宋体的路劲 测试的时候这个指向本地也行
String FONTHEI_PATH="E:/Git/busi/cites/sw-citesapprove-parent/citesapprove-server/src/main/webapp/static/fonts/";//这个是黑体的路劲 测试的时候这个指向本地也行
//单元测试文件
//path = path.substring(1,path.length());// 从路径字符串中取出工程路劲
FONT_PATH=FONT_PATH+"simfang.ttf";
FONTHEI_PATH=FONTHEI_PATH+"simhei.ttf";
//仿宋体
BaseFont baseFont = BaseFont.createFont(FONT_PATH, "Identity-H", BaseFont.EMBEDDED);
//黑体 文件标题用黑体
BaseFont baseFontHei = BaseFont.createFont(FONTHEI_PATH, "Identity-H", BaseFont.EMBEDDED);
//创建文本
//构造函数 选择对应的纸张型号,以及左右上下的边距
Document document = new Document(PageSize.A4, 35, 35, 110, 60);
//PDF文件对应的位置可以是指定位置的,也可以是输出流,输出流可以写到硬盘上
PdfWriter pdfWriter = PdfWriter.getInstance(document, output);
pdfWriter.setPageEvent(new BackGroundImage(headUrl,endUrl));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日");
try {
//打开文本
document.open();
//根据图片得到文件头
/*Image img1 = Image.getInstance(headUrl);
img1.setAbsolutePosition(0, 750);//设置图片位置
img1.scaleAbsolute(600, 150);//设置图片大小
document.add(img1);//把图片添加到PDF文档
//得到尾部图片
Image img2 = Image.getInstance(endUrl);
img2.setAbsolutePosition(0, 20);//设置图片位置
img2.scaleAbsolute(600, 50);//设置图片所占大小
document.add(img2);//添加到PDF上
*/ //文件号
//Paragraph fileNumberParagraph = new Paragraph(70); //这是段落 传入的值是距离上一段的位置,没有上一段则是距离边框的位置
//fileNumberParagraph.setAlignment(2);//设置对齐方式 对齐方式有三种 分别是 1 2 3 中右左
//Font font = new Font(baseFont);//得到对应的字
//font.setSize(16);//设置字体大小
//fileNumberParagraph.setFont(font); //设置字体
//Chunk chunk = new Chunk(); //块,文字区域,表示一个区域,也能放图片
//fileNumberParagraph.add(chunk); //把文字区域放入段落
//document.add(fileNumberParagraph);//把段落放入文档
/* CurCitesApprovalHeadVo tempVo=new CurCitesApprovalHeadVo();
ReflectionUtils.updateBeanData(headBo, tempVo);
ParaMappingConfig[] configs = new ParaMappingConfig[]{
// 境外国家地区
new ParaMappingConfig(ParaMappingConfig.sw_app, "iEType", CitesSwPara.CITES_I_E_TYPE.getUserNm(),CitesSwPara.CITES_I_E_TYPE.getParaTypeCd()),// 进出口类型
};
paraServiceUtil.setParaNameVal2Vo(tempVo, configs, "Text");*/
Paragraph title = getParagraph(approvNo, baseFontHei,1,0,22,0,0);
document.add(title);
//第一段
StringBuilder noticeText=new StringBuilder();
noticeText.append("关于同意");
noticeText.append("tempVo.getCopName()");
noticeText.append("tempVo.getiETypeText()");
noticeText.append("野生动植物及其制品的行政许可决定你(单位)的申请材料(");
noticeText.append("tempVo.getApplyNo()");
noticeText.append(")收悉。经审核,同意你(单位)");
noticeText.append("tempVo.getiETypeText()");
noticeText.append("的申请,详见附表");
Paragraph noticeOne = getParagraph(noticeText.toString(), baseFont, 3, 20,16,33,24);
document.add(noticeOne);
/*************************************************************************************/
//画摆表格
PdfPTable table = new PdfPTable(7); //传入的参数表示有几列
table.setTotalWidth(520);
float[] columnWidth={40,100,100,60,60,100,60};//没列的大小
table.setTotalWidth(columnWidth);
table.setLockedWidth(true);
//标题与表格中间的距离
Paragraph p = new Paragraph();
Font f = new Font(baseFont);//字体
f.setSize(18);//字体大小
p.setFont(f);//设置段落字体
Chunk c = new Chunk(" ");
p.add(c);
document.add(p);
//表格开始 每一个cell 对应一列,不满六列不打印,这个几列是自己设置的 表格每一行必须有列,
PdfPCell cell = getPdfPCell("序号",baseFontHei,14,1);//表格第一个标题
cell.setFixedHeight(40);//设置表格单元格高度
table.addCell(cell);
//表格第2个标题
cell = getPdfPCell("物种名称(中文名)",baseFontHei,14,1);
cell.setFixedHeight(40);//设置表格单元格高度
table.addCell(cell);
//表格第3个标题
cell = getPdfPCellCenter("物种名称(拉丁学名)",baseFontHei);
cell.setFixedHeight(40);//设置表格单元格高度
table.addCell(cell);
//表格第4个标题
cell = getPdfPCellCenter("数量",baseFontHei);
cell.setFixedHeight(40);//设置表格单元格高度
table.addCell(cell);
//表格第5个标题
cell = getPdfPCellCenter("单位",baseFontHei);
cell.setFixedHeight(40);//设置表格单元格高度
table.addCell(cell);
//表格第5个标题
cell = getPdfPCellCenter("标本类型",baseFontHei);
cell.setFixedHeight(40);//设置表格单元格高度
table.addCell(cell);
//表格第6个标题
cell = getPdfPCellCenter("境外国家/地区",baseFontHei);
cell.setFixedHeight(40);//设置表格单元格高度
table.addCell(cell);
/* List<CurCitesSpeListVo> list = citesApprovalVoDao.queryCurCitesSpeListVoByApplyNo(headBo.getApplyNo());
ParaMappingConfig[] listLonfigs = new ParaMappingConfig[]{
// 境外国家地区
new ParaMappingConfig(ParaMappingConfig.sw_dep, "abrCounName", "CITES_PARA_COUNTRY")
};
paraServiceUtil.setParaNameVal2Vo(list, listLonfigs, "Text");
//序号 物种名称(中文名) 物种名称(拉丁学名) 数量 单位 标本类型 境外国家/地区
int num=1;
//开始编列细项
for (CurCitesSpeListVo vo : list) {
table.addCell(getPdfPCell(num+"",baseFont,12,1)); //这个是第几个物种
table.addCell(getPdfPCell(vo.getSpeName(),baseFont,12,1)); //
table.addCell(getPdfPCell(vo.getSpeEname(),baseFont,12,1)); //
table.addCell(getPdfPCell(vo.getQty().toString(),baseFont,12,3));//
table.addCell(getPdfPCell(vo.getUnit(),baseFont,12,1));//
table.addCell(getPdfPCell(vo.getMarkType(),baseFont,12,1));//
table.addCell(getPdfPCell(vo.getAbrCounNameText(),baseFont,12,1));//
num++;
}*/
for (int i = 1; i <65; i++) {
table.addCell(getPdfPCell(i+"",baseFont,12,1)); //这个是第几个物种
table.addCell(getPdfPCell("2",baseFont,12,1)); //
table.addCell(getPdfPCell("3",baseFont,12,1)); //
table.addCell(getPdfPCell("4",baseFont,12,3));//
table.addCell(getPdfPCell("5",baseFont,12,1));//
table.addCell(getPdfPCell("6",baseFont,12,1));//
table.addCell(getPdfPCell("7",baseFont,12,1));//
}
document.add(table);
/*************************************************************************************/
StringBuilder noticeTwoText=new StringBuilder();
noticeTwoText.append("是否需要申请标识?");
noticeTwoText.append("请你(单位)于");
noticeTwoText.append("sdf.format(tempVo.getValidDate())");
noticeTwoText.append("前向国家濒危物种进出口管理机构办理《允许进出口证明书》,逾期无效。");
//第二段
Paragraph noticeTwo = getParagraph(noticeTwoText.toString(), baseFont, 3, 20,16,33,24);
document.add(noticeTwo);
StringBuilder noticeThreeText=new StringBuilder();
/*if("01".equals(tempVo.getDep())){
noticeThreeText.append("抄送:国家濒管办、");
noticeThreeText.append(tempVo.getCcDepName());
noticeThreeText.append("\n");
noticeThreeText.append("本局发送:局行政许可办公室");
noticeThreeText.append("国家林业和草原局 ");
noticeThreeText.append(sdf.format(sendDte));
noticeThreeText.append("印发");
}else{
noticeThreeText.append("抄送:国家林业和草原局野生动植物保护司、国家濒管办、");
noticeThreeText.append(tempVo.getCcDepName());
noticeThreeText.append("\n");
noticeThreeText.append(headBo.getDepName());
noticeThreeText.append(sdf.format(sendDte));
noticeThreeText.append("印发");
}*/
noticeThreeText.append("抄送:国家林业和草原局野生动植物保护司、国家濒管办、");
noticeThreeText.append("tempVo.getCcDepName()");
noticeThreeText.append("\n");
noticeThreeText.append("headBo.getDepName()");
noticeThreeText.append(sdf.format(sendDte));
noticeThreeText.append("印发");
Paragraph noticeThree = getParagraph(noticeThreeText.toString(), baseFont, 3, 20,16,33,24);
document.add(noticeThree);
PdfPageEventHelper aa=new PdfPageEventHelper();
//关闭文本
document.close();
} catch (DocumentException e) {
} catch (FileNotFoundException e) {
}
return output.toByteArray();
}
public static URL getURLTemplate(String urlAdress) {
URL url = null;
String path = "E:/Git/busi/cites/sw-citesapprove-parent/sw-citesapprove-front/src/main/webapp/static/pdfjs/template/";// 得到d:/tomcat/webapps/工程名WEB-INF/classes/路径
path=path+urlAdress;
try {
// SEnv.WINDOWS获取当前系统操作类型
if (SEnv.WINDOWS) {
url = new URL("file", null, path);// String转化成URL
} else if (SEnv.LINUX || SEnv.SUN_OS) {
url = new URL("file", null, "/" + path);// String转化成URL
}
} catch (Exception e) {
}
return url;
}
private static PdfPCell getPdfPCellCenter(String cellText,BaseFont baseFont) throws Exception{
//为null会报错 防止报错
if(cellText==null){
cellText=" ";
}
//表格开始
Paragraph paragraph = new Paragraph();//为了让起居中
paragraph.setAlignment(1); //对齐方式
Font font = new Font(baseFont);//字体
font.setSize(14);//字体大小
paragraph.setFont(font);//设置段落字体
Chunk chunk = new Chunk(cellText);
paragraph.add(chunk);
PdfPCell cell = new PdfPCell();
cell.setMinimumHeight(25);//设置单元格最小高度,会随着数据增多而增多
cell.addElement(paragraph);
return cell;
}
/**
*
* @param chunkText 段落文本
* @param baseFont 字体
* @param alignment //设置对齐方式 对齐方式有三种 分别是 1 2 3 中右左
* @param leading //是距离上一段的位置,没有上一段则是距离边框的位置
* @param fontSize //字体大小
* @param firstLineIndent //首行缩进
* @param fixedLeading //行间距
* @return
*/
private static Paragraph getParagraph(String chunkText,BaseFont baseFont,int alignment,int leading,int fontSize,int firstLineIndent,
int fixedLeading ) {
//为null会报错 防止报错
if(chunkText==null){
chunkText=" ";
}
//标题
Paragraph paragraph = new Paragraph(leading);
Font titlefont = new Font(baseFont);
titlefont.setSize(fontSize);
paragraph.setFirstLineIndent(33);
paragraph.setFont(titlefont);
paragraph.setAlignment(alignment);
paragraph.setLeading(fixedLeading);
Chunk titleChunk = new Chunk(chunkText);
paragraph.add(titleChunk);
return paragraph;
}
private static PdfPCell getPdfPCell(String cellText,BaseFont baseFont,float size,int alignment) throws Exception{
//为null会报错 防止报错
if(cellText==null){
cellText=" ";
}
//表格开始
Paragraph paragraph = new Paragraph();
paragraph.setAlignment(alignment); //对齐方式
Font font = new Font(baseFont);//字体
font.setSize(size);//字体大小
paragraph.setFont(font);//设置段落字体
Chunk chunk = new Chunk(cellText);
paragraph.add(chunk);
PdfPCell cell = new PdfPCell();
cell.setMinimumHeight(25);//设置单元格最小高度,会随着数据增多而增多
cell.addElement(paragraph);
return cell;
}
public static void writeFile(String path, String fileName, byte[] content)
throws IOException {
try {
File f = new File(path);
if (!f.exists()) {
f.mkdirs();
}
FileOutputStream fos = new FileOutputStream(path + fileName);
fos.write(content);
fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static byte[] createHeanAndEndRedFile(byte[] byteDate){
URL headUrl = getURLTemplate(HEAD_IMG);//页码上的红头标题
URL endUrl = getURLTemplate(SUPERVISE_END_IMG);//每页上的尾部红线
ByteArrayOutputStream outputEnd = new ByteArrayOutputStream();
Document documentEnd = null;
PdfCopy copyEnd = null;
try {
PdfReader reader = new PdfReader(byteDate);
int n = reader.getNumberOfPages();
documentEnd = new Document(reader.getPageSize(1));
copyEnd = new PdfCopy(documentEnd, outputEnd);
documentEnd.open();
for (int i = 1; i <= n; i++) {
documentEnd.newPage();
Image img1 = Image.getInstance(headUrl);
img1.setAbsolutePosition(0, 750);//设置图片位置
img1.scaleAbsolute(600, 150);//设置图片大小
copyEnd.add(img1);//把图片添加到PDF文档
//得到尾部图片
Image img2 = Image.getInstance(endUrl);
img2.setAbsolutePosition(0, 20);//设置图片位置
img2.scaleAbsolute(600, 50);//设置图片所占大小
copyEnd.add(img2);//添加到PDF上
PdfImportedPage pageEnd = copyEnd.getImportedPage(reader, i);
copyEnd.addPage(pageEnd);
}
documentEnd.close();
} catch (IOException e) {
Logger.error("split pdf file error:{}",e.getMessage(),e);
} catch(DocumentException e) {
Logger.error("split pdf file error:{}",e.getMessage(),e);
}
return outputEnd.toByteArray();
}
}
加载背景 每页都加上同一个图片
package com.sw.busi.license.cites.approve.spi.service.impl.approval;
import java.io.IOException;
import java.net.URL;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
/**
* @Description: 为每一页pdf都生成背景图片
* @author: kylin
* @create: 2018-01-08 18:00
**/
public class BackGroundImage extends PdfPageEventHelper {
URL headUrl =null;
URL endUrl =null;
public URL getHeadUrl() {
return headUrl;
}
public void setHeadUrl(URL headUrl) {
this.headUrl = headUrl;
}
public URL getEndUrl() {
return endUrl;
}
public void setEndUrl(URL endUrl) {
this.endUrl = endUrl;
}
public BackGroundImage(){
}
public BackGroundImage(URL headUrl,URL endUrl){
this.headUrl = headUrl;
this.endUrl = endUrl;
}
@Override
public void onStartPage(PdfWriter pdfWriter, Document document) {
try {
Image img1 = Image.getInstance(headUrl);
img1.setAbsolutePosition(0, 750);//设置图片位置
img1.scaleAbsolute(600, 150);//设置图片大小
document.add(img1);//把图片添加到PDF文档
//得到尾部图片
Image img2 = Image.getInstance(endUrl);
img2.setAbsolutePosition(0, 20);//设置图片位置
img2.scaleAbsolute(600, 50);//设置图片所占大小
document.add(img2);
} catch (BadElementException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
super.onStartPage(pdfWriter, document);
}
}
到此,相信大家对“itextpdf怎么生成PDF”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/2560716/blog/3083558