导航:首页 > 程序命令 > java命令生成pdf文档

java命令生成pdf文档

发布时间:2024-07-03 11:09:45

‘壹’ 如何运用java组件itext生成pdf

首先从iText的官网下载这个开源的小组件。
iText官方网站
Java版iText组件
Java版工具包
C#版iText组件
C#版工具包
这里笔者使用的是Java版itext-5.2.1。
将itext-5.2.1.zip压缩解压缩后得到7个文件:itextpdf-5.2.1.jar(核心组件)、itextpdf-5.2.1-javadoc.jar(API文档)、itextpdf-5.2.1-sources.jar(源代码)、itext-xtra-5.2.1.jar、itext-xtra-5.2.1-javadoc.jar、itext-xtra-5.2.1-sources.jar
使用5步即可生成一个简单的PDF文档。
复制代码
1 // 1.创建 Document 对象
2 Document _document = new Document();
3 // 2.创建书写器,通过书写器将文档写入磁盘
4 PdfWriter _pdfWriter = PdfWriter.getInstance(_document, new FileOutputStream("生成文件的路径"));
5 // 3.打开文档
6 _document.open();
7 // 4.向文档中添加内容
8 _document.add(new Paragraph("Hi"));
9 // 5.关闭文档
10 _document.close();
复制代码
OK,搞定,不出问题的话就会在你指定的路径中生成一个PDF文档,内容是纯文本的“Hi”。
可是这样并不能完全满足我们的需求,因为通常我们要生成的PDF文件不一定是纯文本格式的,比如我现在要实现打印销售单的功能,那么最起码需要绘制表格才行,怎么办呢?且跟笔者继续向下研究。
在iText中,有专门的表格类,即PdfPTable类。笔者做了一个简单的表格示例,请先看代码:
复制代码
1 OutTradeList _otl = this.getOtlBiz().findOutTradeListById(this.getOtlid());
2 String _fileName = _otl.getOtlId() + ".pdf";
3
4 // iText 处理中文
5 BaseFont _baseFont = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", true);
6 // 1.创建 Document 对象
7 Document _document = new Document(PageSize.A4);
8
9 HttpServletResponse response = ServletActionContext.getResponse();
10 response.setContentType("application/pdf; charset=ISO-8859-1");
11 response.setHeader("Content-Disposition", "inline; filename=" + new String(_fileName.getBytes(), "iso8859-1"));
12
13 // 2.创建书写器,通过书写器将文档写入磁盘
14 PdfWriter _pdfWriter = null;
15 try {
16 _pdfWriter = PdfWriter.getInstance(_document, response.getOutputStream());
17 } catch (Exception e) {
18 this.setMessage("单据生成失败,请检查服务器目录权限配置是否正确");
19 e.printStackTrace();
20 System.out.println("2.挂了");
21 // return INPUT;
22 return null;
23 }
24 if(_pdfWriter == null) {
25 this.setMessage("单据生成失败,请检查服务器目录权限配置是否正确");
26 System.out.println("3.挂了");
27 // return INPUT;
28 return null;
29 }
30
31 // 3.打开文档
32 _document.open();
33
34 // 4.创建需要填入文档的元素
35 PdfPTable _table = new PdfPTable(4);
36 PdfPCell _cell = null;
37
38 _table.addCell(new Paragraph("单据号", new Font(_baseFont)));
39 _cell = new PdfPCell(new Paragraph(_otl.getOtlId()));
40 _cell.setColspan(3);
41 _table.addCell(_cell);
42
43 _table.addCell(new Paragraph("客户名称", new Font(_baseFont)));
44 _cell = new PdfPCell(new Paragraph(_otl.getClients().getName(), new Font(_baseFont)));
45 _cell.setColspan(3);
46 _table.addCell(_cell);
47
48 _table.addCell(new Paragraph("销售日期", new Font(_baseFont)));
49 _cell = new PdfPCell(new Paragraph(_otl.getOutDate().toString()));
50 _cell.setColspan(3);
51 _table.addCell(_cell);
52
53 _cell = new PdfPCell();
54 _cell.setColspan(4);
55 PdfPTable _tabGoods = new PdfPTable(7);
56 // 添加标题行
57 _tabGoods.setHeaderRows(1);
58 _tabGoods.addCell(new Paragraph("序号", new Font(_baseFont)));
59 _tabGoods.addCell(new Paragraph("商品名称", new Font(_baseFont)));
60 _tabGoods.addCell(new Paragraph("自定义码", new Font(_baseFont)));
61 _tabGoods.addCell(new Paragraph("规格", new Font(_baseFont)));
62 _tabGoods.addCell(new Paragraph("数量", new Font(_baseFont)));
63 _tabGoods.addCell(new Paragraph("单价", new Font(_baseFont)));
64 _tabGoods.addCell(new Paragraph("小计", new Font(_baseFont)));
65 Object[] _outTrades = _otl.getOutTrades().toArray();
66 // 将商品销售详细信息加入表格
67 for(int i = 0; i < _outTrades.length;) {
68 if((_outTrades[i] != null) && (_outTrades[i] instanceof OutTrade)) {
69 OutTrade _ot = (OutTrade) _outTrades[i];
70 Goods _goods = _ot.getGoods();
71 _tabGoods.addCell(String.valueOf((++i)));
72 _tabGoods.addCell(new Paragraph(_goods.getName(), new Font(_baseFont)));
73 _tabGoods.addCell(_goods.getUserCode());
74 _tabGoods.addCell(_goods.getEtalon());
75 _tabGoods.addCell(String.valueOf(_ot.getNum()));
76 _tabGoods.addCell(String.valueOf(_ot.getPrice()));
77 _tabGoods.addCell(String.valueOf((_ot.getNum() * _ot.getPrice())));
78 }
79 }
80 _cell.addElement(_tabGoods);
81 _table.addCell(_cell);
82
83 _table.addCell(new Paragraph("总计", new Font(_baseFont)));
84 _cell = new PdfPCell(new Paragraph(_otl.getAllPrice().toString()));
85 _cell.setColspan(3);
86 _table.addCell(_cell);
87
88 _table.addCell(new Paragraph("操作员", new Font(_baseFont)));
89 _cell = new PdfPCell(new Paragraph(_otl.getProcure()));
90 _cell.setColspan(3);
91 _table.addCell(_cell);
92
93 // 5.向文档中添加内容,将表格加入文档中
94 _document.add(_table);
95
96 // 6.关闭文档
97 _document.close();
98 System.out.println(_fileName);
99 this.setPdfFilePath(_fileName);
100 System.out.println("3.搞定");
101 // return SUCCESS;
102 return null;
复制代码
以上代码是写在 Struts2 的 Action 中的,当用户发送了请求之后直接将生成的PDF文件用输出流写入到客户端,浏览器收到服务器的响应之后就会询问用户打开方式。
当然,我们也可以将文件写入磁盘等等。

