java操作pdf的工具类itext的处理方法-mile米乐体育

目录

  • 一、什么是itext?
  • 二、引入jar
  • 三、itext常用类
  • 四、生成pdf步骤
  • 五、java操作pdf的工具类itext
  • 六、更多的java代码实例

一、什么是itext?

在企业的信息系统中,报表处理一直占比较重要的作用,itext是一种生成pdf报表的java组件。通过在服务器端使用jsp或javabean生成pdf报表,客户端采用超链接显示或下载得到生成的报表,这样就很好的解决了b/s系统的报表处理问题。

二、引入jar

1、项目要使用itext,必须引入jar包

com.itextpdf itextpdf 5.5.6

2、输出中文,还要引入下面itext-asian.jar

com.itextpdf itext-asian 5.2.0

3、设置pdf文件密码,还要引入下面bcprov-jdk15on.jar

org.bouncycastle bcprov-jdk15on 1.47

三、itext常用类

  • com.itextpdf.text.document:这是itext库中最常用的类,它代表了一个 pdf 实例。如果你需要从零开始生成一个pdf文件,你需要使用这个document类。首先创建该实例,然后打开它,并添加内容,最后关闭该实例,即可生成一个pdf文件。
  • com.itextpdf.text.paragraph:表示一个缩进的文本段落,在段落中,你可以设置对齐方式,缩进,段落前后间隔等
  • com.itextpdf.text.chapter:表示 pdf 的一个章节,他通过一个paragraph类型的标题和整形章数创建
  • com.itextpdf.text.font:这个类包含了所有规范好的字体,包括family of font,大小,样式和颜色,所有这些字体都被声明为静态常量
  • com.itextpdf.text.list:表示一个列表;com.itextpdf.text.anchor:表示一个锚,类似于html页面的链接。
  • com.itextpdf.text.pdf.pdfwriter:当这个pdfwriter被添加到pdfdocument后,所有添加到document的内容将会写入到与文件或网络关联的输出流中。
  • com.itextpdf.text.pdf.pdfreader:用于读取 pdf 文件;

四、生成pdf步骤

1、创建文档

document document = new document();

2、通过书写器将文档写入磁盘

pdfwriter writer = pdfwriter.getinstance(document, new fileoutputstream(file_dir "createpdfwithcolor.pdf"));

3、打开文档

document.open();

4、向文档中添加内容

document.add(new paragraph("i love csdn"));

5、关闭文档

document.close();

五、java操作pdf的工具类itext

package com.neusoft.guor.itext; import java.io.file; import java.io.filenotfoundexception; import java.io.fileoutputstream; import java.io.ioexception; import java.net.malformedurlexception; import java.util.arraylist; import java.util.iterator; import java.util.zip.zipentry; import java.util.zip.zipoutputstream; import com.itextpdf.text.*; import com.itextpdf.text.pdf.basefont; import com.itextpdf.text.pdf.columntext; import com.itextpdf.text.pdf.pdfaction; import com.itextpdf.text.pdf.pdfannotation; import com.itextpdf.text.pdf.pdfcontentbyte; import com.itextpdf.text.pdf.pdfimportedpage; import com.itextpdf.text.pdf.pdfname; import com.itextpdf.text.pdf.pdfoutline; import com.itextpdf.text.pdf.pdfpageeventhelper; import com.itextpdf.text.pdf.pdfreader; import com.itextpdf.text.pdf.pdfstamper; import com.itextpdf.text.pdf.pdfstring; import com.itextpdf.text.pdf.pdftransition; import com.itextpdf.text.pdf.pdfwriter; import com.itextpdf.text.pdf.draw.dottedlineseparator; import com.itextpdf.text.pdf.draw.lineseparator; import com.itextpdf.text.pdf.draw.verticalpositionmark; /** * itext pdf操作 */ public class pdfinit { public static final string file_dir = "e:\\guor\\itext\\"; public static final string const_jpg_java = file_dir "java.jpg"; public static final string const_jpg_nginx = file_dir "nginx.jpg"; private static final string const_nezha = "哪吒编程"; private static final string const_nezha_program = "获取java学习资料请关注公众号:哪吒编程"; private static final string const_bibidong = "比比东"; private static final string const_yunyun = "云韵"; private static final string const_baidu = "百度一下 你就知道"; private static final string const_baidu_url = "https://www.baidu.com"; private static final string const_page_first = "第一页"; private static final string const_page_second = "第二页"; private static final string const_page_third = "第三页"; private static final string const_page_four = "第四页"; private static final string const_page_five = "第五页"; private static final string const_title_first = "一级标题"; private static final string const_title_second = "二级标题"; private static final string const_content = "内容"; // 普通中文字体 public static font static_font_chinese = null; // 超链字体 public static font static_font_link = null; private static void pdffontinit() throws ioexception, documentexception { // 微软雅黑 basefont chinese = basefont.createfont("stsong-light", "unigb-ucs2-h", basefont.not_embedded); // 普通中文字体 static_font_chinese = new font(chinese, 12, font.normal);// font.bold为加粗 // 超链字体 static_font_link = new font(chinese, 12, font.normal, basecolor.blue); } public static document document; public static void main(string[] args) throws exception { pdffontinit(); //createpdf();// 生成一个 pdf 文件 //createpdfwithcolor();// 设置pdf的页面大小和背景颜色 //createpdfwithpassword();// 创建带密码的pdf //createpdfwithnewpages();// 为pdf添加页 //createpdfwithwatermark();// 为pdf文件添加水印,背景图 //createpdfwithcontent();//插入块chunk, 内容phrase, 段落paragraph, list //createpdfwithextracontent();//插入anchor, image, chapter, section //draw();//画图 //createpdfwithalignment();//设置段落 //createpdftodeletepage();//删除 page //insertpage();// 插入 page //splitpdf();//分割 page //mergepdf();// 合并 pdf 文件 //sortpage();// 排序page //setheaderfooter();// 页眉,页脚 //addcolumntext();// 左右文字 //setview();// 文档视图 //pdftozip();// 压缩pdf到zip addannotation();// 注释 /** * 创建一个 pdf 文件,并添加文本 */ public static void createpdf() throws ioexception, documentexception { // 实例化 document document = new document(); // 生成文件 string path = file_dir "createpdf.pdf"; file file = new file(path); if(!file.exists()){ file.createnewfile(); } pdfwriter.getinstance(document, new fileoutputstream(file_dir "createpdf.pdf")); // 打开 document document.open(); // 添加文本 此处无法写入中文 todo document.add(new paragraph(const_nezha)); document.add(new paragraph(const_nezha, static_font_chinese)); // 关闭 document document.close(); * 创建pdf文件,修改文件的属性 public static void createpdfwithcolor() throws filenotfoundexception, documentexception { // 页面大小 rectangle rect = new rectangle(pagesize.a5.rotate()); // 页面背景色 rect.setbackgroundcolor(basecolor.yellow); document = new document(rect); pdfwriter writer = pdfwriter.getinstance(document, new fileoutputstream(file_dir "createpdfwithcolor.pdf")); // pdf版本(默认1.4) writer.setpdfversion(pdfwriter.version_1_6); // 文档属性 document.addauthor(const_nezha); document.addtitle("我的第一个pdf"); // 页边空白 document.setmargins(10, 10, 10, 10); // 打开 // 关闭 * 创建带密码的pdf public static void createpdfwithpassword() throws filenotfoundexception, documentexception { pdfwriter writer = pdfwriter.getinstance(document, new fileoutputstream(file_dir "createpdfwithpassword.pdf")); // userpassword打开密码:"123" // ownerpassword编辑密码: "123456" writer.setencryption("123".getbytes(), "123456".getbytes(), pdfwriter.allow_screenreaders, pdfwriter.standard_encryption_128); * 为pdf添加页 public static void createpdfwithnewpages() throws filenotfoundexception, documentexception { pdfwriter writer = pdfwriter.getinstance(document, new fileoutputstream(file_dir "createpdfaddnewpages.pdf")); document.add(new paragraph(const_page_first, static_font_chinese)); document.newpage(); document.add(new paragraph(const_page_second, static_font_chinese)); writer.setpageempty(true); document.add(new paragraph(const_page_third, static_font_chinese)); * 为pdf文件添加水印,背景图 public static void createpdfwithwatermark() throws ioexception, documentexception { fileoutputstream out = new fileoutputstream(file_dir "createpdfwithwatermark.pdf"); pdfwriter.getinstance(document, out); // 图片水印 pdfreader reader = new pdfreader(file_dir "createpdfwithwatermark.pdf"); pdfstamper stamp = new pdfstamper(reader, new fileoutputstream(file_dir "createpdfwithwatermark2.pdf")); image img = image.getinstance(const_jpg_java); img.setabsoluteposition(200, 200); pdfcontentbyte under = stamp.getundercontent(1); under.addimage(img); // 文字水印 pdfcontentbyte over = stamp.getovercontent(2); // 加载字库来完成对字体的创建 basefont bf = basefont.createfont(basefont.helvetica, basefont.winansi, basefont.embedded); over.begintext(); // 设置颜色 默认为蓝色 over.setcolorfill(basecolor.red); // 设置字体字号 over.setfontandsize(bf, 50); // 设置起始位置 over.settextmatrix(30, 30); // 开始写入水印 左-下-倾斜度 over.showtextaligned(element.align_left, "nezha", 245, 400, 30); over.endtext(); // 背景图 image img2 = image.getinstance(const_jpg_nginx); img2.setabsoluteposition(0, 0); pdfcontentbyte under2 = stamp.getundercontent(3); under2.addimage(img2); stamp.close(); reader.close(); * 插入chunk, phrase, paragraph, list * chunk : 块,pdf文档中描述的最小原子元素 * phrase : 短语,chunk的集合 * paragraph : 段落,一个有序的phrase集合 public static void createpdfwithcontent() throws documentexception, filenotfoundexception { fileoutputstream out = new fileoutputstream(file_dir "createpdfwithcontent.pdf"); // 添加块 document.add(new chunk(const_nezha, static_font_chinese)); font font = new font(font.fontfamily.helvetica, 8, font.bold, basecolor.white); chunk id = new chunk("springboot", font); id.setbackground(basecolor.black, 1f, 0.5f, 1f, 1.5f); id.settextrise(7); document.add(id); font font2 = new font(font.fontfamily.helvetica, 6, font.bold, basecolor.white); chunk id2 = new chunk("springcloud", font2); id2.setbackground(basecolor.black, 1f, 0.5f, 1f, 1.5f); id2.settextrise(3); id2.setunderline(0.2f, -2f); document.add(id2); document.add(chunk.newline); // 添加一页,添加短语 document.add(new phrase("phrase page")); // 添加短语 phrase director = new phrase(); chunk name = new chunk(const_bibidong, static_font_chinese); // 添加下划线(thickness:下划线的粗细,yposition:下划线离字的距离) name.setunderline(0.5f, -1f); director.add(name); director.add(new chunk(",")); director.add(new chunk(" ")); director.add(new chunk(const_yunyun, static_font_chinese)); director.setleading(24); document.add(director); // 添加一页 phrase director2 = new phrase(); chunk name2 = new chunk(const_bibidong, static_font_chinese); name2.setunderline(0.2f, -2f); director2.add(name2); director2.add(new chunk(",")); director2.add(new chunk(" ")); director2.add(new chunk(const_yunyun, static_font_chinese)); director2.setleading(24); document.add(director2); // 添加段落 document.add(new paragraph("paragraph page")); paragraph info = new paragraph(); info.add(new chunk(const_nezha)); info.add(new chunk(const_bibidong)); info.add(chunk.newline); info.add(new phrase(const_nezha)); document.add(info); // 通过循环添加段落信息 list list = new list(list.ordered); for (int i = 0; i < 5; i ) { listitem item = new listitem(string.format("%s: %d " const_nezha, const_yunyun (i 1), (i 1) * 100), new font(font.fontfamily.helvetica, 6, font.bold, basecolor.white)); list girllist = new list(list.ordered, list.alphabetical); girllist.setlowercase(list.lowercase); for (int j = 0; j < 3; j ) { listitem girlitem = new listitem("girls" (j 1)); list rolelist = new list(list.unordered); for (int k = 0; k < 2; k ) { rolelist.add(string.format("%s, %s", const_nezha (k 1), const_bibidong (k 1))); } girlitem.add(rolelist); girllist.add(girlitem); } item.add(girllist); list.add(item); document.add(list); * 插入锚anchor, image, 章节chapter, 子列表section public static void createpdfwithextracontent() throws documentexception, malformedurlexception, ioexception { fileoutputstream out = new fileoutputstream(file_dir "createpdfwithextracontent.pdf"); string content = "you can get anything from : "; paragraph paragraph = new paragraph(content); // 创建一个链接到外部网站的新锚点 // 并将此锚点添加到段落中。 anchor anchor = new anchor(const_baidu, stmlayicatic_font_link); anchor.setreference(const_baidu_url); paragraph.add(anchor); document.add(paragraph); // image对象 image img = image.getinstance(const_jpg_nginx); img.setalignment(image.left | image.textwrap); img.setborder(image.box); img.setborderwidth(10); img.setbordercolor(basecolor.white); img.scaleto恰卡编程网fit(800, 50);// 大小 img.setrotationdegrees(-50);// 旋转 document.add(img); // 章节chapter -- 目录 paragraph title = new paragraph(const_title_first,static_font_chinese); // 标题和序号 chapter chapter = new chapter(title, 1); // 子列表section title = new paragraph(const_title_second,static_font_chinese); section section = chapter.addsection(title); section.setbookmarktitle(const_nezha); section.setindentation(10); section.setbookmarkopen(false); section.setnumberstyle(section.numberstyle_dotted_without_final_dot); section subsection1 = section.addsection(new paragraph(const_content,static_font_chinese)); subsection1.setindentationleft(10); subsection1.setnumberdepth(1); document.add(chapter); * 画图 public static void draw() throws exception { fileoutputstream out = new fileoutputstream(file_dir "draw.pdf"); // 左右箭头 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) { e.printstacktrace(); 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(const_nezha ,static_font_chinese); p1.add(new chunk(new lineseparator())); p1.add(const_bibidong); document.add(p1); // 点线 paragraph p2 = new paragraph(const_nezha ,static_font_chinese); p2.add(new chunk(new dottedlineseparator())); p2.add(const_bibidong); document.add(p2); // 下滑线 lineseparator underline = new lineseparator(1, 100, null, element.align_center, -2); paragraph p3 = new paragraph(const_nezha_program ,static_font_chinese); p3.add(underline); document.add(p3); * 设置段落 public static void createpdfwithalignment() throws exception { fileoutputstream out = new fileoutputstream(file_dir "createpdfwithalignment.pdf"); paragraph p = new paragraph("never frown, even when you are sad, because you never know who is falling in love with your smile;" "you will see exactly what life is worth, when all the rest has gone;" "it is very simple to be happy, but it is very difficult to be simple.恰卡编程网"); // 默认 p.setalignment(element.align_justified); document.add(p); // 慢慢的向右移动 p.setindentationleft(1 * 15f); p.setindentationright((5 - 1) * 15f); // 居右 p.setalignment(element.align_right); p.setspacingafter(15f); // 居左 p.setalignment(element.align_left); p.setspacingbefore(15f); // 居中 p.setalignment(element.align_center); * 删除页 public static void createpdftodeletepage() throws exception { fileoutputstream out = new fileoutputstream(file_dir "createpdftodeletepage.pdf"); pdfwriter writer = pdfwriter.getinstance(document, out); pdfreader reader = new pdfreader(file_dir "createpdftodeletepage.pdf"); reader.selectpages("1,3"); pdfstamper stamp = new pdfstamper(reader, new fileoutputstream(file_dir "createpdftodeletepage2.pdf")); * 插入 page public static void insertpage() throws exception { fileoutputstream out = new fileoutputstream(file_dir "insertpage.pdf"); pdfreader reader = new pdfreader(file_dir "insertpage.pdf"); pdfstamper stamp = new pdfstamper(reader, new fileoutputstream(file_dir "insertpage2.pdf")); stamp.insertpage(2, reader.getpagesize(1)); columntext ct = new columntext(null); ct.addelement(new paragraph(24, new chunk("insert page"))); ct.setcanvas(stamp.getovercontent(2)); ct.setsimplecolumn(36, 36, 559, 770); * 分割 page public static void splitpdf() throws exception { fileoutputstream out = new fileoutputstream(file_dir "splitpdf.pdf"); document.add(new paragraph(const_page_four, static_font_chinese)); 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); 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); cb2.addtemplate(writer2.getimportedpage(reader, 4), 0, 0); dd2.close(); writer2.close(); * 合并 pdf 文件 public static void mergepdf() throws exception { pdfreader reader1 = new pdfreader(file_dir "splitpdf1.pdf"); pdfreader reader2 = new pdfreader(file_dir "splitpdf2.pdf"); fileoutputstream out = new fileoutputstream(file_dir "mergepdf.pdf"); document document = new document(); java.util.list readers = new arraylist(); readers.add(reader1); readers.add(reader2); int pageofcurrentreaderpdf = 0; iterator iteratorpdfreader = readers.iterator(); while (iteratorpdfreader.hasnext()) { pdfreader pdfreader = iteratorpdfreader.next(); // 在目标中为每个源页面创建一个新页面 while (pageofcurrentreaderpdf < pdfreader.getnumberofpages()) { document.newpage(); pageofcurrentreaderpdf ; pdfimportedpage page = writer.getimportedpage(pdfreader, pageofcurrentreaderpdf); cb.addtemplate(page, 0, 0); pageofcurrentreaderpdf = 0; out.flush(); out.close(); * 排序page public static void sortpage() throws exception { fileoutputstream out = new fileoutputstream(file_dir "sortpage.pdf"); writer.setlinearpagemode(); document.add(new paragraph(const_page_five, static_font_chinese)); int[] order = { 4, 3, 2, 1 }; writer.reorderpages(order); * 页眉页脚 public static void setheaderfooter() throws exception { pdfwriter writer = pdfwriter.getinstance(document, 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) { e.printstacktrace(); 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(); document.add(new paragraph("1 page")); document.add(new paragraph("2 page")); document.add(new paragraph("3 page")); document.add(new paragraph("4 page")); public static void addcolumntext() throws exception { fileoutputstream out = new fileoutputstream(file_dir "addcolumntext.pdf"); pdfcontentbyte canvas = writer.getdirectcontent(); phrase phrase1 = new phrase(const_bibidong " is a beauty!left", static_font_chinese); phrase phrase2 = new phrase(const_bibidong " is a beauty!right", static_font_chinese); phrase phrase3 = new phrase(const_bibidong " is a beauty!center", static_font_chinese); columntext.showtextaligned(canvas, element.align_left, phrase1, 200, 700, 0); columntext.showtextaligned(canvas, element.align_right, phrase2, 200, 600, 0); columntext.showtextaligned(canvas, element.align_center, phrase3, 200, 500, 0); * 文档视图 public static void setview() throws exception { fileoutputstream out = new fileoutputstream(file_dir "setview.pdf"); writer.setpdfversion(pdfwriter.version_1_5); writer.setviewerpreferences(pdfwriter.pagemodefullscreen);// 全屏 public void onstartpage(pdfwriter writer, document document) { writer.settransition(new pdftransition(pdftransition.dissolve, 3)); writer.setduration(5);// 间隔时间 * 压缩pdf到zip public static void pdftozip() throws exception { zipoutputstream zip = new zipoutputstream(new fileoutputstream(file_dir "pdftozip.zip")); for (int i = 1; i <= 3; i ) { zipentry entry = new zipentry(const_nezha i ".pdf"); zip.putnextentry(entry); document = new document(); pdfwriter writer = pdfwriter.getinstance(document, zip); writer.setclosestream(false); document.open(); document.add(new paragraph(const_nezha i, static_font_chinese)); document.close(); zip.closeentry(); zip.close(); * 添加注释 public static void addannotation() throws exception { fileoutputstream out = new fileoutputstream(file_dir "addannotation.pdf"); document doc = new document(); pdfwriter writer = pdfwriter.getinstance(doc, out); doc.open(); doc.add(new paragraph(const_page_first, static_font_chinese)); doc.add(new annotation("title", "this is a annotation!")); doc.newpage(); doc.add(new paragraph(const_page_second, static_font_chinese)); chunk chunk = new chunk(const_nezha); chunk.setannotation(pdfannotation.createtext(writer, null, "title", "this is a another annotation!", false, "comment")); doc.add(chunk); // 添加附件 //doc.newpage(); //doc.add(new paragraph(const_page_third, static_font_chinese)); //chunk chunk2 = new chunk(const_bibidong, static_font_chinese); //pdfannotation annotation = pdfannotation.createfileattachment(writer, null, "title", null, const_jpg_java, const_jpg_nginx); //annotation.put(pdfname.name, new pdfstring("paperclip")); //chunk2.setannotation(annotation); //doc.add(chunk2); doc.close(); }

六、更多的java代码实例

【java 代码实例 1】java反射三种方法



【java 代码实例 4】javacompiler编译多java文件



【java 代码实例 6】fileutils、stringutil、collectionutils、arrayutils(附代码示例)

【java 代码实例 7】jsoup解析html

【java 代码实例 8】qrcode生成二维码

【java 代码实例 9】java通过process执行c# exe程序

到此这篇关于java操作pdf的工具类itext的文章就介绍到这了,更多相关javapdf的工具类itext内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

展开全文
内容来源于互联网和用户投稿,文章中一旦含有米乐app官网登录的联系方式务必识别真假,本站仅做信息展示不承担任何相关责任,如有侵权或涉及法律问题请联系米乐app官网登录删除

最新文章

网站地图