当前位置:文档之家› Java实现打印功能

Java实现打印功能

Java实现打印功能
Java实现打印功能

Java实现打印功能

用java实现打印,java.awt中提供了一些打印的API,要实现打印,首先要获得打印对象,然后继承Printable实现接口方法print,以便打印机进行打印,最后用用Graphics2D直接输出直接输出。

下面代码实现了简单的打印功能:

import java.awt.BasicStroke;

import java.awt.Color;

import https://www.doczj.com/doc/035702247.html,ponent;

import java.awt.Font;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Image;

import java.awt.Toolkit;

import java.awt.RenderingHints;

import java.awt.font.FontRenderContext;

import java.awt.font.LineBreakMeasurer;

import java.awt.font.TextAttribute;

import java.awt.font.TextLayout;

import java.awt.geom.Point2D;

import java.awt.image.BufferedImage;

import java.awt.print.Book;

import java.awt.print.PageFormat;

import java.awt.print.Paper;

import java.awt.print.Printable;

import java.awt.print.PrinterException;

import java.awt.print.PrinterJob;

import java.text.AttributedString;

import javax.swing.JApplet;

public class PrintTest implements Printable{

/**

* @param Graphic指明打印的图形环境

* @param PageFormat指明打印页格式(页面大小以点为计量单位,1点为1英才的1/72,1英寸为25.4毫米。A4纸大致为595×842点)

* @param pageIndex指明页号

**/

public int print(Graphics gra, PageFormat pf, int pageIndex) thr ows PrinterException {

System.out.println("pageIndex="+pageIndex);

Component c = null;

//print string

String str = "中华民族是勤劳、勇敢和富有智慧的伟大民族。";

//转换成Graphics2D

Graphics2D g2 = (Graphics2D) gra;

//设置打印颜色为黑色

g2.setColor(Color.black);

//打印起点坐标

double x = pf.getImageableX();

double y = pf.getImageableY();

switch(pageIndex){

case 0:

//设置打印字体(字体名称、样式和点大小)(字体名称可以是物理或者逻辑名称)

//Java平台所定义的五种字体系列:Serif、SansSerif、Monospaced、Dialog 和 DialogInput

Font font = new Font("新宋体", Font.PLAIN, 9);

g2.setFont(font);//设置字体

//BasicStroke bs_3=new BasicStroke(0.5f);

float[] dash1 = {2.0f};

//设置打印线的属性。

//1.线宽 2、3、不知道,4、空白的宽度,5、虚线的宽度,6、偏移量

g2.setStroke(new BasicStroke(0.5f, BasicStroke.CAP_B UTT, BasicStroke.JOIN_MITER, 2.0f, dash1, 0.0f));

//g2.setStroke(bs_3);//设置线宽

float heigth = font.getSize2D();//字体高度

System.out.println("x="+x);

// -1- 用Graphics2D直接输出

//首字符的基线(右下部)位于用户空间中的 (x, y) 位置处

//g2.drawLine(10,10,200,300);

Image src = Toolkit.getDefaultToolkit().getImage("D:\\Ec lipseWorkSpace3.1\\Kfc-wuxi\\WebRoot\\image\\KFC.jpg");

g2.drawImage(src,(int)x,(int)y,c);

int img_Height=src.getHeight(c);

int img_width=src.getWidth(c);

//System.out.println("img_Height="+img_Height+"img_width ="+img_width) ;

g2.drawString(str, (float)x, (float)y+1*heigth+img_Heigh t);

g2.drawLine((int)x,(int)(y+1*heigth+img_Height+10),(int) x+200,(int)(y+1*heigth+img_Height+10));

g2.drawImage(src,(int)x,(int)(y+1*heigth+img_Height+11), c);

return PAGE_EXISTS;

default:

return NO_SUCH_PAGE;

}

}

public static void main(String[] args) {

// 通俗理解就是书、文档

Book book = new Book();

// 设置成竖打

PageFormat pf = new PageFormat();

pf.setOrientation(PageFormat.PORTRAIT);

// 通过Paper设置页面的空白边距和可打印区域。必须与实际打印纸张大小相符。

Paper p = new Paper();

p.setSize(590,840);//纸张大小

p.setImageableArea(10,10, 590,840);//A4(595 X 842)设置打印区域,其实0,0应该是72,72,因为A4纸的默认X,Y边距是72

pf.setPaper(p);

// 把 PageFormat 和 Printable 添加到书中,组成一个页面

book.append(new PrintTest(), pf);

//获取打印服务对象

PrinterJob job = PrinterJob.getPrinterJob();

// 设置打印类

job.setPageable(book);

try {

//可以用printDialog显示打印对话框,在用户确认后打印;也可以直接打印

//boolean a=job.printDialog();

//if(a)

//{

job.print();

//}

} catch (PrinterException e) {

e.printStackTrace();

}

}

}

