java怎么输出pdf格式的文件

Python011

java怎么输出pdf格式的文件,第1张

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", "attachmentfilename=\""+ 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导出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", "attachmentfilename=\""+ 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生成PDF 加密 水印

1、iText简介

iText是一个开放源码的Java类库,可以用来方便地生成PDF文件。大家通过访问http://sourceforge.net/project/showfiles.php?group_id=15255&release_id=167948

下载最新版本的类库,下载完成之后会得到一个.jar包,把这个包加入JDK的classpath即可使用。

如果生成的PDF文件中需要出现中文、日文、韩文字符,则还需要通过访问http://itext.sourceforge.net/downloads/iTextAsian.jar

下载iTextAsian.jar包。

关于iText类库的使用,http://www.lowagie.com/iText/tutorial/index.html

有比较详细的教程。该教程从入门开始,比较系统地介绍了在PDF文件中放入文字、图片、表格等的方法和技巧。

读完这片教程,大致就可以做一些从简单到复杂的PDF文件了。不过,试图通过教程解决在生成PDF文件过程中遇到的所有困难无疑是一种奢望。所以,阅读iText的api文档显得非常重要。读者在下载类库的同时,也可以下载类库的文档。

注:如果以上两个下载链接无法下载而且通过网络也找不到这个jar包的同志可以留下邮箱地址,我会在两个工作日之内发邮件过去。

以下部分我是我调试通过的源代码,提供大家参考:

import java.awt.*

import java.io.*

import com.lowagie.text.*

import com.lowagie.text.Font

import

com.lowagie.text.Rectangle

import com.lowagie.text.pdf.*

/**

* 最近的项目中使用Itext将txt文件转换为PDF文件, 并且实现对文件的一些权限控制。

现实对pdf文件加

*密,添加水印等。

*/

public class PDFConvertBL

{

//

txt原始文件的路径

private static final String txtFilePath = "d:/11.txt"

// 生成的pdf文件路径

private static final String pdfFilePath =

"d:/22.pdf"

// 添加水印图片路径

// private static final String

imageFilePath = "D:/33.jpg"

// 生成临时文件前缀

private static final

String prefix = "tempFile"

// 所有者密码

private static final String

OWNERPASSWORD = "12345678"

/**

* txt文件转换为pdf文件

*

* @param txtFile

txt文件路径

* @param pdfFile pdf文件路径

* @param userPassWord

用户密码

* @param waterMarkName 水印内容

* @param permission

操作权限

*/

public static void generatePDFWithTxt(String txtFile,

String pdfFile, String userPassWord, String

waterMarkName,

int permission)

{

try

{

// 生成临时文件

File file =

File.createTempFile(prefix, ".pdf")

//

创建pdf文件到临时文件

if (createPDFFile(txtFile, file))

{

// 增加水印和加密

waterMark(file.getPath(),

pdfFile, userPassWord, OWNERPASSWORD, waterMarkName, permission)

}

}

catch (Exception e)

{

e.printStackTrace()

}

}

/**

* 创建PDF文档

*

* @param txtFilePath

txt文件路径(源文件)

* @param pdfFilePath pdf文件路径(新文件)

*/

private

static boolean createPDFFile(String txtFilePath, File file)

{

// 设置纸张

Rectangle rect = new Rectangle(PageSize.A4)

//

设置页码

HeaderFooter footer = new HeaderFooter(new Phrase("页码:",

setChineseFont()), true)

footer.setBorder(Rectangle.NO_BORDER)

// step1

Document

doc = new Document(rect, 50, 50, 50, 50)

doc.setFooter(footer)

try

{

FileReader

fileRead = new FileReader(txtFilePath)

BufferedReader read = new

BufferedReader(fileRead)

// 设置pdf文件生成路径 step2

PdfWriter.getInstance(doc, new FileOutputStream(file))

//

打开pdf文件 step3

doc.open()

// 实例化Paragraph

获取写入pdf文件的内容,调用支持中文的方法. step4

while (read.ready())

{

// 添加内容到pdf(这里将会按照txt文件的原始样式输出)

doc.add(new Paragraph(read.readLine(), setChineseFont()))

}

// 关闭pdf文件 step5

doc.close()

return true

}

catch (Exception e)

{

e.printStackTrace()

return false

}

}

/**

* 在pdf文件中添加水印

*

* @param inputFile

原始文件

* @param outputFile 水印输出文件

* @param waterMarkName

水印名字

*/

private static void waterMark(String inputFile, String

outputFile, String userPassWord, String ownerPassWord,

String waterMarkName, int permission)

{

try

{

PdfReader reader = new PdfReader(inputFile)

PdfStamper stamper = new PdfStamper(reader, new

FileOutputStream(outputFile))

// 设置密码

stamper.setEncryption(userPassWord.getBytes(), ownerPassWord.getBytes(),

permission, false)

BaseFont base =

BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",

BaseFont.NOT_EMBEDDED)

int total = reader.getNumberOfPages() +

1

// Image image =

Image.getInstance(imageFilePath)

//

image.setAbsolutePosition(200, 400)

PdfContentByte

under

int j = waterMarkName.length()

char c =

0

int rise = 0

for (int i = 1i <total

i++)

{

rise = 500

under =

stamper.getUnderContent(i)

// 添加图片

//

under.addImage(image)

under.beginText()

under.setColorFill(Color.CYAN)

under.setFontAndSize(base,

30)

// 设置水印文字字体倾斜 开始

if (j >=

15)

{

under.setTextMatrix(200,

120)

for (int k = 0k <j

k++)

{

under.setTextRise(rise)

c =

waterMarkName.charAt(k)

under.showText(c +

"")

rise -= 20

}

}

else

{

under.setTextMatrix(180, 100)

for (int k = 0k <jk++)

{

under.setTextRise(rise)

c = waterMarkName.charAt(k)

under.showText(c +

"")

rise -= 18

}

}

// 字体设置结束

under.endText()

// 画一个圆

//

under.ellipse(250, 450, 350, 550)

//

under.setLineWidth(1f)

// under.stroke()

}

stamper.close()

}

catch (Exception

e)

{

e.printStackTrace()

}

}

/**

* 设置中文

*

* @return Font

*/

private static Font setChineseFont()

{

BaseFont base =

null

Font fontChinese = null

try

{

base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",

BaseFont.EMBEDDED)

fontChinese = new Font(base, 12,

Font.NORMAL)

}

catch (DocumentException e)

{

e.printStackTrace()

}

catch (IOException

e)

{

e.printStackTrace()

}

return fontChinese

}

public static void main(String[] args)

{

generatePDFWithTxt(txtFilePath, pdfFilePath, "123", "水印文字", 16)

}

}

文章参考一些网络博客稍加修改调试,特此申明

http://hi.baidu.com/sx_python/item/15081531ad7d1bc21b96965e