您的位置:首页 > 编程语言 > Java开发

java 生成pdf文件,添加图片

2017-03-23 10:04 465 查看
from  http://blog.csdn.net/luckyspring/article/details/1633611

所需要的包:

1.  iText    下载地址:  http://nchc.dl.sourceforge.net/sourceforge/itext/itext-2.0.3.jar

2.  iTextSsian    下载地址:  http://itext.sourceforge.net/downloads/iTextAsian.jar   (设置亚洲国家的字体)

Hello.Java   生成 Hello.pdf文件

代码:

package com.test;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import com.lowagie.text.Document;

import com.lowagie.text.DocumentException;

import com.lowagie.text.Font;

import com.lowagie.text.Paragraph;

import com.lowagie.text.pdf.BaseFont;

import com.lowagie.text.pdf.PdfWriter;

public class HelloWorld {

 public static void main(String[] args) throws IOException {

  //创建一个文档对象

  Document doc = new Document();

  try {

   // 定义输出位置并把文档对象装入输出对象中

   PdfWriter.getInstance(doc, new FileOutputStream("c:/hello.pdf"));

   // 打开文档对象

   doc.open();

   

   // 设置中文字体

   

   BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

   Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);

   // 加入文字“HelloWorld ------ 中国北京,我的2008 .”

   

   String str = "HelloWorld ------ 中国北京, 我的2008 .";

   

   Paragraph tt = new Paragraph(str, FontChinese);

   doc.add(tt);

   // 加入图片Deepinpl.jpg

   

   Image jpg = Image.getInstance("c:/Deepinpl.jpg");

   

   jpg.setAlignment(Image.ALIGN_CENTER);

   

   doc.add(jpg);

   // 关闭文档对象,释放资源

   

   doc.close();

   

   

  } catch (FileNotFoundException e) {

   e.printStackTrace();

  } catch (DocumentException e) {

   e.printStackTrace();

  }

  

  System.out.println("OK");

 }

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: