利用iText包实现Java报表打印

合集下载

java使用IText将数据导出为pdf文件(数据为excel表格样式)

java使用IText将数据导出为pdf文件(数据为excel表格样式)

java使⽤IText将数据导出为pdf⽂件(数据为excel表格样式)1.pom.xml导⼊使⽤的jar包<dependency><groupId>com.itextpdf</groupId><artifactId>itext-pdfa</artifactId><version>5.5.0</version></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version></dependency>2.直接上代码(数据导出为pdf⽂件,数据呈现样式为⾃定义excel表格样式,⽀持多页展⽰)public class DataToPdf {public static final String DEST = "pdf/tables.pdf";public static void main(String[] args) throws IOException, DocumentException {File file = new File(DEST);file.getParentFile().mkdirs();new DataToPdf().dataToPdf(DEST);}/*** 数据转pdf* @param dest* @throws IOException* @throws DocumentException*/public void dataToPdf(String dest) throws IOException, DocumentException {Document document = new Document();PdfWriter.getInstance(document, new FileOutputStream(dest));document.open();// 使⽤语⾔包字体BaseFont abf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);//字体Font font = new Font(abf, 8);//段落Paragraph p = new Paragraph("测试结算单", new Font(abf, 12, Font.BOLD));p.setAlignment(Paragraph.ALIGN_CENTER);document.add(p);//表格PdfPTable table = new PdfPTable(8);//numcolumns:列数table.setSpacingBefore(16f);//表格与上⾯段落的空隙//表格列创建并赋值PdfPCell cell = new PdfPCell(new Phrase("单位名称:测试有限公司", font));cell.setHorizontalAlignment(Element.ALIGN_LEFT);//居中cell.disableBorderSide(13);//去除左右上边框,保留下边框cell.setColspan(4);//合并列数table.addCell(cell);cell = new PdfPCell(new Phrase("⽇期:2020-06-05", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);cell.disableBorderSide(13);cell.setColspan(3);table.addCell(cell);cell = new PdfPCell(new Phrase("单位(元)", font));cell.setHorizontalAlignment(Element.ALIGN_LEFT);cell.disableBorderSide(13);cell.setColspan(1);table.addCell(cell);//⾸⾏cell = new PdfPCell(new Phrase("期间", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);cell.setColspan(2);table.addCell(cell);cell = new PdfPCell(new Phrase("⽉份", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("分类", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("年利率", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("⽇利率", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("基数", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("利息", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("起始⽇:2020-03-26\n" +"结束⽇:2020-04-25", font));cell.setPadding(16f);cell.setVerticalAlignment(Element.ALIGN_CENTER);cell.setHorizontalAlignment(Element.ALIGN_CENTER);cell.setRowspan(3);cell.setColspan(2);table.addCell(cell);cell = new PdfPCell(new Phrase("4", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("10598164.91", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("325.01", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("4", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("资⾦", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("1.10%", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("0.000031", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("-", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("-", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("4", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("资⾦", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("1.10%", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("0.000031", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("-", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("-", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("合计", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);cell.setColspan(7);table.addCell(cell);cell = new PdfPCell(new Phrase("325.01", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("会计制单:", font));cell.setHorizontalAlignment(Element.ALIGN_LEFT);cell.disableBorderSide(14);cell.setColspan(4);table.addCell(cell);cell = new PdfPCell(new Phrase("复核:", font));cell.setHorizontalAlignment(Element.ALIGN_LEFT);cell.disableBorderSide(14);cell.setColspan(4);table.addCell(cell);table.setSpacingBefore(16f);document.add(table);//下⼀页document.newPage();//段落Paragraph p1 = new Paragraph("下⼀页测试结算单", new Font(abf, 12, Font.BOLD)); p1.setAlignment(Paragraph.ALIGN_CENTER);document.add(p1);//表格table = new PdfPTable(8);//numcolumns:列数table.setSpacingBefore(16f);//表格与上⾯段落的空隙//表格列创建并赋值cell = new PdfPCell(new Phrase("单位名称:测试有限公司", font));cell.setHorizontalAlignment(Element.ALIGN_LEFT);//居中cell.disableBorderSide(13);//去除左右上边框,保留下边框cell.setColspan(4);//合并列数table.addCell(cell);cell = new PdfPCell(new Phrase("⽇期:2020-06-05", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);cell.disableBorderSide(13);cell.setColspan(3);table.addCell(cell);cell = new PdfPCell(new Phrase("单位(元)", font));cell.setHorizontalAlignment(Element.ALIGN_LEFT);cell.disableBorderSide(13);cell.setColspan(1);table.addCell(cell);//⾸⾏cell = new PdfPCell(new Phrase("期间", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);cell.setColspan(2);cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("⽇利率", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("基数", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("利息", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("起始⽇:2020-04-26\n" +"结束⽇:2020-05-25", font));cell.setPadding(16f);cell.setVerticalAlignment(Element.ALIGN_CENTER);cell.setHorizontalAlignment(Element.ALIGN_CENTER);cell.setColspan(2);table.addCell(cell);cell = new PdfPCell(new Phrase("4", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("资⾦", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("1.10%", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("0.000031", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("10598164.91", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("325.01", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("合计", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);cell.setColspan(7);table.addCell(cell);cell = new PdfPCell(new Phrase("325.01", font));cell.setHorizontalAlignment(Element.ALIGN_CENTER);table.addCell(cell);cell = new PdfPCell(new Phrase("会计制单:", font));cell.setHorizontalAlignment(Element.ALIGN_LEFT);cell.disableBorderSide(14);cell.setColspan(4);table.addCell(cell);cell = new PdfPCell(new Phrase("复核:", font));cell.setHorizontalAlignment(Element.ALIGN_LEFT);cell.disableBorderSide(14);cell.setColspan(4);table.addCell(cell);table.setSpacingBefore(16f);document.add(table);document.close();}}3.上述代码中对于IText字体设置可改:使⽤iText中的字体例:BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);使⽤Windows系统⾃带的字体例:BaseFont.createFont("C:/WINDOWS/Fonts/SIMYOU.TTF", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED); 使⽤外部引⼊的资源字体(例:BaseFont.createFont("/SIMYOU.TTF", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);4.上述代码⽣成的表格边框隐藏⽅式:1:代表上边框2:代表下边框4:代表左边框8:代表右边框//需要隐藏那些边框就把对应的值加起来,得到的和就是要设置的值//⽐如要隐藏左右边框就是 4+8=12cell.disableBorderSide(12);//左右没了具体例⼦://隐藏上边框cell.disableBorderSide(1);//隐藏下边框cell.disableBorderSide(2);//隐藏左、上边框cell.disableBorderSide(5);//隐藏左、下边框cell.disableBorderSide(6);//隐藏左、上、下边框cell.disableBorderSide(7);//隐藏右边框cell.disableBorderSide(8);//隐藏右、上边框cell.disableBorderSide(9);//隐藏右、下边框cell.disableBorderSide(10);//隐藏右、上、下边框cell.disableBorderSide(11);//隐藏左、右边框cell.disableBorderSide(12);//左右没了 //隐藏上、左、右边框cell.disableBorderSide(13);//只剩下 //隐藏下、左、右边框cell.disableBorderSide(14);//只剩上//隐藏全部cell.disableBorderSide(15);//全没了5.运⾏展⽰效果例:。

在ASP.Net中利用iTextSharp实现报表输出功能

在ASP.Net中利用iTextSharp实现报表输出功能
限 , 同 浏 览器 的打 印 结 果 也 存在 很 大 差 异 。通 过 客 户端 的浏 不 览 器控 制打 印机 完成 精确 的 打 印 结 果 ,实 现 起 来 是 相 对 困难 的 。 以 系 统 生 成 一 个 PDF文 档 发 送 给 客 户 端 , 一 个 很 好 的 所 是
来 存 放 我们 系 统 已经 生 成 的 P DF文 档 , 项 目 “ y p” 再 在 M Ap 中
理 系统实现报表输 出功能是个可行的思路。来 自第三方的开源组件 i x#可 以很好地实现 P Tet DF文件的 生成 . 用
iet 够很 方便 地 制 作 出精 美 的 P T x#能 DF报表 文件 , 过 实例 对 i x# 的应 用 方 法进 行 了讲 解 。 通 Tet
【 关冀词】 信息管理系统 A P E 报表 P F文档 iet S. T N D Tx≠ ≠
实 现精 美报 表 输 出 的办 法 。 经 过 各种 尝试 , 最 终 选 择 了可 以 我 精 确控 制 P DF报表 输 出 的第 三 方 组 件 i x#。 在这 里 简 单 介 Te t
绍 一 下 ie t T x #是 如 何 实 现 报 表 输 出 功 能 的 。
usng i i Tex Shar t xtpdf t p.e . ;
新 建~ 个 文 件 夹 , 名 为 i g s 用 来 存 放我 们 准 备 好 的 图 像 命 ma e ,
素 材 ,在 本 实 例 中 我 们 放 入 一 个 i 1Jg文 件 , 分 辨 率 为 mO . P
400 X 2 30。
第 五 , 加一个新 的 We 添 b窗 体 , 名 为 rn.s x, rn 命 u ap 在 u .
Do u c me t d c m e t= n w c me t ( a e z A4 0 n o u n e Do u n P g Si e. ,3

Java使用itext5实现PDF表格文档导出

Java使用itext5实现PDF表格文档导出

Java使⽤itext5实现PDF表格⽂档导出最近拿到⼀个需求,需要导出PDF⽂档,市⾯上可以实现的⽅法有很多,经过测试和调研决定使⽤itext5来实现,话不多说,说⼲就⼲。

1.依赖导⼊<!-- https:///artifact/com.itextpdf/itextpdf --><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.13.1</version></dependency><!-- https:///artifact/com.itextpdf/itext-asian --><dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version></dependency>这⾥说明下:上⾯的依赖就是主要实现PDF⽣成的,下⾯的依赖是中⽂字体相关依赖;2.PDF表格导出实现1.导出PDF// 1.打开⽂档并设置基本属性Document document = new Document();// 2.设置请求头,encode⽂件名response.setContentType("application/pdf;charset=UTF-8");response.setHeader("Content-Disposition","attachment; filename=" + .URLEncoder.encode("" +recordDto.getTitle() + ".pdf", "UTF-8"));// 3.通过流将pdf实例写出到浏览器PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());⾄此导出PDF已经实现了,只是这个PDF中什么内容都没有,明⽩这⼀点,接下来做的就是给这个⽂档“加料”咯(这⾥的response就是HttpServletResponse)。

java使用IText生成表格到PDF中

java使用IText生成表格到PDF中

1.生成pdf的表格package com.me.test;import java.awt.Color;import java.io.FileOutputStream;import com.lowagie.text.Cell;import com.lowagie.text.Document;import com.lowagie.text.Element;import com.lowagie.text.Font;import com.lowagie.text.PageSize;import com.lowagie.text.Paragraph;import com.lowagie.text.Table;import com.lowagie.text.pdf.BaseFont;import com.lowagie.text.pdf.PdfWriter;/*** 生成表格到硬盘** @author admin**/public class ITextTest {public void getTable(){try {Document document = new Document(PageSize.A4, 20, 20, 20, 20);PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream(";f:/IText/table.pdf";));document.open();BaseFont bfChinese;bfChinese = BaseFont.createFont(";STSong-Light";, ";UniGB-UCS2-H";,false);Font fontChinese = new Font(bfChinese, 9, Font.BOLD, Color.black);Table t = new Table(12, 2);// t.setBorderColor(new Color(220, 255, 100));int width[] = { 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, };t.setWidths(width);t.setWidth(100); // 占页面宽度 %t.setPadding(1);t.setSpacing(0);t.setBorderWidth(2);Cell c1 = new Cell(";header1";);t.addCell(c1);c1 = new Cell(";Header2";);t.addCell(c1);c1 = new Cell(";Header3";);t.addCell(c1);c1 = new Cell(";Header4";);t.addCell(c1);c1 = new Cell(";Header5";);t.addCell(c1);c1 = new Cell(";Header6";);t.addCell(c1);c1 = new Cell(";Header7";);t.addCell(c1);c1 = new Cell(";Header8";);t.addCell(c1);c1 = new Cell(";Header9";);t.addCell(c1);c1 = new Cell(";Header10";);t.addCell(c1);c1 = new Cell(";Header11";);t.addCell(c1);c1 = new Cell(";Header12";);t.addCell(c1);int k = 0;while (k <; 3) {for (int q = 0; q <; 12; q++) {Paragraph par = new Paragraph(k + ";-"; + q, fontChinese);c1 = new Cell(par);c1.setHorizontalAlignment(Element.ALIGN_CENTER);t.addCell(c1);}k++;}for (int i = 0; i <; 24; i++) {String num = Integer.toString(i);c1.setHorizontalAlignment(Element.ALIGN_CENTER);c1 = new Cell(num);c1.setColspan(2);c1.setRowspan(1);t.addCell(c1);}c1 = new Cell(";26";);t.addCell(c1);document.add(t);// 创建一个新页面document.newPage();document.add(t);document.close();} catch (Exception e2) {e2.printStackTrace();}}}2.将网页中的信息,用pdf格式文件弹出package com.me.test;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.OutputStream;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.itextpdf.text.Document;import com.itextpdf.text.DocumentException;import com.itextpdf.text.Paragraph;import com.itextpdf.text.pdf.PdfWriter;/*** 在网页上获取信息,查看pdf格式文件* @author admin**/public class PdfServlet extends HttpServlet {/*** @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)*/protected void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {try {// Get the text that will be added to the PDFString text = request.getParameter(";text";);if (text == null || text.trim().length() == 0) {text = ";You didn't enter any text.";;}// step 1Document document = new Document();// step 2ByteArrayOutputStream baos = new ByteArrayOutputStream();PdfWriter.getInstance(document, baos);// step 3document.open();// step 4document.add(new Paragraph(String.format(";You have submitted the following text using the %s method:";, request.getMethod())));document.add(new Paragraph(text));// step 5document.close();// setting some response headersresponse.setHeader(";Expires";, ";0";);response.setHeader(";Cache-Control";,";must-revalidate, post-check=0, pre-check=0";);response.setHeader(";Pragma";, ";public";);// setting the content typeresponse.setContentType(";application/pdf";);// the contentlengthresponse.setContentLength(baos.size());// write ByteArrayOutputStream to the ServletOutputStreamOutputStream os = response.getOutputStream();baos.writeTo(os);os.flush();os.close();}catch(DocumentException e) {throw new IOException(e.getMessage());}}/*** Serial version UID.*/private static final long serialVersionUID = 6067021675155015602L; }3.在网页上直接以pdf的形式显示package com.me.test;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.lowagie.text.Document;import com.lowagie.text.DocumentException;import com.lowagie.text.pdf.PdfWriter;import com.lowagie.text.Element;import com.lowagie.text.PageSize;import com.lowagie.text.pdf.PdfPTable;/*** 直接在网页中生成PDF格式查看*//*** Hello World example as a Servlet.** @author blowagie*/public class HelloWorldServlet extends HttpServlet {/****/private static final long serialVersionUID = 3710911016238241119L;/*** Returns a PDF, RTF or HTML document.** @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)*/public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {System.out.println(";document.add(BigTable)";);// step1Document document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10); //定义纸张类型及方向,页边距// step 1try {// step 2: we set the ContentType and create an instance of the corresponding Writerresponse.setContentType(";application/pdf";);PdfWriter.getInstance(document, response.getOutputStream());// step3document.open();// step4 定义表格填充内容String[] bogusData = { ";M0065920";, ";SL";, ";FR86000P";, ";PCGOLD";,";119000";, ";96 06";, ";2001-08-13";, ";4350";, ";6011648299";,";FLFLMTGP";, ";153";, ";119000.00"; };int NumColumns = 12; //定义表格列数PdfPTable datatable = new PdfPTable(NumColumns); //创建新表.int headerwidths[] = { 9, 4, 8, 10, 8, 11, 9, 7, 9, 10, 4, 10 }; // percentage 定义表格头宽度datatable.setWidths(headerwidths);datatable.setWidthPercentage(100); // percentagedatatable.getDefaultCell().setPadding(3);datatable.getDefaultCell().setBorderWidth(2);datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);//以下是填充表头datatable.addCell(";Clock #";);datatable.addCell(";Trans Type";);datatable.addCell(";Cusip";);datatable.addCell(";Long Name";);datatable.addCell(";Quantity";);datatable.addCell(";Fraction Price";);datatable.addCell(";Settle Date";);datatable.addCell(";Portfolio";);datatable.addCell(";ADP Number";);datatable.addCell(";Account ID";);datatable.addCell(";Reg Rep ID";);datatable.addCell(";Amt To Go ";);datatable.setHeaderRows(1); // this is the end of the table headerdatatable.getDefaultCell().setBorderWidth(1);for (int i = 1; i <; 750; i++) {if (i % 2 == 1) {datatable.getDefaultCell().setGrayFill(0.9f);}for (int x = 0; x <; NumColumns; x++) {datatable.addCell(bogusData[x]);}if (i % 2 == 1) {datatable.getDefaultCell().setGrayFill(0.0f);}}document.add(datatable); //加载新表}catch(DocumentException de) {de.printStackTrace();System.err.println(";document: "; + de.getMessage());}// step 5: we close the document (the outputstream is also closed internally) document.close();}}4.生成PDF到计算机中package com.me.test;import java.awt.*;import java.io.*;import com.lowagie.text.*;import com.lowagie.text.Font;import com.lowagie.text.Image;import com.lowagie.text.Rectangle;import com.lowagie.text.pdf.BaseFont;import com.lowagie.text.pdf.PdfContentByte;import com.lowagie.text.pdf.PdfReader;import com.lowagie.text.pdf.PdfWriter;/*** 通过给定的短语生成pdf文件,并且加密*//*** First iText example: Hello World.*/public class HelloWorld {/** Path to the resulting PDF file. */public static final String RESULT = ";f:/hello.pdf";;public static final String pwd = ";123456";;public static final String result = ";f:/Itext/b.gif";;/*** Creates a PDF file: hello.pdf** @param args* no arguments needed*/public static void main(String[] args) throws DocumentException, IOException {new HelloWorld().createPdf(RESULT);}/*** Creates a PDF document.** @param filename* the path to the new PDF document* @throws DocumentException* @throws IOException*/public void createPdf(String filename) throws DocumentException, IOException {// 设定文本样式Rectangle rec = new Rectangle(PageSize.A4);rec.setBackgroundColor(Color.GRAY);rec.setBorder(Rectangle.TOP);rec.setBorderColor(Color.black);rec.setBorderWidth(50);// 创建本文Document doc = new Document(rec, 100, 201, 20, 20);// 设定路径PdfWriter pdf = PdfWriter.getInstance(doc, new FileOutputStream(HelloWorld.RESULT));// 设定布局pdf.setViewerPreferences(PdfWriter.PageModeUseThumbs| PdfWriter.PageLayoutTwoColumnLeft | PdfWriter.HideMenubar);// 加密pdf.setEncryption(pwd.getBytes(), pwd.getBytes(), PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_40);// 设置中文BaseFont base = null;Font fontChinese = null;try {base = BaseFont.createFont(";STSong-Light";, ";UniGB-UCS2-H";,BaseFont.EMBEDDED);fontChinese = new Font(base, 18, Font.BOLD);} catch (DocumentException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}doc.open();doc.add(new Paragraph(";你好我是Pro";, fontChinese));doc.close();}}。

iText 生成 PDF (java)

iText 生成 PDF (java)

iText 生成PDF (java)标签:itextpdfit 分类:java技术文档public class BL {***// private String rgtno = "580401000130";private SSRS ssrsRgtno = new SSRS();// rgtno 赔案号,grpcontno 团体保单号,grpname// 投保单位,endcasedate 结案日期private SSRS ssrsCustomerno = new SSRS();// customerno客户号private SSRS ssrsIdno = new SSRS();// idno 证件号,bankcode 银行编码,bankaccno// 账号,accname 户名private SSRS ssrsOpt = new SSRS();// 门诊医疗费用理算信息:private SSRS ssrsHos = new SSRS();// 住院医疗费用理算信息:private SSRS ssrsBirth = new SSRS();// 生育医疗费用理算信息:private SSRS sumSsrsOpt = new SSRS();// 门诊医疗费用理算信息:总计private SSRS sumSsrsHos = new SSRS();// 住院医疗费用理算信息:总计private SSRS sumSsrsBirth = new SSRS();// 生育医疗费用理算信息:总计public boolean batchPrint() throws DocumentException, IOException {String rgtno = "580401000130";String rgtno2 = "580401000131";String rgtno3 = "580501000012";ArrayList rgtnoList = new ArrayList();rgtnoList.add(rgtno);rgtnoList.add(rgtno2);rgtnoList.add(rgtno3);Document document = new Document(PageSize.A4, 10, 10, 60, 20);// 参数:第一个是页面大小;接下来是左右上下边距;try {// // 生成名为xxx的文档PdfWriter.getInstance(document, new FileOutputStream("D:\\ITextTest.pdf"));BaseFont bfChinese = BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);Color colorGray = new Color(217, 217, 217);Color colorBlack = new Color(0, 0, 0);Font titleFont = new Font(bfChinese, 21, Font.BOLD, colorBlack);Font infoFont = new Font(bfChinese, 11, Font.NORMAL, colorBlack);Font infoLittleNormal = new Font(bfChinese, 10, Font.NORMAL,colorBlack);Font infoLittleBold = new Font(bfChinese, 10, Font.BOLD, colorBlack);document.open();for (int i = 0; i < rgtnoList.size(); i++) {String rgtn22o =rgtnoList.get(i).toString();// 查询数据selectData(rgtn22o);// 打开文档,将要写入内容document.newPage();// 插入图片:可以是绝对路径,也可以是URL// String path = "D:\\tkyl.bmp";String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();if (path.indexOf( "newlisnew") > 0) {path = path.substring(0, path.indexOf( "/newlisnew/") + 11);}path = path + "ui\\common\\images\\tkyl.bmp";// String path = "D:\\tkyl.bmp";printImage(document, path);// 打印PDF头部信息printHead(document, titleFont, infoFont);// 打印空白表格printBlank(document, titleFont);printInfoTable(document, infoFont);// 门诊医疗费用理算信息String strOpt = " 门诊医疗费用理算信息";// 门诊医疗费用理算信息,表头printInfoTable(document, strOpt, infoLittleBold,infoLittleNormal, colorGray, ssrsOpt, sumSsrsOpt);// 住院医疗费用理算信息String strHos = " 住院医疗费用理算信息";// 门诊医疗费用理算信息,表头printInfoTable(document, strHos, infoLittleBold,infoLittleNormal, colorGray, ssrsHos, sumSsrsHos);// 生育医疗费用理算信息String strBirth = " 生育医疗费用理算信息";// 门诊医疗费用理算信息,表头printInfoTable(document, strBirth, infoLittleBold,infoLittleNormal, colorGray, ssrsBirth, sumSsrsBirth);// 打印PDF结尾部分printEndInfoTable(document, infoFont, colorGray);}} catch (DocumentException de) {System.err.println(de.getMessage());} catch (IOException ioe) {System.err.println(ioe.getMessage());}document.close();return true;}public void setAlignment(PdfPCell pdfPCell, int verticalAlign,int horizontalAlign) {if (verticalAlign == Element.ALIGN_MIDDLE) {pdfPCell.setVerticalAlignment(Element.ALIGN_MIDDLE);// 垂直居中} else if (verticalAlign == Element.ALIGN_TOP) {pdfPCell.setVerticalAlignment(Element.ALIGN_TOP);// 垂直上居中} else if (verticalAlign == Element.ALIGN_BOTTOM) {pdfPCell.setVerticalAlignment(Element.ALIGN_BOTTOM);// 垂直下居中}if (horizontalAlign == Element.ALIGN_CENTER) {pdfPCell.setHorizontalAlignment(Element.ALIGN_CENTER);// 水平居中} else if (horizontalAlign == Element.ALIGN_LEFT) {pdfPCell.setHorizontalAlignment(Element.ALIGN_LEFT);// 水平左居中} else if (horizontalAlign == Element.ALIGN_RIGHT) {pdfPCell.setHorizontalAlignment(Element.ALIGN_RIGHT);// 水平右居中}}public void setOptInfoStyle(PdfPCell pdfPCell) {setDisableBorder(pdfPCell, 0, 0, 4, 8);// 上下边框显示,左右边框不显示。

iTextSharp做C#的PDF打印和下载

iTextSharp做C#的PDF打印和下载

基于iTextSharp的PDF操作(PDF打印,PDF下载)准备1. iTextSharp的简介iTextSharp是一个移植于java平台的iText项目,被封装成c#的组件来用于C#生成PDF 文档,目前,也有不少操作PDF的类库,(国产的有福盺的,免费试用,用于商业用途收费)但是功能普遍没有iText强大,而且使用没有iText广泛。

还有他就是开源的。

目前比较新的是5.5版本的。

2. 使用工具硬件:PC机:一台软件:Windows操作系统Isual studio 2013 (可以是任意版本).Net frameWork 4.5 (可以是任意版本)iTextSharp 5.5 可以到官网下载(iTextSharp)/projects/itextsharp/下载后,解压得到iTextSharp.dll文件基本知识1. 主要对象1).Document 对象:Document 对象主要用于操作页面的大小,就是页面的尺寸。

页面的尺寸一般有以下几种:A0-A10, LEGAL, LETTER, HALFLETTER, _11x17, LEDGER, NOTE, B0-B5, ARCH_A-ARCH_E, FLSA 和 FLSE,例如,需要创建一个A4纸张大小的PDF文档:Document document = new Document(PageSize.A4);这个文档漠然是纵向的,如果满足不了你横向文档的需要,可以加上rotate属性。

有的时候,我们需要生成特定颜色的,特定大小的PDF文档,可以使用下面的方法Rectangle pageSize = new Rectangle(120, 520); //120*520规格pageSize.BackgroundColor = new Color(0xFF, 0xFF, 0xDE); //背景色Document document = new Document(pageSize); //新建Documen对象页边距:Document document = new Document(PageSize.A5, 36, 72, 108, 180);//默认单位为磅。

Java_实现iReport打印

Java_实现iReport打印

iReport报表打印功能代码编写环境系统:windows xp开发工具:Myeclipes6.0JDK版本:Java6(jdk6.0,jre6.0)服务器:Tomcat5.5Ireport版本:iReport-2.0.5 windows 安装版(iReport-2.0.5-windows-installer.exe)实现步骤一、iReport-2.0.5安装。

选择安装路径默认安装(一直点击下一步)。

二、将iReprot的jasperreports-2.0.5.jar文件复制到Myeclipes中你工程的WEB-INF/lib目录下。

jasperreports-2.0.5.jar文件所在位置在你iReprot的安装路径下,我的是C:\Program Files\JasperSoft\iReport-2.0.5\lib。

三、要实现打印的Jsp文件编写,Jsp文件中打印按钮或者打印连接应该提交给一个javascript,具体代码如:<a href="javascript: print(${exammanage.oid })"><fontcolor="blue">打印</font></a>javascript代码如下function print(oid){if(!confirm("确定要打印该资格证吗?"))return ;window.showModalDialog('${ctx}/exam/exammanage/examprint_cert.jsp?oid='+oid,'','dialogWidth:50px;dialogHeight:150px;dialogTop:1000px;dialogLef t:1000px');document.forms[0].flg.value = "0";document.forms[0].action="${ctx}/ExamPermitPrint.html";document.forms[0].submit();}代码解释:1、window.showModalDialog('${ctx}/exam/exammanage/examprint_cert.jsp?oid='+oid,'','dialogWidth:50px;dialogHeight:150px;dialogTop:1000px;dialogLef t:1000px');此段的功能是显示打印提示窗口,我的文件是WebRoot路径下/exam/exammanage/路径下的examprint_cert.jsp文件,而且需要传一个你所要打印的记录的唯一字段(数据库中唯一代表一条记录的字段),我这里用OID。

Java使用IText(VM模版)导出PDF,IText导出word(二)

Java使用IText(VM模版)导出PDF,IText导出word(二)

Java使⽤IText(VM模版)导出PDF,IText导出word(⼆)===============action===========================//退款导出wordpublic void exportWordTk() throws IOException{Long userId=(Long)ServletActionContext.getContext().getSession().get(Constant.SESSION_USER_ID);//获取⽣成Pdf需要的⼀些路径String tmPath=ServletActionContext.getServletContext().getRealPath("download/template");//vm 模板路径String wordPath=ServletActionContext.getServletContext().getRealPath("download/file");//⽣成word路径//wordPath+"/"+userId+"_"+fk+".doc"//数据Map map=new HashMap();//velocity模板中的变量map.put("date1",this.fk);map.put("date",new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()));String newFile=wordPath+"/tk_word_"+userId+".doc";File file=new File(newFile);if(!file.exists()){//设置字体,⽀持中⽂显⽰new PdfUtil().addFontAbsolutePath(ServletActionContext.getServletContext().getRealPath("dzz/pdfFont/simsun.ttf"));//这个字体需要⾃⼰去下载PdfUtil.createByVelocityPdf(tmPath,"tk_word.vm", wordPath+"/tk_word_"+userId+".pdf", map);//导出PDFPdfUtil.createByVelocityDoc(tmPath,"tk_word.vm",newFile, map);//导出word}sendMsgAjax("dzz/download/file/tk_word_"+userId+".doc");}=================vm ⽂件模板(tk_word.vm)=====================<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title></title><style type="text/css">body, button, input, select, textarea {color: color:rgb(0,0,0);font: 14px/1.5 tahoma,arial,宋体,sans-serif;}p{margin:0;padding:0;}.title{border-bottom:1px solid rgb(0,0,0);margin:0;padding:0;width:85%;height:25px;}li{list-style:none;}.li_left li{text-align:left;line-height:47px;font-size:14pt;}.li_left{width:610px;}.fnt-21{font-size:16pt;}table{width:90%;/*argin-left:25px;*/}div_cls{width:100%;text-align:center;}</style></head><body style="font-family: songti;width:100%;text-align:center;"><div style="text-align:center;"><b class="fnt-21">&nbsp;&nbsp;本组评审结果清单</b> </div> <table border="1" cellpadding="0" cellspacing="0" style="width:90%;margin-left:25px;"> <tr><td style="width:20%" align="center">申报单位</td><td style="width:10%" align="center">申报经费(万元)</td></tr></table><br/><div><ul style="float:right;margin-right:40px;"><li>$date</li><!--获取后天封装的数据--></ul></div></body></html>====================⼯具类======================package com.qgc.dzz.util;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.io.PrintWriter;import .URL;import java.util.ArrayList;import java.util.List;import java.util.Map;import java.util.UUID;import org.apache.struts2.ServletActionContext;import org.apache.velocity.Template;import org.apache.velocity.VelocityContext;import org.apache.velocity.app.VelocityEngine;import org.xhtmlrenderer.pdf.ITextFontResolver;import org.xhtmlrenderer.pdf.ITextRenderer;import com.lowagie.text.Document;import com.lowagie.text.DocumentException;import com.lowagie.text.Font;import com.lowagie.text.Image;import com.lowagie.text.Rectangle;import com.lowagie.text.pdf.BaseFont;import com.lowagie.text.pdf.PdfImportedPage;import com.lowagie.text.pdf.PdfReader;import com.lowagie.text.pdf.PdfWriter;public class PdfUtil {private static List<String> fonts = new ArrayList();//字体路径/*** 使⽤vm导出word* @param localPath VM 模板路径* @param templateFileName vm 模板名称* @param docPath ⽣成⽂件的路径,包含⽂件如:d://temp.doc* @param map 参数,传递到vm* @return*/public static boolean createByVelocityDoc(String localPath, String templateFileName, String docPath, Map<String, Object> map) {try{createFile(localPath,templateFileName,docPath, map);return true;} catch (Exception e) {e.printStackTrace();}return false;}/*** 导出pdf* @param localPath VM 模板路径* @param templateFileName vm 模板名称* @param pdfPath ⽣成⽂件的路径,包含⽂件如:d://temp.pdf* @param map 参数,传递到vm* @return*/public static boolean createByVelocityPdf(String localPath, String templateFileName, String pdfPath, Map<String, Object> map) {try{String htmlPath = pdfPath + UUID.randomUUID().toString() + ".html";createFile(localPath, templateFileName, htmlPath, map);//⽣成html 临时⽂件HTML2OPDF(htmlPath, pdfPath, fonts);//html转成pdfFile file = new File(htmlPath);file.delete();return true;} catch (Exception e) {e.printStackTrace();}return false;}/*** 合并PDF* @param writer* @param document* @param reader* @throws DocumentException*/public void addToPdfUtil(PdfWriter writer, Document document,PdfReader reader) throws DocumentException {int n = reader.getNumberOfPages();Rectangle pageSize = document.getPageSize();float docHeight = pageSize.getHeight();float docWidth = pageSize.getWidth();for (int i = 1; i <= n; i++) {document.newPage();PdfImportedPage page = writer.getImportedPage(reader, i);Image image = Image.getInstance(page);float imgHeight = image.getPlainHeight();float imgWidth = image.getPlainWidth();if (imgHeight < imgWidth) {float temp = imgHeight;imgHeight = imgWidth;imgWidth = temp;image.setRotationDegrees(90.0F);}if ((imgHeight > docHeight) || (imgWidth > docWidth)) {float hc = imgHeight / docHeight;float wc = imgWidth / docHeight;float suoScale = 0.0F;if (hc > wc)suoScale = 1.0F / hc * 100.0F;else {suoScale = 1.0F / wc * 100.0F;}image.scalePercent(suoScale);}image.setAbsolutePosition(0.0F, 0.0F);document.add(image);}}/*** html 转成 pdf ⽅法* @param htmlPath html路径* @param pdfPath pdf路径* @param fontPaths 字体路径* @throws Exception*/public static void HTML2OPDF(String htmlPath, String pdfPath,List<String> fontPaths)throws Exception{String url = new File(htmlPath).toURI().toURL().toString();//获取⽣成html的路径OutputStream os = new FileOutputStream(pdfPath);//创建输出流ITextRenderer renderer = new ITextRenderer();//itext 对象ITextFontResolver fontResolver = renderer.getFontResolver();//字体// //⽀持中⽂显⽰字体// fontResolver.addFont(ServletActionContext.getServletContext().getRealPath("dzz/pdfFont/simsun_0.ttf"), // BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);if ((fontPaths != null) && (!fontPaths.isEmpty())) {URL classPath = PdfUtil.class.getResource("/");for (String font : fontPaths) {if (font.contains(":"))fontResolver.addFont(font, "Identity-H", false);else {fontResolver.addFont(classPath + "/" + font, "Identity-H",false);}}}renderer.setDocument(url);//设置html路径yout();renderer.createPDF(os);//html转换成pdfSystem.gc();os.close();System.gc();}public static boolean createFile(String localPath, String templateFileName,String newFilePath, Map<String, Object> map){try{VelocityEngine engine = new VelocityEngine();engine.setProperty("file.resource.loader.path", localPath);//指定vm路径Template template = engine.getTemplate(templateFileName, "UTF-8");//指定vm模板VelocityContext context = new VelocityContext();//创建上下⽂对象if (map != null){Object[] keys = map.keySet().toArray();for (Object key : keys) {String keyStr = key.toString();context.put(keyStr, map.get(keyStr));//传递参数到上下⽂对象}}PrintWriter writer = new PrintWriter(newFilePath, "UTF-8");//写⼊参数到vm template.merge(context, writer);writer.flush();writer.close();return true;} catch (Exception e) {e.printStackTrace();}return false;}public static Font FONT = getChineseFont();public static BaseFont BSAE_FONT = getBaseFont();/*** ⽀持显⽰中⽂* @return*/public static Font getChineseFont() {BaseFont bfChinese = null;try {bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);} catch (DocumentException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}Font fontChinese = new Font(bfChinese);return fontChinese;}public static BaseFont getBaseFont() {BaseFont bfChinese = null;try {bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);} catch (DocumentException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return bfChinese;}public void addFontAbsolutePath(String path) {this.fonts.add(path);}public void addFontClassPath(String path) {this.fonts.add(path);}public List<String> getFonts() {return this.fonts;}public void setFonts(List<String> fonts) {this.fonts = fonts;}}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

利用iText包实现Java报表打印摘要:结合报表制作的两种情形介绍了iText的应用方法。

一种是由程序对象动态产生整个报表文件的内容,另一种是在已存在的PDF报表文档中填写数据域以完成报表。

给出了Java实现报表打印的控制方法。

关键词: Java报表;iText包;动态报表;填充型报表;报表打印在信息系统应用中,报表处理一直起着比较重要的作用。

Java报表制作中最常使用的是iText组件,它是一种生成PDF报表的Java组件。

本文讨论两种形式的PDF报表处理,一种是通过程序对象生成整个PDF报表文档,另一种是利用制作好的含报表的PDF文档模板,通过在模板填写数据实现数据报表。

1 通过编程绘制实现报表的生成对于内容动态变化的表格,适合使用程序绘制办法进行生成处理。

这类表格中数据项和数据均是动态存在的。

1.1使用iText编程生成含报表的PDF文档的步骤[1] (1)建立Document对象。

Document是PDF文件所有元素的容器。

Document document = new Document(); (2)建立一个与Document对象关联的书写器(Writer)。

通过书写器(Writer)对象可以将具体文档存盘成需要的格式,PDFWriter可以将文档保存为PDF文件。

PDFWriter.getInstance(document, new FileOutputStream(&quot;my.PDF&quot;)); (3)打开文档。

如:document.open(); (4)向文档中添加内容。

所有向文档添加的内容都是以对象为单位的,iText中用文本块(Chunk)、短语(Phrase)和段落(Paragraph)处理文本。

document.add(new Paragraph(&quot;HelloWorld&quot;));//添加一个段落值得注意的是文本中汉字的显示,默认的iText字体设置不支持中文字体,需要下载远东字体包iTextAsian.jar,否则不能往PDF文档中输出中文字体[2]。

(5)关闭文档。

如:document.close();1.2 表格绘制要在PDF文件中创建表格,iText提供了两个类&mdash;&mdash;Table和PdfPTable。

Table类用来实现简单表格,PdfPTable类则用来实现比较复杂的表格。

本文主要讨论PdfPTable类的应用。

(1)创建PdfPTable对象创建PdfPTable对象只需要指定列数,不用指定行数。

通常生成的表格默认以80%的比例显示在页面上。

例如定义3列的表格,每列的宽度分别为15%、25%和60%,语句如下:float[] widths = {15f, 25f, 60f}; PdfPTable table = newPdfPTable(widths); 用setWidthPercentage(float widthPercentage)方法可设置表格的按百分比的宽度。

而用setTotalWidth则可设置表格按像素计算的宽度。

如果表格的内容超过了300 px,表格的宽度会自动加长。

用setLockedWidth(true)方法可锁定表格宽度。

通过表格对象的系列方法可设置表格的边界以及对齐、填充方式。

(2)添加单元格表格创建完成以后,可通过addCell(Object object)方法插入单元格元素(PdfPCell)。

其中,Object对象可以是PdfPCell、String、Phrase、Image,也可以是PdfPTable对象本身,即在表格中嵌套一个表格。

通过单元格的方法可设定单元格的列跨度、边框粗细、对齐方式、填充间隙等。

(3)合并单元格为了实现某些特殊的表格形式,需要合并单元格。

PdfPCell类提供了setColspan(int colspan)方法用于合并横向单元格,参数colspan为合并的单元格数。

但要合并纵向单元格需要使用嵌套表格的方法。

将某个子表加入单元格,且安排单元格所占列数为子表中列数,则其行跨度也就是子表中的行数。

由于实际编程时,经常出现各类结构的嵌套情形,可以将产生某种结构的表格模块进行封装,编制成方法,通过传递方法参数完成表格特定模块的绘制。

例如,可以将生成一个整齐行列表格的代码编写成方法。

方法返回表格,填充的数据通过二维对象数组传递。

代码如下:public staticPdfPTable creatSubTable(Object x[][]){ PdfPTable t= new PdfPTable(x[0].length);t.getDefaultCell ().setHorizontalAlignment (Element.ALIGN_CENTER); for (intk=0;k&lt;x.length;k++) { for (int j=0;j&lt;x[0].length;j++) t.addCell(new Phrase(x[k][j].toString(),FontChinese)); } return t;}以下代码调用上述方法,绘制图1表格中黑框内部分: PdfPTable t2= new PdfPTable(3);String x1[][]={ {&quot;+601k&quot;,&quot;10&quot;,&quot;合格&quot;},{&quot;-601k&quot;,&quot;11&quot;,&quot;合格&quot;},{&quot;+601k-601k&quot;,&quot;12&quot;,&quot;合格&quot;}}; PdfPCellm=new PdfPCell(creatSubTable(x1));//将创建的子表放入单元格 m.setColspan(3);//单元格占用外层表格的3栏 t2.addCell(m);2 基于PDF报表模板的报表生成有些表格具有固定的格式,实际工作中只是给表格填写数据。

这类表格可转换为PDF文件格式的报表模板,通过特殊工具在文件中定义若干数据域,通过给数据域写入数据实现对报表数据的填充处理。

它具有格式灵活的特点。

基于报表模板的报表处理步骤如下: (1)利用Word制作打印报表; (2)利用Adobe Acrobat 7.0 Professional将Word文档转换为PDF格式; (3)利用Adobe Designer 7.0对PDF进行设计,定义数据域; (4)利用iText组件实现对报表数据字段的写入。

可利用AdobeDesigner 7.0导入某个PDF文件进行设计,在任意位置添加文本域。

每个文本域有一个绑定的名称和值,在Java程序中正是通过文本域的名称访问文本域对象。

图2给出了利用Adobe Acrobat 7.0 Professional打开一个制作好的带数据域定义的PDF文档模板文件的浏览界面,出于清晰考虑,图中特别将数据域采用高亮度显示。

以下给出了打开报表模板实现数据写入的关键代码:importcom.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.AcroFields;import com.itextpdf.text.pdf.PdfReader; importcom.itextpdf.text.pdf.PdfStamper; &hellip;&hellip; PdfReader r=newPdfReader(&quot;d:\\预检模板(DC600V方式).pdf&quot;); // ① PdfStamper s=new PdfStamper(r,new FileOutputStream(&quot;d:\\结果.pdf&quot;)); //② AcroFieldsform=s.getAcroFields(); // ③ Stringx[]=detectlog.getYjdata(date,cheNumber,code);//读取数据库数据form.setField(&quot;日期&quot;, x[1]); // ④ form.setField(&quot;修规&quot;,x[2]); &hellip;&hellip; s.close(); 【说明】①利用PdfReader读取PDF文档;通过实例化PdfReader对象来获取pdf模板,传入的字符串就是pdf文件所放置的路径,可以用绝对路径表示。

②取得对象后,需要用PdfStamper来编辑PdfReader对象,同时获取一个OutputStream输出流作为输出对象。

③利用PdfStamper获取文件中定义的AcroFields对象。

④用AcroFields对象的setField填写各个字段的数据到表格中。

3 Java打印PDF报表文件在Web应用中要在客户端打印PDF文档只需要将文件送客户浏览器显示,利用浏览器客户端的文件打印功能可实现打印。

以下讨论在Java应用程序中如何打印报表文件。

Java实现报表打印首先要获取打印服务对象,然后利用服务对象开始一个作业的打印。

以下给出了新的JDK1.4以上版本中实现打印的具体步骤和关键代码。

// ① 构建打印请求属性集PrintRequestAttributeSet pras = new HashPrintRequest-AttributeSet(); // ② 设置打印格式,因为未确定文件类型,这里选择AUTOSENSE DocFlavor flavor=DocFlavor.INPUT_STREAM.AUTOSENSE;// ③ 查找所有的可用打印服务PrintService printService[] = PrintServiceLookup.lookup-PrintServices(flavor, pras); // ④ 定位默认的打印服务PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService(); // ⑤ 显示打印对话框PrintService service = ServiceUI.printDialog(null, 200,200, printService, defaultService, flavor, pras); if (service != null) { DocPrintJob job = service.createPrintJob(); // ⑥创建打印作业 FileInputStream fis = new FileInputStream(file); // 假设file为具体文件对象 DocAttributeSet das = new HashDocAttributeSet(); Doc doc = new SimpleDoc(fis, flavor, das); // ⑦ 建立打印文件格式job.print(doc, pras); // ⑧ 进行文件的打印 } 本文介绍了利用iText实现PDF报表打印的编程处理方法。

相关文档
最新文档