‘贰’ 怎么用java代码生成pdf文档

package com.qhdstar.java.pdf;
import java.awt.Color;
import java.io.FileOutputStream;

import com.lowagie.text.Chapter;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Section;
import com.lowagie.text.pdf.PdfWriter;

/**
* 描述:TODO 【JAVA生成PDF】
* <p>
*
* @title GeneratePDF
* @author SYJ
* @email [email protected]
* @date 2013-4-6
* @version V1.0
*/
public class GeneratePDF {

public static void main(String[] args) {

//调用第一个方法,向C盘生成一个名字为ITextTest.pdf 的文件
try {
writeSimplePdf();
}
catch (Exception e) { e.printStackTrace(); }

//调用第二个方法,向C盘名字为ITextTest.pdf的文件,添加章节。
try {
writeCharpter();
}
catch (Exception e) { e.printStackTrace(); }

}

public static void writeSimplePdf() throws Exception {

// 1.新建document对象
// 第一个参数是页面大小。接下来的参数分别是左、右、上和下页边距。
Document document = new Document(PageSize.A4, 50, 50, 50, 50);

// 2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
// 创建 PdfWriter 对象 第一个参数是对文档对象的引用,第二个参数是文件的实际名称,在该名称中还会给出其输出路径。
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\ITextTest.pdf"));

// 3.打开文档
document.open();

// 4.向文档中添加内容
// 通过 com.lowagie.text.Paragraph 来添加文本。可以用文本及其默认的字体、颜色、大小等等设置来创建一个默认段落
document.add(new Paragraph("First page of the document."));
document.add(new
Paragraph("Some more text on the first page with different color and
font type.", FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new
Color(255, 150, 200))));

// 5.关闭文档
document.close();
}