这个例子实现了打印字符串,线(包括虚线)和打印图片。而且通过Paper 的setImageableArea可以设置打印的区域和边距,让开发者随意的设置打印的位置。

下面的打印代码没有设置打印区域,默认为打印纸张的区域和边距,比如我们一般用的A4纸,打印的起点X和Y坐标则是72,72。

无区域设置的代码:

import java.awt.BasicStroke;

import java.awt.Color;

import https://www.doczj.com/doc/035702247.html,ponent;

import java.awt.Font;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Image;

import java.awt.Toolkit;

import java.awt.RenderingHints;

import java.awt.font.FontRenderContext;

import java.awt.font.LineBreakMeasurer;

import java.awt.font.TextAttribute;

import java.awt.font.TextLayout;

import java.awt.geom.Point2D;

import java.awt.image.BufferedImage;

import java.awt.print.Book;

import java.awt.print.PageFormat;

import java.awt.print.Paper;

import java.awt.print.Printable;

import java.awt.print.PrinterException;

import java.awt.print.PrinterJob;

import java.text.AttributedString;

import javax.swing.JApplet;

public class PrintTest1 implements Printable{

/**

* @param Graphic指明打印的图形环境

* @param PageFormat指明打印页格式(页面大小以点为计量单位,1点为1英才的1/72,1英寸为25.4毫米。A4纸大致为595×842点)

* @param pageIndex指明页号

**/

public int print(Graphics gra, PageFormat pf, int pageIndex) thr ows PrinterException {

System.out.println("pageIndex="+pageIndex);

Component c = null;

//print string

String str = "中华民族是勤劳、勇敢和富有智慧的伟大民族。";

//转换成Graphics2D

Graphics2D g2 = (Graphics2D) gra;

//设置打印颜色为黑色

g2.setColor(Color.black);

/*Paper paper = pf.getPaper();//得到页面格式的纸张

paper.setSize(500,500);//纸张大小

paper.setImageableArea(0,0,500,500); //设置打印区域的大小

System.out.println(paper.getWidth());

System.out.println(paper.getHeight());

pf.setPaper(paper);//将该纸张作为格式 */

//打印起点坐标

double x = pf.getImageableX();

double y = pf.getImageableY();

switch(pageIndex){

case 0:

//设置打印字体(字体名称、样式和点大小)(字体名称可以是物理或者逻辑名称)

//Java平台所定义的五种字体系列:Serif、SansSerif、Monospaced、Dialog 和 DialogInput

Font font = new Font("新宋体", Font.PLAIN, 9);

g2.setFont(font);//设置字体

//BasicStroke bs_3=new BasicStroke(0.5f);

float[] dash1 = {4.0f};

g2.setStroke(new BasicStroke(0.5f, BasicStroke.CAP_B UTT, BasicStroke.JOIN_MITER, 4.0f, dash1, 0.0f));

float heigth = font.getSize2D();//字体高度

System.out.println("x="+x);

//使用抗锯齿模式完成文本呈现

/*g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASI NG,

RenderingHints.VALUE_TEXT_ANTIALIAS_ON);*/

// -1- 用Graphics2D直接输出

//首字符的基线(右下部)位于用户空间中的 (x, y) 位置处

//g2.drawLine(10,10,200,10);

Image src = Toolkit.getDefaultToolkit().getImage("d://lo go.gif");

g2.drawImage(src,(int)x,(int)y,c);

int img_Height=src.getHeight(c);

int img_width=src.getWidth(c);

//System.out.println("img_Height="+img_Height+"img_width ="+img_width) ;

g2.drawString(str, (float)x, (float)y+1*heigth+img_Heigh t);

g2.drawLine((int)x,(int)(y+1*heigth+img_Height+10),(int) x+200,(int)(y+1*heigth+img_Height+10));

g2.drawImage(src,(int)x,(int)(y+1*heigth+img_Height+11), c);

// -2- 直接构造TextLayout打印

/*FontRenderContext frc = g2.getFontRenderContext();

TextLayout layout = new TextLayout(str, font, frc);

layout.draw(g2, (float)x, (float)y+2*heigth);*/

// -3- 用LineBreakMeasurer进行打印

/*AttributedString text = new AttributedString(str);

text.addAttribute(TextAttribute.FONT, font);

LineBreakMeasurer lineBreaker = new LineBreakMeasurer(te xt.getIterator(), frc);

//每行字符显示长度(点)

double width = pf.getImageableWidth();

//首字符的基线位于用户空间中的 (x, y) 位置处

Point2D.Double pen = new Point2D.Double (100, y+3*heigth );

while ( (layout = lineBreaker.nextLayout( (float) width) ) != null){

layout.draw(g2, (float)x, (float) pen.y);

pen.y += layout.getAscent();

}*/

return PAGE_EXISTS;

default:

return NO_SUCH_PAGE;

}

}

public static void main(String[] args) {

//获取打印服务对象

PrinterJob job = PrinterJob.getPrinterJob();

PageFormat pageFormat = job.defaultPage();//得到默认页格式

job.setPrintable(new PrintTest1());//设置打印类

try {

//可以用printDialog显示打印对话框,在用户确认后打印;也可以直接打印

//boolean a=job.printDialog();

//if(a)

//{

job.print();

//}

} catch (PrinterException e) {

e.printStackTrace();

}

}

}

Java实现打印功能

Java实现打印功能 用java实现打印,java.awt中提供了一些打印的API,要实现打印,首先要获得打印对象,然后继承Printable实现接口方法print,以便打印机进行打印,最后用用Graphics2D直接输出直接输出。 下面代码实现了简单的打印功能: import java.awt.BasicStroke; import java.awt.Color; import https://www.doczj.com/doc/035702247.html,ponent; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; import java.awt.RenderingHints; import java.awt.font.FontRenderContext; import java.awt.font.LineBreakMeasurer; import java.awt.font.TextAttribute; import java.awt.font.TextLayout; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; import java.awt.print.Book; import java.awt.print.PageFormat; import java.awt.print.Paper; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.text.AttributedString; import javax.swing.JApplet; public class PrintTest implements Printable{ /** * @param Graphic指明打印的图形环境 * @param PageFormat指明打印页格式(页面大小以点为计量单位,1点为1英才的1/72,1英寸为25.4毫米。A4纸大致为595×842点) * @param pageIndex指明页号 **/

JavaPrintService_Java打印API_用户手册_中文版

目录 第一章介绍 Java平台打印的历史 JDK 1.3 JDK 1.2 JDK 1.1 Java Print Service API能做什么 Java Print Service 构架 javax.print包 发现打印服务 指定打印数据格式 创建打印工作 javax.print.event包 应用程序如何使用JPS 一个基本的例子 第二章属性 属性的类别和值 属性角色 属性集 如何指定属性 标准属性 OrientationRequested Copies Media MediaSize MediaPrintableArea Destination SheetCollate Sides Fidelity 使用JPS属性 第三章指定文档类型 用户格式打印数据 预定义数据格式的MIME类型 文本数据 页面描述语言文档 图像数据 自适应打印数据 表示类 字符编码的重要性 服务格式打印数据 怎样使用DocFlavor 第四章打印及流化文档

比较StreamPrintService与PrintService 定位服务 发现打印服务 发现流打印服务 获得一个打印工作 创建DOC 注册事件 打印服务事件 打印工作事件 PrintJobAttributeListener PrintJobListener 提交打印工作 向打印机提交打印工作 向流提交打印工作 打印服务提供商 第五章打印及流化2D图像 使用打印工作打印或流化图像 打印2D图像 流化2D图像 使用服务格式数据 打印服务格式数据 流化服务格式打印数据 示例:PrintPS.java 示例:PrintGIFtoStream.java 示例:Print2DPrinterJob.java 示例:Print2DGraphics.java 示例:Print2DtoStream.java 示例:PrintGIF.java Java Print Service 词汇表

java大作业编一个程序打印出公司月各员工工资

