iText
iText是著名的开放项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。
官方网站:http://itextpdf.com/
示例版本:itextpdf-5.2.1.jar
示例代码
Rectangle rect = new Rectangle(PageSize.B5.rotate()); //页面大小
rect.setBackgroundColor(BaseColor.ORANGE); //页面背景色
Document doc = new Document(rect);
PdfWriter writer = PdfWriter.getInstance(doc, out);
writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2); //PDF版本(默认1.4)
/* 设置密码 */
writer.setEncryption("Hello".getBytes(), "World".getBytes(),
PdfWriter.ALLOW_SCREENREADERS,
PdfWriter.STANDARD_ENCRYPTION_128); /* PDF属性 */
doc.addTitle("Title@sample");
doc.addAuthor("Author@rensanning");
doc.addSubject("Subject@iText sample");
doc.addKeywords("Keywords@iText");
doc.addCreator("Creator@iText"); doc.setMargins(10, 20, 30, 40);
doc.open();
doc.add(new Paragraph("Hello World")); //在此处追加内容 document.close();
document.add(new Paragraph("First page"));
document.add(new Paragraph(Document.getVersion())); document.newPage();
writer.setPageEmpty(false); document.newPage();
document.add(new Paragraph("New page"));
添加多个Page
PdfReader reader = new PdfReader(FILE_DIR + "deletePage.pdf"); /* 删除Page */
reader.selectPages("1,3");
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR + "deletePage2.pdf")); /* 插入Page */
stamp.insertPage(2, reader.getPageSize(1)); stamp.close();
reader.close(); /* 排序Page */
PdfWriter writer = PdfWriter.getInstance(doc, out);
writer.setLinearPageMode();
writer.reorderPages({4,3,2,1});
Page删除、插入、排序
/* Chunk对象: a String, a Font, and some attributes */
document.add(new Chunk("China"));
document.add(new Chunk(" "));
Font font = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);
Chunk id = new Chunk("chinese", font);
id.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
id.setTextRise(6);
document.add(id);
document.add(Chunk.NEWLINE); document.add(new Chunk("Japan"));
document.add(new Chunk(" "));
Font font2 = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);
Chunk id2 = new Chunk("japanese", font2);
id2.setBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
id2.setTextRise(6);
id2.setUnderline(0.2f, -2f);
document.add(id2);
document.add(Chunk.NEWLINE); /* Phrase对象: a List of Chunks with leading */
document.newPage();
document.add(new Phrase("Phrase page")); Phrase director = new Phrase();
Chunk name = new Chunk("China");
name.setUnderline(0.2f, -2f);
director.add(name);
director.add(new Chunk(","));
director.add(new Chunk(" "));
director.add(new Chunk("chinese"));
director.setLeading(24);
document.add(director); Phrase director2 = new Phrase();
Chunk name2 = new Chunk("Japan");
name2.setUnderline(0.2f, -2f);
director2.add(name2);
director2.add(new Chunk(","));
director2.add(new Chunk(" "));
director2.add(new Chunk("japanese"));
director2.setLeading(24);
document.add(director2); /* Paragraph对象: a Phrase with extra properties and a newline */
document.newPage();
document.add(new Paragraph("Paragraph page")); Paragraph info = new Paragraph();
info.add(new Chunk("China "));
info.add(new Chunk("chinese"));
info.add(Chunk.NEWLINE);
info.add(new Phrase("Japan "));
info.add(new Phrase("japanese"));
document.add(info); /* List对象: a sequence of Paragraphs called ListItem */
document.newPage();
List list = new List(List.ORDERED);
for (int i = 0; i < 10; i++) {
ListItem item = new ListItem(
String.format("%s: %d movies","country" + (i + 1), (i + 1) * 100),
new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE));
List movielist = new List(List.ORDERED, List.ALPHABETICAL);
movielist.setLowercase(List.LOWERCASE);
for (int j = 0; j < 5; j++) {
ListItem movieitem = new ListItem("Title" + (j + 1));
List directorlist = new List(List.UNORDERED);
for (int k = 0; k < 3; k++) {
directorlist.add(String.format("%s, %s", "Name1" + (k + 1),"Name2" + (k + 1)));
}
movieitem.add(directorlist);
movielist.add(movieitem);
}
item.add(movielist);
list.add(item);
}
document.add(list); /* Anchor对象: internal and external links */
document.newPage();
Paragraph country = new Paragraph();
Anchor dest = new Anchor("china", new Font(Font.FontFamily.HELVETICA, 14, Font.BOLD, BaseColor.BLUE));
dest.setName("CN");
dest.setReference("http://www.china.com");//external
country.add(dest);
country.add(String.format(": %d sites", 10000));
document.add(country); document.newPage();
Anchor toUS = new Anchor("Go to first page.", new Font(Font.FontFamily.HELVETICA, 14, Font.BOLD, BaseColor.BLUE));
toUS.setReference("#CN");//internal
document.add(toUS); /* Image对象 */
document.newPage();
Image img = Image.getInstance("resource/test.jpg");
img.setAlignment(Image.LEFT | Image.TEXTWRAP);
img.setBorder(Image.BOX);
img.setBorderWidth(10);
img.setBorderColor(BaseColor.WHITE);
img.scaleToFit(1000, 72);//大小
img.setRotationDegrees(-30);//旋转
document.add(img); /* Chapter, Section对象(目录) */
document.newPage();
Paragraph title = new Paragraph("Title");
Chapter chapter = new Chapter(title, 1); title = new Paragraph("Section A");
Section section = chapter.addSection(title);
section.setBookmarkTitle("bmk");
section.setIndentation(30);
section.setBookmarkOpen(false);
section.setNumberStyle(Section.NUMBERSTYLE_DOTTED_WITHOUT_FINAL_DOT); Section subsection = section.addSection(new Paragraph("Sub Section A"));
subsection.setIndentationLeft(20);
subsection.setNumberDepth(1); document.add(chapter);
添加内容
Paragraph p = new Paragraph("段落内容"); /* 对齐方式 */
p.setAlignment(Element.ALIGN_JUSTIFIED); /* 缩进 */
p.setIndentationLeft(1 * 15f);
p.setIndentationRight((5 - 1) * 15f); /* 间距 */
p.setSpacingAfter(15f);
p.setSpacingBefore(15f);
段落设置
PdfPTable table = new PdfPTable(3);
PdfPCell cell;
cell = new PdfPCell(new Phrase("Cell with colspan 3"));
cell.setColspan(3);
table.addCell(cell); cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
cell.setRowspan(2);
table.addCell(cell); table.addCell("row 1; cell 1");
table.addCell("row 1; cell 2");
table.addCell("row 2; cell 1");
table.addCell("row 2; cell 2"); document.add(table);
表格
PdfPTable table = new PdfPTable(4); /* 1行2列 */
PdfPTable nested1 = new PdfPTable(2);
nested1.addCell("1.1");
nested1.addCell("1.2"); /* 2行1列 */
PdfPTable nested2 = new PdfPTable(1);
nested2.addCell("2.1");
nested2.addCell("2.2"); /* 将表格插入到指定位置 */
table.addCell(nested1);
table.addCell(nested2); document.add(table);
表格嵌套
PdfPTable table = new PdfPTable(widths); /* 百分比宽度 */
table.setWidthPercentage(50);
table.setHorizontalAlignment(Element.ALIGN_RIGHT); //对齐方式 /* 固定宽度 */
table.setTotalWidth(300);
table.setLockedWidth(true); /* 上下间距 */
table.setSpacingBefore(15f);
table.setSpacingAfter(15f); /* 百分比列宽 */
float[] widths = {40f, 40f, 20f, 80f};
table.setWidths(widths); /* 固定列宽 */
Rectangle r = new Rectangle(PageSize.A4.getRight(72), PageSize.A4.getTop(72));
table.setWidthPercentage(widths, r);
表格设置
PdfPTable datatable = new PdfPTable(5);
datatable.setWidths({ 9, 4, 8, 10, 8 });// percentage datatable.addCell("Clock #");
datatable.addCell("Trans Type");
datatable.addCell("Cusip");
datatable.addCell("Long Name");
datatable.addCell("Quantity"); datatable.setHeaderRows(1);
表格标题行
PdfPCell cell = new PdfPCell(new Paragraph("blah blah"));
cell.setNoWrap(false); //自动换行
cell.setFixedHeight(50f); //固定高度
cell.setMinimumHeight(50f); //最小高度
cell.setUseBorderPadding(true); //内填充
cell.setPadding(10f); // 内填充统一
cell.setPaddingTop(0f); //内填充上
cell.setPaddingLeft(20f);//内填充左
cell.setBorder(Rectangle.BOTTOM); //边框
cell.setBorderColorBottom(BaseColor.MAGENTA); //边框颜色
cell.setBorderWidthBottom(5f); //边框宽度
cell.setBackgroundColor(BaseColor.RED); //背景
cell.setGrayFill(0.25f);//背景灰色度 table.setExtendLastRow(true); //最后一行拉长到page底部
cell = new PdfPCell(new Paragraph("page footer",fontZH)); cell = table1.getDefaultCell(); // 默认单元格,提供默认设置
单元格设置
/* 左右箭头 */
document.add(new VerticalPositionMark() {
public void draw(PdfContentByte canvas, float llx, float lly,
float urx, float ury, float y) {
canvas.beginText();
BaseFont bf = null;
try {
bf = BaseFont.createFont(BaseFont.ZAPFDINGBATS, "", BaseFont.EMBEDDED);
} catch (Exception e) {}
canvas.setFontAndSize(bf, 12);
/* LEFT */
canvas.showTextAligned(Element.ALIGN_CENTER, String.valueOf((char) 220), llx - 10, y, 0);
/* RIGHT */
canvas.showTextAligned(Element.ALIGN_CENTER, String.valueOf((char) 220), urx + 10, y + 8, 180);
canvas.endText();
}
}); /* 直线 */
Paragraph p1 = new Paragraph("LEFT");
p1.add(new Chunk(new LineSeparator()));
p1.add("R");
document.add(p1); /* 点线 */
Paragraph p2 = new Paragraph("LEFT");
p2.add(new Chunk(new DottedLineSeparator()));
p2.add("R");
document.add(p2); /* 下滑线 */
LineSeparator UNDERLINE = new LineSeparator(1, 100, null, Element.ALIGN_CENTER, -2);
Paragraph p3 = new Paragraph("NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN");
p3.add(UNDERLINE);
画图
/* 添加一些Page */
document.newPage();
document.add(new Chunk("Chapter 1").setLocalDestination("1")); document.newPage();
document.add(new Chunk("Chapter 2").setLocalDestination("2"));
document.add(new Paragraph(new Chunk("Sub 2.1").setLocalDestination("2.1")));
document.add(new Paragraph(new Chunk("Sub 2.2").setLocalDestination("2.2"))); document.newPage();
document.add(new Chunk("Chapter 3").setLocalDestination("3")); /* 生成大纲 */
PdfContentByte cb = writer.getDirectContent();
PdfOutline root = cb.getRootOutline(); PdfOutline oline1 = new PdfOutline(root, PdfAction.gotoLocalPage("1", false), "Chapter 1");
PdfOutline oline2 = new PdfOutline(root, PdfAction.gotoLocalPage("2", false), "Chapter 2");
PdfOutline oline2_1 = new PdfOutline(oline2, PdfAction.gotoLocalPage("2.1", false), "Sub 2.1");
PdfOutline oline2_2 = new PdfOutline(oline2, PdfAction.gotoLocalPage("2.2", false), "Sub 2.2");
PdfOutline oline3 = new PdfOutline(root, PdfAction.gotoLocalPage("3", false), "Chapter 3");
目录大纲
PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(FILE_DIR + "setHeaderFooter.pdf"));
writer.setPageEvent(new PdfPageEventHelper() {
public void onEndPage(PdfWriter writer, Document document) {
PdfContentByte cb = writer.getDirectContent();
cb.saveState();
cb.beginText();
BaseFont bf = null;
try {
bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
} catch (Exception e) {}
cb.setFontAndSize(bf, 10); /* Header,分左中右 */
float x = document.top(-20);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT,"H-Left",document.left(), x, 0);
cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
writer.getPageNumber()+ " page",
(document.right() + document.left())/2,
x, 0);
cb.showTextAligned(PdfContentByte.ALIGN_RIGHT,"H-Right",document.right(), x, 0); /* Footer,分左中右 */
float y = document.bottom(-20);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT,"F-Left",document.left(), y, 0);
cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
writer.getPageNumber()+" page",
(document.right() + document.left())/2,
y, 0);
cb.showTextAligned(PdfContentByte.ALIGN_RIGHT,"F-Right",document.right(), y, 0); cb.endText();
cb.restoreState();
}
});
页眉页脚
PdfWriter writer = PdfWriter.getInstance(doc, out);
writer.setPdfVersion(PdfWriter.VERSION_1_5);
writer.setViewerPreferences(PdfWriter.PageModeFullScreen);//全屏
writer.setPageEvent(new PdfPageEventHelper() {
public void onStartPage(PdfWriter writer, Document document) {
writer.setTransition(new PdfTransition(PdfTransition.DISSOLVE, 3));
writer.setDuration(5);//间隔时间
}
});
幻灯片放映
/* 实现FontProvider接口比如叫MyFontProvider,在getFont()方法里设置你的字体库 */
HashMap providers = new HashMap();
providers.put(HTMLWorker.FONT_PROVIDER, new MyFontProvider());
List<Element> list = HTMLWorker.parseToList(new StringReader(html),new StyleSheet(),providers);
for (Element e : list) {
document.add(e);
}
自定义字体
PdfReader reader = new PdfReader(FILE_DIR + "splitPDF.pdf"); /* 拆分一 */
Document dd = new Document();
PdfWriter writer = PdfWriter.getInstance(dd, new FileOutputStream(FILE_DIR + "splitPDF1.pdf"));
dd.open();
PdfContentByte cb = writer.getDirectContent();
dd.newPage();
cb.addTemplate(writer.getImportedPage(reader, 1), 0, 0);
dd.newPage();
cb.addTemplate(writer.getImportedPage(reader, 2), 0, 0);
dd.close();
writer.close(); /* 拆分二 */
Document dd2 = new Document();
PdfWriter writer2 = PdfWriter.getInstance(dd2, new FileOutputStream(FILE_DIR + "splitPDF2.pdf"));
dd2.open();
PdfContentByte cb2 = writer2.getDirectContent();
dd2.newPage();
cb2.addTemplate(writer2.getImportedPage(reader, 3), 0, 0);
dd2.newPage();
cb2.addTemplate(writer2.getImportedPage(reader, 4), 0, 0);
dd2.close();
writer2.close();
拆分PDF
Document document = new Document(PageSize.LETTER);
PdfWriter.getInstance(document, new FileOutputStream("c://testpdf1.pdf"));
document.open();
HTMLWorker htmlWorker = new HTMLWorker(document);
htmlWorker.parse(new StringReader("<h1>This is a test!</h1>"));
document.close();
HTML转换为PDF
ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(FILE_DIR + "zipPDF.zip"));
for (int i = 1; i <= 3; i++) {
ZipEntry entry = new ZipEntry("hello_" + i + ".pdf");
zip.putNextEntry(entry);
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, zip);
writer.setCloseStream(false);
document.open();
document.add(new Paragraph("Hello " + i));
document.close();
zip.closeEntry();
}
zip.close();
压缩为ZIP
iText的更多相关文章
- Itext Demo
Tables and fonts /** * Example written by Bruno Lowagie in answer to the following question: * http: ...
- 【Java】使用iText生成PDF文件
iText介绍 iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库.通过iText不仅可以生成PDF或rtf的文档,而且可以将XML.Html文件转 ...
- 使用iText库创建PDF文件
前言 译文连接:http://howtodoinjava.com/apache-commons/create-pdf-files-in-java-itext-tutorial/ 对于excel文件的读 ...
- itext 实现pdf打印数字上标和下标
https://kathleen1974.wordpress.com/category/itext-pdf/ In one of my project, we need to give the use ...
- 新知识:Java 利用itext填写pdf模板并导出(昨天奋战到深夜四点,知道今天两点终于弄懂)
废话少说,不懂itext干啥用的直接去百度吧. ***************制作模板******************* 1.先用word做出界面 2.再转换成pdf格式 3.用Adobe Acr ...
- PDF 生成插件 flying saucer 和 iText
最近的项目中遇到了需求,用户在页面点击下载,将页面以PDF格式下载完成供用户浏览,所以上网找了下实现方案. 在Java世界,要想生成PDF,方案不少,所以简单做一个小结吧. 在此之前,先来勾画一下我心 ...
- IText&Html2canvas js截图 绘制 导出PDF
Html2canvas JS截图 HTML <div id="divPDF"> 需要截图的区域 </div> JS <script src=" ...
- C#:IText构造PDF文件
IText构造PDF文件 1.1 生成Document Document是我们要生成的PDF文件所有元素的容器,因此要生成一个PDF文档,必须首先定义一个Document对象. Document有三种 ...
- iText导出pdf、word、图片
一.前言 在企业的信息系统中,报表处理一直占比较重要的作用,本文将介绍一种生成PDF报表的Java组件--iText.通过在服务器端使用Jsp或JavaBean生成PDF报表,客户端采用超级连接显示或 ...
- 【PDF】java使用Itext生成pdf文档--详解
[API接口] 一.Itext简介 API地址:javadoc/index.html:如 D:/MyJAR/原JAR包/PDF/itext-5.5.3/itextpdf-5.5.3-javadoc/ ...
随机推荐
- JDK1.5中LOCK,Condition的使用
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.uti ...
- 各种开源协议介绍 BSD、Apache Licence、GPL V2 、GPL V3 、LGPL、MIT
现今存在的开源协议很多,而经过Open Source Initiative组织通过批准的开源协议目前有58种(http://www.opensource.org/licenses /alphabeti ...
- shell每日发邮件
LOGFILE="$fank/"`date +"%Y%m%d"`"data"#每日文件 from="abc@123.com&quo ...
- ajax+XMLHttpRequest里的FormData实现图片异步上传
发这篇博客的时候我是自己在研究这个XMLHttpRequest请求,在别人的博客上面知道XMLHttpRequest新加了一个FormData的东西,好像现在APP请求后台也有用这种方式的吧. 别的不 ...
- jQuery中事件的学习
刚学习了jQuery中的事件,主要通过bind(),toggle(),hover()来主要实现,下面先说一说关于bind的想关要点. 1.bind方法. bind方法的主要参数为bind(type,f ...
- Access数据库导入到mysql数据库中
做项目时需要查询手机号归属地的,用网上提供的接口,耗时太长,反应慢,只能自己在网上搜了一个包含所有手机号归属地的Access数据库,导入到自己的mysql数据库中 Access数据库导入到mysql中 ...
- HTML&CSS基础学习笔记1.29-灵活地使用样式
灵活的使用样式 使用样式的感觉很棒吧! 刚我们使用的内联样式是给具体的标签加上样式,如果有多个标签的时候,我们用内联样式给标签加样式的时候就需要一个个的加过来,这样就很麻烦. 而如果我们使用内部样式表 ...
- css阴影
文字阴影:text-shadow:[颜色 x轴 y轴 模糊半径],[颜色 x轴 y轴 模糊半径]... 区域阴影:box-shadow:[颜色 x轴 y轴 模糊半径],[颜色 x轴 y轴 模糊半径]. ...
- Egret 入门
居然使用 TyptScript... 先贴手册地址:http://www.typescriptlang.org/docs/tutorial.html. 先要接受一个诡异的写法: private loa ...
- HTML 基础元素
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...