/**
* 添加含有章节的pdf文件
*
* @throws Exception
*/
public static void writeCharpter() throws Exception {

// 新建document对象 第一个参数是页面大小。接下来的参数分别是左、右、上和下页边距。
Document document = new Document(PageSize.A4, 20, 20, 20, 20);

// 建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("c:\\ITextTest.pdf"));

// 打开文件
document.open();

// 标题
document.addTitle("Hello mingri example");

// 作者
document.addAuthor("wolf");

// 主题
document.addSubject("This example explains how to add metadata.");
document.addKeywords("iText, Hello mingri");
document.addCreator("My program using iText");

// document.newPage();
// 向文档中添加内容
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
document.add(new Paragraph("First page of the document."));
document.add(new Paragraph("First page of the document."));
document.add(new Paragraph("First page of the document."));
document.add(new Paragraph("First page of the document."));
document.add(new
Paragraph("Some more text on the first page with different color and
font type.", FontFactory.getFont(FontFactory.defaultEncoding, 10,
Font.BOLD, new Color(0, 0, 0))));
Paragraph title1 = new
Paragraph("Chapter 1", FontFactory.getFont(FontFactory.HELVETICA, 18,
Font.BOLDITALIC, new Color(0, 0, 255)));

// 新建章节
Chapter chapter1 = new Chapter(title1, 1);
chapter1.setNumberDepth(0);
Paragraph
title11 = new Paragraph("This is Section 1 in Chapter 1",
FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD, new Color(255,
0, 0)));
Section section1 = chapter1.addSection(title11);
Paragraph someSectionText = new Paragraph("This text comes as part of section 1 of chapter 1.");
section1.add(someSectionText);
someSectionText = new Paragraph("Following is a 3 X 2 table.");
section1.add(someSectionText);
document.add(chapter1);

// 关闭文档
document.close();
}

}

‘叁’ 如何运用Java组件itext生成pdf