姓名:王镱澍 Java大作业 一、题目 白浪公司的雇员根据参数月份来确定工资,如果该月员工过生日,则公司会额外奖励100元。 雇员分为以下若干类: SalariedEmployee:拿固定工资的员工。 HourlyEmployee:按小时拿工资的员工。 SalesEmployee:销售人员,工资由月销售额和提成率决定。 BasePlusSalesEmployee:有固定底薪的销售人员,工资由底薪加上销售提成。 公司会给SalaryEmployee每月另外发放2000元加班费,给 BasePlusSalesEmployee发放1000元加班费。编一个java程序创建上述若干类,并实现确定月份以及该月不同员工的工作情况后打印出该公司该月各员工工资,公司总的工资支出情况。 二、程序功能说明 编一个java程序创建上述若干类,并实现确定该月不同员工的工作情况以及输入月份后打印出该公司该月各员工工资,公司总的工资支出情况。 三、类、属性、方法说明 程序中已给出详细解释在此只作简要说明: Employee:这是所有员工总的父类。 属性:员工的姓名和生日月份。 方法:getSalary(int month) 根据参数月份来确定工资,如果该月员工过生日,则公司会额外奖励100元。 SalariedEmployee:Employee的子类,拿固定工资的员工。 属性:月薪。 方法:每月工作超出160小时的部分按照倍工资发放。 HourlyEmployee:Employee的子类,按小时拿工资的员工。 属性:每小时的工资、每月工作的小时数。 SalesEmployee:Employee的子类,销售人员。 属性:月销售额、提成率。 方法:工资由月销售额和提成率决定。 BasePlusSalesEmployee:SalesEmployee的子类,有固定底薪的销售人员。 属性:底薪。 方法:工资由底薪加上销售提成部分。 四、程序代码 import .*; class MyException extends Exception {

打印java方法参数

打印Java方法参数 首先描述一下具体的需求就是,能不能不需要手动添加代码就能打印Java方法所有的参数,这有些时候在我们调试代码的时候有很重要的帮助。 按照这个需求,我们可以想一下我们大体需要一下什么信息,方法的名称,方法参数类型,方法参数的名字,方法参数的值。 如何实现不写代码就能够实现动态的打印这些信息呢,了解Java的这时候就都会想到动态代理。有了动态代理我们就可以不用写代码了,但是为了区分哪些方法需要打印,哪些方法不需要打印,我们这里还需要注解来辅助区分需要打印的方法。 如何获取需要打印的信息呢,这里我相信大家都会想到反射,但是反射这里有一个参数是拿不到的,哪个参数呢,方法参数的名字是拿不到的。这里我们采用的是asm的方式来获取方法参数的名字。 到这里功能已经描述清楚,需要用到的技术也描述清楚,接下来就是具体怎么实现了。 首先,我们设计了一个注解类如下: import https://www.doczj.com/doc/035702247.html,ng.annotation.ElementType; import https://www.doczj.com/doc/035702247.html,ng.annotation.Retention; import https://www.doczj.com/doc/035702247.html,ng.annotation.RetentionPolicy; import https://www.doczj.com/doc/035702247.html,ng.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public@interface MethodLog { } 接下来就是我们设计的最后要打印的数据的一个简单的封装类,如下: public class MethodInfo { private int index;//参数的索引 private Object parameterType;//参数的类型 private String parameterName;//参数的名称 private Object parameterValue;//参数的值 public MethodInfo(){} public MethodInfo(int index, Object parameterType, String parameterName, Object parameterValue) { super(); this.index = index; this.parameterType = parameterType; this.parameterName = parameterName; this.parameterValue = parameterValue; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; }

Java打印程序设计

Java打印程序设计 1 前言 在我们的实际工作中,经常需要实现打印功能。但由于历史原因,Java提供的打印功能一直都比较弱。实际上最初的jdk根本不支持打印,直到jdk1.1才引入了很轻量的打印支持。所以,在以前用Java/Applet/JSP/Servlet设计的程序中,较复杂的打印都是通过调用ActiveX/OCX控件或者VB/VC程序来实现的,非常麻烦。实际上,SUN公司也一直致力于Java打印功能的完善,而Java2平台则终于有了一个健壮的打印模式的开端,该打印模式与Java2D图形包充分结合成一体。更令人鼓舞的是,新发布的jdk1.4则提供了一套完整的"Java 打印服务 API" (Java Print Service API),它对已有的打印功能是积极的补充。利用它,我们可以实现大部分实际应用需求,包括打印文字、图形、文件及打印预览等等。本文将通过一个具体的程序实例来说明如何设计Java打印程序以实现这些功能,并对不同版本的实现方法进行分析比较,希望大家能从中获取一些有益的提示。 2 Java中的打印 2.1 Java的打印API Java的打印API主要存在于java.awt.print包中。而jdk1.4新增的类则主要存在于javax.print 包及其相应的子包javax.print.event和javax.print.attribute中。其中javax.print包中主要包含打印服务的相关类,而javax.print.event则包含打印事件的相关定义,javax.print.attribute则包括打印服务的可用属性列表等。 2.2 如何实现打印 要产生一个打印,至少需要考虑两条: 需要一个打印服务对象。这可通过三种方式实现:在jdk1.4之前的版本,必须要实现java.awt.print.Printable接口或通过Toolkit.getDefaultToolkit().getPrintJob来获取打印服务对象;在jdk1.4中则可以通过javax.print.PrintSerivceLookup来查找定位一个打印服务对象。 需要开始一个打印工作。这也有几种实现方法:在jdk1.4之前可以通过java.awt.print.PrintJob(jdk1.1提供的,现在已经很少用了)调用print或printAll方法开始打印工作;也可以通过java.awt.print.PrinterJob的printDialog显示打印对话框,然后通过print方法开始打印;在jdk1.4中则可以通过javax.print.ServiceUI的printDialog显示打印对话框,然后调用print方法开始一个打印工作。 2.3 打印机对话框 2.3.1 Printable的打印对话框 开始打印工作之前,可以通过PrinterJob.printDialog来显示一个打印对话框。它给用户一个机会以选择应该打印的页码范围,并可供用户改变打印设置。它是一个本地对话框。

java各种打印输出

1.import java.util.Scanner; 2. 3.public class Test03 4.{ 5.public static void main(String[] args) 6. { 7. Scanner input = new Scanner(System.in); 8. System.out.println("请输入行数"); 9.int rows=input.nextInt(); 10.for (int i = 0; i < rows; i++) 11. { 12.for (int j = 0; j <= i; j++) 13. { 14. System.out.print("* "); 15. } 16. System.out.println(); 17. } 18. System.out.println("倒过来的三角"); 19.for (int i = rows-1; i >=0; i--) 20. { 21.for (int j = 0; j <= i; j++) 22. { 23. System.out.print("* "); 24. } 25. System.out.println(); 26. } 27. 28. } 29.} 30.请输入行数 31.5 32.* 33.* * 34.* * * 35.* * * * 36.* * * * * 37.倒过来的三角 38.* * * * * 39.* * * * 40.* * * 41.* * 42.* 43.

062106" name="code"class="java">package ch09; 45. 46.import java.util.Scanner; 47. 48. 49. 50.public class Test04 51.{ 52.public static void main(String[] args) 53. { 54. Scanner input = new Scanner(System.in); 55. System.out.println("请输入行数"); 56.int row=input.nextInt(); 57. 58.for (int i = 1; i <=row; i++) 59. { 60.for (int j = 0; j < row-i; j++) 61. { 62. System.out.print(" "); 63. } 64.for (int j = 0; j < 2*i-1; j++) 65. { 66. System.out.print("*"); 67. } 68. System.out.println(); 69. } 70. 71. 72. } 73.} 74.请输入行数 75.10 76. * 77. *** 78. ***** 79. ******* 80. ********* 81. *********** 82. ************* 83. *************** 84. ***************** 85.******************* 86.

Java打印最

Java打印最大的改变来自于J2SE的发布带来的Java打印服务API。这个第三代Java打印支持接口突破了先前提到的使用javax.print包的PrintService和DocPrintJob接口的局限性。因为新的API就是以前两种旧的打印机制定义的功能函数的一个父集,它是目前我们常用的方法并且是这篇文章的焦点。 更深入来说,以下的步骤包含了怎么使用这个新的Java打印服务API: 1.定义打印机,限制那些返回到提供你要实现功能的函数的列表。打印服务实现了PrintService接口. 2.通过调用接口中定义的createPrintJob()方法创建一个打印事件,作为DocPrintJob 的一个实例。 3.创建一个实现Doc接口的类来描述你想要打印的数据, 你也可以创建一个PrintRequestAttributeSet的实例来定义你想要的打印选项。 4.通过DocPrintJob接口定义的printv()方法来初始化打印,指定你先前创建的Doc,指定PrintRequestAttributeSet或者设为空值。 现在你可以检查每一步并且试着完成它们。 注意 在这篇文章里,我将交替使用打印机和打印服务,因为在大部分情况下,打印服务不亚于一台真实的打印机。一般的打印服务反映了理论上可以发送到不仅仅是打印机的的输出。举例来说,打印服务也许根本不能打印东西但是可以往磁盘上的文件写数据。换句话说,所有的打印机可以看成是特殊的打印服务,但是并不是所有打印服务和打印机有联系。就像你一般把你的文本送到打印机那里一样,我有时候使用更为简便的打印机这个名词来代替技术上更精确的打印服务。 定义打印服务 你可以使用在PrintServiceLookup类中定义的三种静态方法中的一种来定义。最简单的一种就是lookupDefaultPrintService(),正如它的名字一样,它返回一个你默认的打印机: PrintService service = PrintServiceLookup.lookupDefaultPrintService(); 虽然用这个办法很简单也很方便,用它来选择你的打印机意味着用户的打印机一直都支持你的程序所要精确传输的数据输出。实际上,你真正想要的是那种可以处理你想要的数据的类型并且可以支持你要的特征例如颜色或者两边打印。为了从列表中中返回你所要求的特殊功能支持的打印机,你可以使用剩下两个方法中的lookupPrintServices() 或者lookupMultiDocPrintServices()。

利用iText包实现Java报表打印

利用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("my.PDF")); (3)打开文档。如:document.open(); (4) 向文档中添加内容。所有向文档添加的内容都是以对象为单位的,iText中用文本块(Chunk)、 短语(Phrase)和段落(Paragraph)处理文本。 document.add(new Paragraph("Hello World"));//添加一个段落值得注意的是文本中汉字的显示,默认的iText字体设 置不支持中文字体,需要下载远东字体包iTextAsian.jar,否则不能往PDF文档中输出中文 字体[2]。 (5)关闭文档。如:document.close();1.2 表格绘制要在PDF文件中创建 表格,iText提供了两个类——Table和PdfPTable。Table类用来实现简单表格, PdfPTable类则用来实现比较复杂的表格。本文主要讨论PdfPTable类的应用。 (1)创建 PdfPTable对象创建PdfPTable对象只需要指定列数,不用指定行数。通常生成的表格 默认以80%的比例显示在页面上。例如定义3列的表格,每列的宽度分别为15%、25%和60%, 语句如下:float[] widths = {15f, 25f, 60f}; PdfPTable table = new PdfPTable(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 static PdfPTable creatSubTable(Object x[][]){ PdfPTable t= new PdfPTable(x[0].length); t.getDefaultCell ().setHorizontalAlignment (Element.ALIGN_CENTER); for (int k=0;k<x.length;k++) { for (int j=0;j<x[0].length;j++) t.addCell(new Phrase(x[k][j].toString(),FontChinese)); } return t;}

