java 生成pdf文件,添加图片

来源:互联网 发布:硕士论文实证数据造假 编辑:程序博客网 时间:2024/05/19 02:02

所需要的包:

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");

 }

}

1 1