实现流程:
一、iText介绍
iText是着名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。
二、建立第一个PDF文档
用iText生成PDF文档需要5个步骤:
①建立com.lowagie.text.Document对象的实例。
Document document = new Document();
②建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
PDFWriter.getInstance(document, new FileOutputStream("Helloworld.PDF"));
③打开文档。
document.open();
④向文档中添加内容。
document.add(new Paragraph("Hello World"));
⑤关闭文档。
document.close();
通过上面的5个步骤,就能产生一个Helloworld.PDF的文件,文件内容为"Hello World"。
建立com.lowagie.text.Document对象的实例
com.lowagie.text.Document对象的构建函数有三个,分别是:
public Document();
public Document(Rectangle pageSize);
public Document(Rectangle pageSize,
int marginLeft,
int marginRight,
int marginTop,
int marginBottom);
构建函数的参数pageSize是文档页面的大小,对于第一个构建函数,页面的大小为A4,同Document(PageSize.A4)的效果一样;
对于第三个构建函数,参数marginLeft、marginRight、marginTop、marginBottom分别为左、右、上、下的页边距。
通过参数pageSize可以设定页面大小、面背景色、以及页面横向/纵向等属性。iText定义了A0-A10、AL、LETTER、
HALFLETTER、_11x17、LEDGER、NOTE、B0-B5、ARCH_A-ARCH_E、FLSA
和FLSE等纸张类型,也可以通过Rectangle pageSize = new Rectangle(144,
720);自定义纸张。通过Rectangle方法rotate()可以将页面设置成横向。
书写器(Writer)对象
一旦文档(document)对象建立好之后,需要建立一个或多个书写器(Writer)对象与之关联。通过书写器(Writer)对象可以将具体文档
存盘成需要的格式,如com.lowagie.text.PDF.PDFWriter可以将文档存成PDF文件,
com.lowagie.text.html.HtmlWriter可以将文档存成html文件。
设定文档属性
在文档打开之前,可以设定文档的标题、主题、作者、关键字、装订方式、创建者、生产者、创建日期等属性,调用的方法分别是:
public boolean addTitle(String title)
public boolean addSubject(String subject)
public boolean addKeywords(String keywords)
public boolean addAuthor(String author)
public boolean addCreator(String creator)
public boolean addProcer()
public boolean addCreationDate()
public boolean addHeader(String name, String content)
其中方法addHeader对于PDF文档无效,addHeader仅对html文档有效,用于添加文档的头信息。
当新的页面产生之前,可以设定页面的大小、书签、脚注(HeaderFooter)等信息,调用的方法是:
public boolean setPageSize(Rectangle pageSize)
public boolean add(Watermark watermark)
public void removeWatermark()
public void setHeader(HeaderFooter header)
public void resetHeader()
public void setFooter(HeaderFooter footer)
public void resetFooter()
public void resetPageCount()
public void setPageCount(int pageN)
如果要设定第一页的页面属性,这些方法必须在文档打开之前调用。
对于PDF文档,iText还提供了文档的显示属性,通过调用书写器的setViewerPreferences方法可以控制文档打开时Acrobat Reader的显示属性,如是否单页显示、是否全屏显示、是否隐藏状态条等属性。
另外,iText也提供了对PDF文件的安全保护,通过书写器(Writer)的setEncryption方法,可以设定文档的用户口令、只读、可打印等属性。
添加文档内容
所有向文档添加的内容都是以对象为单位的,如Phrase、Paragraph、Table、Graphic对象等。比较常用的是段落(Paragraph)对象,用于向文档中添加一段文字。
三、文本处理
iText中用文本块(Chunk)、短语(Phrase)和段落(paragraph)处理文本。
文本块(Chunk)是处理文本的最小单位,有一串带格式(包括字体、颜色、大小)的字符串组成。如以下代码就是产生一个字体为HELVETICA、大小为10、带下划线的字符串:
Chunk chunk1 = new Chunk("This text is underlined", FontFactory.getFont(FontFactory.HELVETICA, 12, Font.UNDERLINE));
短语(Phrase)由一个或多个文本块(Chunk)组成,短语(Phrase)也可以设定字体,但对于其中以设定过字体的文本块
(Chunk)无效。通过短语(Phrase)成员函数add可以将一个文本块(Chunk)加到短语(Phrase)中,
如:phrase6.add(chunk);
段落(paragraph)由一个或多个文本块(Chunk)或短语(Phrase)组
成,相当于WORD文档中的段落概念,同样可以设定段落的字体大小、颜色等属性。另外也可以设定段落的首行缩进、对齐方式(左对齐、右对齐、居中对齐)。
通过函数setAlignment可以设定段落的对齐方式, setAlignment的参数1为居中对齐、2为右对齐、3为左对齐,默认为左对齐。
四、表格处理
iText中处理表格的类为:com.lowagie.text.Table和com.lowagie.text.PDF.PDFPTable,对于比
较简单的表格处理可以用com.lowagie.text.Table,但是如果要处理复杂的表格,这就需要
com.lowagie.text.PDF.PDFPTable进行处理。这里就类com.lowagie.text.Table进行说明。
类com.lowagie.text.Table的构造函数有三个:
①Table (int columns)
②Table(int columns, int rows)
③Table(Properties attributes)
参数columns、rows、attributes分别为表格的列数、行数、表格属性。创建表格时必须指定表格的列数,而对于行数可以不用指定。
建立表格之后,可以设定表格的属性,如:边框宽度、边框颜色、衬距(padding space 即单元格之间的间距)大小等属性。下面通过一个简单的例子说明如何使用表格,代码如下:
1:Table table = new Table(3);
2:table.setBorderWidth(1);
3:table.setBorderColor(new Color(0, 0, 255));
4:table.setPadding(5);
5:table.setSpacing(5);
6:Cell cell = new Cell("header");
7:cell.setHeader(true);
8:cell.setColspan(3);
9:table.addCell(cell);
10:table.endHeaders();
11:cell = new Cell("example cell with colspan 1 and rowspan 2");
12:cell.setRowspan(2);
13:cell.setBorderColor(new Color(255, 0, 0));
14:table.addCell(cell);
15:table.addCell("1.1");
16:table.addCell("2.1");
17:table.addCell("1.2");
18:table.addCell("2.2");
19:table.addCell("cell test1");
20:cell = new Cell("big cell");
21:cell.setRowspan(2);
22:cell.setColspan(2);
23:table.addCell(cell);
24:table.addCell("cell test2");
运行结果如下:
header
example cell with colspan 1 and rowspan 2 1.1 2.1
1.2 2.2
cell test1 big cell
cell test2
代码1-5行用于新建一个表格,如代码所示,建立了一个列数为3的表格,并将边框宽度设为1,颜色为蓝色,衬距为5。
代码6-10行用于设定表格的表头,第7行cell.setHeader(true);是将该单元格作为表头信息显示;第8行
cell.setColspan(3);指定了该单元格占3列;为表格添加表头信息时,要注意的是一旦表头信息添加完了之后,必须调用
endHeaders()方法,如第10行,否则当表格跨页后,表头信息不会再显示。
代码11-14行是向表格中添加一个宽度占一列,长度占二行的单元格。
往表格中添加单元格(cell)时,按自左向右、从上而下的次序添加。如执行完11行代码后,表格的右下方出现2行2列的空白,这是再往表格添加单元格时,先填满这个空白,然后再另起一行,15-24行代码说明了这种添加顺序。
五、图像处理
iText中处理表格的类为com.lowagie.text.Image,目前iText支持的图像格式有:GIF, Jpeg, PNG,
wmf等格式,对于不同的图像格式,iText用同样的构造函数自动识别图像格式。通过下面的代码分别获得gif、jpg、png图像的实例。
Image gif = Image.getInstance("vonnegut.gif");
Image jpeg = Image.getInstance("myKids.jpg");
Image png = Image.getInstance("hitchcock.png");
图像的位置
图像的位置主要是指图像在文档中的对齐方式、图像和文本的位置关系。IText中通过函数public void setAlignment(int
alignment)进行处理,参数alignment为Image.RIGHT、Image.MIDDLE、Image.LEFT分别指右对齐、居中、
左对齐;当参数alignment为Image.TEXTWRAP、Image.UNDERLYING分别指文字绕图形显示、图形作为文字的背景显示。这
两种参数可以结合以达到预期的效果,如setAlignment(Image.RIGHT|Image.TEXTWRAP)显示的效果为图像右对齐,文字
围绕图像显示。
图像的尺寸和旋转
如果图像在文档中不按原尺寸显示,可以通过下面的函数进行设定:
public void scaleAbsolute(int newWidth, int newHeight)
public void scalePercent(int percent)
public void scalePercent(int percentX, int percentY)
函数public void scaleAbsolute(int newWidth, int
newHeight)直接设定显示尺寸;函数public void scalePercent(int
percent)设定显示比例,如scalePercent(50)表示显示的大小为原尺寸的50%;而函数scalePercent(int
percentX, int percentY)则图像高宽的显示比例。
如果图像需要旋转一定角度之后在文档中显示,可以通过函数public void setRotation(double r)设定,参数r为弧度,如果旋转角度为30度,则参数r= Math.PI / 6。
六、中文处理
默认的iText字体设置不支持中文字体,需要下载远东字体包iTextAsian.jar,否则不能往PDF文档中输出中文字体。通过下面的代码就可以在文档中使用中文了:
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
com.lowagie.text.Font FontChinese = new com.lowagie.text.Font(bfChinese, 12, com.lowagie.text.Font.NORMAL);
Paragraph pragraph=new Paragraph("你好", FontChinese);

‘肆’ java导出PDF文档

java导出pdf需要用到iText库,iText是着名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf
的文档,而且可以将XML、Html文件转化为PDF文件。
iText的安装非常方便,下载iText.jar文件后,只需要在系统的CLASSPATH中加入iText.jar的路径,在程序中就可以使用
iText类库了。
代码如下:

public class createPdf {
//自己做的一个简单例子,中间有图片之类的
//先建立Document对象:相对应的 这个版本的jar引入的是com.lowagie.text.Document
Document document = new Document(PageSize.A4, 36.0F, 36.0F, 36.0F, 36.0F);
public void getPDFdemo() throws DocumentException, IOException{
//这个导出用的是 iTextAsian.jar 和iText-2.1.3.jar 属于比较老的方法。 具体下在地址见:
//首先
//字体的定义:这里用的是自带的jar里面的字体
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
// 当然你也可以用你电脑里面带的字体库
//BaseFont bfChinese = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1",BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
//定义字体 注意在最新的包里面 颜色是封装的
Font fontChinese8 = new Font(bfChinese, 10.0F, 0, new Color(59, 54, 54));
//生成pdf的第一个步骤:
//保存本地指定路径
saveLocal();
document.open();
ByteArrayOutputStream ba = new ByteArrayOutputStream();
// PdfWriter writer = PdfWriter.getInstance(document, ba);
document.open();
//获取此编译的文件路径
String path = this.getClass().getClassLoader().getResource("").getPath();
//获取根路径
String filePath = path.substring(1, path.length()-15);
//获取图片路径 找到你需要往pdf上生成的图片
//这里根据自己的获取的路径写 只要找到图片位置就可以
String picPath = filePath +"\\WebContent" +"\\images\\";
//往PDF中添加段落
Paragraph pHeader = new Paragraph();
pHeader.add(new Paragraph(" 你要生成文字写这里", new Font(bfChinese, 8.0F, 1)));
//pHeader.add(new Paragraph("文字", 字体 可以自己写 也可以用fontChinese8 之前定义好的 );
document.add(pHeader);//在文档中加入你写的内容
//获取图片
Image img2 = Image.getInstance(picPath +"ccf-stamp-new.png");
//定义图片在文档中显示的绝对位置
img2.scaleAbsolute(137.0F, 140.0F);
img2.setAbsolutePosition(330.0F, 37.0F);
//将图片添加到文档中
document.add(img2);
//关闭文档
document.close();
/*//设置文档保存的文件名
response.setHeader("Content-
disposition", "attachment;filename=\""+ new String(("CCF会员资格确认
函.pdf").getBytes("GBK"),"ISO-8859-1") + "\"");
//设置类型
response.setContentType("application/pdf");
response.setContentLength(ba.size());
ServletOutputStream out = response.getOutputStream();
ba.writeTo(out);
out.flush();*/
}
public static void main(String[]args) throws DocumentException, IOException{
createPdf pdf= new createPdf();
pdf.getPDFdemo();
}

//指定一个文件进行保存 这里吧文件保存到D盘的text.pdf
public void saveLocal() throws IOException, DocumentException{
//直接生成PDF 制定生成到D盘test.pdf
File file = new File("D:\\text2.pdf");
file.createNewFile();
PdfWriter.getInstance(document, new FileOutputStream(file));

}
}

‘伍’ java中poi如何将word文档转换成pdf

itext等等,可以方便转换的了
~
~
~
~

‘陆’ java怎么输出pdf格式的文件

java导出pdf需要用到iText库,iText是着名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf
的文档,而且可以将XML、Html文件转化为PDF文件。
iText的安装非常方便,下载iText.jar文件后,只需要在系统的CLASSPATH中加入iText.jar的路径,在程序中就可以使用
iText类库了。
代码如下:

public class createPdf {
//自己做的一个简单例子,中间有图片之类的
//先建立Document对象:相对应的 这个版本的jar引入的是com.lowagie.text.Document
Document document = new Document(PageSize.A4, 36.0F, 36.0F, 36.0F, 36.0F);
public void getPDFdemo() throws DocumentException, IOException{
//这个导出用的是 iTextAsian.jar 和iText-2.1.3.jar 属于比较老的方法。 具体下在地址见:
//首先
//字体的定义:这里用的是自带的jar里面的字体
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
// 当然你也可以用你电脑里面带的字体库
//BaseFont bfChinese = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1",BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
//定义字体 注意在最新的包里面 颜色是封装的
Font fontChinese8 = new Font(bfChinese, 10.0F, 0, new Color(59, 54, 54));
//生成pdf的第一个步骤:
//保存本地指定路径
saveLocal();
document.open();
ByteArrayOutputStream ba = new ByteArrayOutputStream();
// PdfWriter writer = PdfWriter.getInstance(document, ba);
document.open();
//获取此编译的文件路径
String path = this.getClass().getClassLoader().getResource("").getPath();
//获取根路径
String filePath = path.substring(1, path.length()-15);
//获取图片路径 找到你需要往pdf上生成的图片
//这里根据自己的获取的路径写 只要找到图片位置就可以
String picPath = filePath +"\\WebContent" +"\\images\\";
//往PDF中添加段落
Paragraph pHeader = new Paragraph();
pHeader.add(new Paragraph(" 你要生成文字写这里", new Font(bfChinese, 8.0F, 1)));
//pHeader.add(new Paragraph("文字", 字体 可以自己写 也可以用fontChinese8 之前定义好的 );
document.add(pHeader);//在文档中加入你写的内容
//获取图片
Image img2 = Image.getInstance(picPath +"ccf-stamp-new.png");
//定义图片在文档中显示的绝对位置
img2.scaleAbsolute(137.0F, 140.0F);
img2.setAbsolutePosition(330.0F, 37.0F);
//将图片添加到文档中
document.add(img2);
//关闭文档
document.close();
/*//设置文档保存的文件名
response.setHeader("Content-
disposition", "attachment;filename=\""+ new String(("CCF会员资格确认
函.pdf").getBytes("GBK"),"ISO-8859-1") + "\"");
//设置类型
response.setContentType("application/pdf");
response.setContentLength(ba.size());
ServletOutputStream out = response.getOutputStream();
ba.writeTo(out);
out.flush();*/
}
public static void main(String[]args) throws DocumentException, IOException{
createPdf pdf= new createPdf();
pdf.getPDFdemo();
}

//指定一个文件进行保存 这里吧文件保存到D盘的text.pdf
public void saveLocal() throws IOException, DocumentException{
//直接生成PDF 制定生成到D盘test.pdf
File file = new File("D:\\text2.pdf");
file.createNewFile();
PdfWriter.getInstance(document, new FileOutputStream(file));

}
}