Java打印4种直角三角形

使用Java 打印4种直角三角形 public class Text1 { public static void main(String[] args) { for (int i = 1;i <= 5;i++) { for (int j = 0; j < i; j++) { System.out .print("*"); } System.out .println(); } System.out .print("\n"); for (int a = 0; a < 5; a++) { for (int b = a; b < 5; b++) { System.out .print("*"); } System.out .println(); } System.out .println(); for (int i = 0; i < 5; i++) { for (int j =0; j < 5 - i; j++) { System.out .print("*"); } System.out .println(); } System.out .println(); for (int i = 0; i < 5; i++) { for (int j = 0; j < i; j++) { System.out .print(" "); } for (int k = 1; k <= 5 - i; k++) { System.out .print("*"); } System.out .println(); * ** *** **** ***** ***** **** *** ** * ***** **** *** ** * ***** **** *** ** *

Java_实现iReport打印

iReport报表打印功能代码编写环境 系统:windows xp 开发工具:Myeclipes6.0 JDK版本:Java6(jdk6.0,jre6.0) 服务器:Tomcat5.5 Ireport版本: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, 具体代码如: 打印 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。 2.document.forms[0].action="${ctx}/ExamPermitPrint.html"; document.forms[0].submit(); 此代码是当你打印成功执行完之后要执行的代码,例如重新查询记录列表 四、打印提示窗口文件examprint_cert.jsp编写 examprint_cert.jsp <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

Java 打印Word文档

Java 打印Word文档 通过使用Sprie.Doc for Java提供的PrinterSettings类可执行文档打印,具体可参见这篇文章中关于使用PrinterSettings来打印的方法。本文中将介绍的是使用Spire.Doc 提供的另一个类PrinterJob来打印Word文档,需要使用最新版的Jar包。 Jar包导入方法: 方法1:使用jar包时,可手动下载导入; 方法2:在Maven程序中通过配置pom.xml文件导入jar,如下,需要指定Maven仓库路径以及Spire.Doc的依赖 com.e-iceblue https://www.doczj.com/doc/035702247.html,/repository/maven-public/ e-iceblue spire.doc 3.9.4 如下jar导入效果: PrinterJob打印示例

import com.spire.doc.*; import java.awt.print.PageFormat; import java.awt.print.Paper; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; public class Print { public static void main(String[] args) { //加载Word文档 Document doc = new Document(); doc.loadFromFile("test.docx"); //创建PrinterJob对象 PrinterJob loPrinterJob = PrinterJob.getPrinterJob(); PageFormat loPageFormat = loPrinterJob.defaultPage(); Paper loPaper = loPageFormat.getPaper(); loPaper.setSize(600, 500);//设置打印纸张大小 loPageFormat.setPaper(loPaper); loPaper.setImageableArea(0, 0, loPageFormat.getWidth(), loPageFormat.getHeight());//删除默认页边距 loPrinterJob.setCopies(1);//设置打印份数 loPrinterJob.setPrintable(doc, loPageFormat); //设置打印对话框 if (loPrinterJob.printDialog()) { try { loPrinterJob.print(); //执行打印 } catch (PrinterException e) { e.printStackTrace(); } } } }

JAVA打印(完整版)

1.选择题:(每个2分,共10个,20分) 1.Which of the following is a constant, according to Java naming conventions? A. MAX_VALUE B. Test C. read D. ReadInt 2.You should override the __________ method to draw things on a Swing component. A.repaint() B.update() C.paintComponent() D.init() 3.Which class can the user defined exception class inherit from? A.Error B.AWTError C.VirtualMachineError D.Exception and its subclass 4.Which is wrong about the Frame class? A.Frame is the direct subclass of the Window class B.the object of Frame displays a window C.Frame is visible by default D.the default layout of Frame is BorderLayout 1. A runtime error implies the following: a. The program cannot be compiled. b. The program runs, but is terminated unexpectedly. c. The program runs, but produces incorrect results. d. None of the above 2.When you run your program Test, you receive NoClassDefFoundError: Test. What is the reason? a. JVM cannot find Test.class. b. JVM cannot find Test.java. c. Test is not a public class. d. Test does not have a main method. e. Test does not have a constructor. 3.When you run your program Test, you receive NoSuchMethodError: main. What is the reason? a. JVM cannot find Test.class. b. JVM cannot find Test.java. c. Test is not a public class. d. Test does not have a main method, or the signature of the main method is incorrect. e. Test does not have a constructor. 4.What is the range of an int variable? a. 0 to 216. b. -216 to 216. c. -215to 215-1. d. -216 to 216-1. e. None of the above. 5.Which of the following statement is incorrect? a. byte b = 40; b. short s = 200; c. int i = 200; d. int j = 200L; 7.Assume x=1 and y=2, what is the result of ev aluating "x + y = " + x + y? a. x + y = 3 b. x + y = 12 c. Illegal operations d. None of the above 8.Assume x=1 and y=2, what is the result of evaluating ++x + y? a. 1 b. 2 c. 3 d. 4 9.Assume x=1 and y=2, what is the result of ev aluating x++ + y? a. 1 b. 2 c. 3 d. 4 e. None of the above 10.Assume x=1 and y=2, what is x, after evaluating (x > 0) || (x-- > 0)? a. 1 b. 2 c. 3 d. 4 e. None of the above 11.Assume x=1 and y=2, what is x, after evaluating (x > 0) | (x-- > 0)? a. 0 b. 1 c. 2 d. 3 e. None of the above 12.Suppose x = 1, y = -1, and z = 1. What is the printout of the following statement? if (x > 0) if (y > 0) System.out.println("A"); else if (z > 0) System.out.println("B"); else System.out.println("C"); a. A b. B c. C d. None of the abov e. 13.Analyze the following program fragment: int x; double d = 1.5; switch (d) { case 1.0: x = 1; case 1.5: x = 2; } a. The required break statement is missing in the switch statement. b. The required default case is missing in the switch statement. c. The switch control variable cannot be double. d. None of the abov e. 14.Which of the following statement is true? a. You can define a method inside a method. b. A local variable in a method always has a default value if you don’t explicitly assign a value to it. c. A method can be declared with no parameters. d. None of the above is tru e. 15.What is item after the following loop terminates? int sum = 0; int item = 0; do { item += 1; sum += item; if (sum > 4) break; } while (item < 5); a. 2 b. 3 c. 4 d. 5 16.What is item after the following loop terminates? int sum = 0; int item = 0; while (item < 5) { item++; sum += item; if (sum >= 4) continue; } a. 5 b. 6 c. 7 d. 8 17.Analyze the following fragment: double sum = 0; double d = 0; while (d != 10.0) { d += 0.1; sum += sum + d; } a. The program does not compile because sum and d are declared double, but assigned with integer value 0. b. The program never stops because d is always 0.1 inside the loop. c. The program may not stop because of the phenomenon referred to as numerical inaccuracy for operating with floating-point numbers. d. None of the abov e. 18. A call for a method with a void return type is alw ays a statement itself, but a call for the method with a non-void return type can be treated as either a statement or an expression. a. True. b. False. 19.Which of the following is true. a. x.length does not exist if x is null. b. The array index is not limited to int type. c. An array variable can be declared and redeclared in the same block. d. Binary search can be applied on an unsorted list. 20.Which of the following is false. a. You can use the operator == to check whether two variables refer to the same array. b.The copyarray method does not allocate memory space for the target array. The target array must already be created with memory space allocated. c.The array index of the first element in an array is 0. d.The element in the array must be of primitive data typ e. 21. Analyze the following code: public class Test { public static void main(String[] args) { int[] x = {1, 2, 3, 4}; x = new int[2]; int[] y = x; for (int i = 0; i < y.length; i++) System.out.print(y[i] + " "); }} a. The program displays 1 2 3 4. b. The program displays 0 0. c. The program displays 0 0 3 4. d. The program displays 0 0 0 0. 1. describes the state of an object. a. attributes b. methods c. constructors d. no of the above 2. An attribute that is shared by all objects of the class is coded using ________. a. an instance variable b. a static variable c. an instance method d. a static method 3. If a class named Student has no constructors defined explicitly, the following constructor is implicitly provided. a. public Student() b. protected Student() c. private Student() d. Student() 4. If a class named Student has a constructor Student(String name) defined explicitly, the following constructor is implicitly provided. a. public Student() b. protected Student() c. private Student() d. Student() e. None 5. Suppose the xMethod() is invoked in the following constructor, xMethod() is ________ public MyClass() { xMethod(); } a. a static method b. an instance method c. None of the above 6. Suppose the xMethod() is invoked from a main method as follows, xMethod() is __ public static void main(String[] args) { xMethod(); } a. a static method b. an instance method c. None of the above 7. What would be the result of attempting to compile and run the following code? public class Test { static int x; public static void main(String[] args){ System.out.println("Value is " + x); } } a. The output "Value is 0" is printed. b. An "illegal array declaration syntax" compiler error occurs. c. A "possible reference before assignment" compiler error occurs. d. A runtime error occurs, because x is not initialized. 8. Analyze the following code: public class Test { private int t; public static void main(String[] args) { Test test = new Test(); System.out.println(test.t); } } a. The variable t is not initialized and therefore causes errors. b. The variable t is private and therefore cannot be accessed in the main method. c. Since t is an instance variable, it cannot appear in the static main metho d. d. The program compiles and runs fin e. 9. Suppose s is a string with the value "java". What will be assigned to x if you execute the following code? char x = s.charAt(4); a. 'a' b. 'v' c. Nothing will be assigned to x, because the execution causes the runtime error StringIndex OutofBoundsException. d. None of the abov e. 10.What is the printout for the following code? class Test { public static void main(String[] args) {

相关主题
文本预览
相关文档 最新文档