‘柒’ Java如何使用Java创建一个空的PDF文档

package com.yii;import java.io.IOException;import org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.pdmodel.PDPage;// 需要下 apache pdfbox包和apache.commons.loggin乌,下载地址:http://pdfbox.apache.org/download.cgi 和 http://commons.apache.org/proper/commons-logging/download_logging.cgi// 在本示例中下载使用的是:pdfbox-2.0.7.jar // 将下载的pdfbox-2.0.7.jar添加到Eclipse项目依懒库中。// 右键点击:"java_apache_pdf_box"->"Bulid Path"->"Add External Artchives...",然后选笃下载的"pdfbox-2.0.7.jar"和"commons-logging-1.2.jar"文件 public class CreatingEmptyPdf {
public static void main(String args[]) throws IOException {

// Creating PDF document object
PDDocument document = new PDDocument();

// Add an empty page to it
document.addPage(new PDPage());

// Saving the document
document.save("F:/worksp/javaexamples/java_apache_pdf_box/BlankPdf.pdf");
System.out.println("PDF created");

// Closing the document
document.close();
}}

阅读全文

与java命令生成pdf文档相关的资料

热点内容
安卓应用软件如何卸载 浏览:913
ug简化体命令 浏览:743
cs连接服务器失败什么意思 浏览:866
脚本命令快捷 浏览:677
怎么下载网络连接宽带连接服务器地址 浏览:89
活动专栏网站源码 浏览:532
有代理服务器地址ip怎么设置方法 浏览:294
androidv23 浏览:440
小米和魅族的云服务器地址 浏览:243
jpg换成pdf 浏览:986
php获取目录名 浏览:986
浪潮服务器怎么拆主板 浏览:869
phppost提交json 浏览:576
linux无法使用ftp命令 浏览:807
电脑怎么修改无线密码并加密 浏览:954
程序员中高级班 浏览:146
澳门分布式服务器云主机 浏览:748
python列表中有有add吗 浏览:128
crsa加密解密算法 浏览:738
linux设置打开终端的快捷键设置 浏览:340