java中怎么利用poi和itext生成pdf文档

发布网友

我来回答

2个回答

热心网友

生成PDF文档代码如下:

package poi.itext;
import java.io.FileOutputStream;
import java.io.IOException;
import java.awt.Color;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
import com.lowagie.text.pdf.BaseFont;
/**
 * 创建Pdf文档
 * @author Administrator
 *
 */
public class HelloPdf
{
    public static void main(String[] args)throws Exception
    {
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
        // 第一步,创建document对象
        Rectangle rectPageSize = new Rectangle(PageSize.A4);
        
        //下面代码设置页面横置
        //rectPageSize = rectPageSize.rotate();
        
        //创建document对象并指定边距
        Document doc = new Document(rectPageSize,50,50,50,50);
        Document document = new Document();
        try
        {
            // 第二步,将Document实例和文件输出流用PdfWriter类绑定在一起
            //从而完成向Document写,即写入PDF文档
            PdfWriter.getInstance(document,new FileOutputStream("src/poi/itext/HelloWorld.pdf"));
            //第3步,打开文档
            document.open();
            //第3步,向文档添加文字. 文档由段组成
            document.add(new Paragraph("Hello World"));
            Paragraph par = new Paragraph("世界你好",FontChinese);
            document.add(par);
            PdfPTable table = new PdfPTable(3);
            for(int i=0;i<12;i++)
            {
                if (i == 0)
                {
                    PdfPCell cell = new PdfPCell();
                    cell.setColspan(3);
                    cell.setBackgroundColor(new Color(180,180,180));
                    cell.addElement(new Paragraph("表格头" , FontChinese));
                    table.addCell(cell);
                }
                else
                {
                    PdfPCell cell = new PdfPCell();
                    cell.addElement(new Paragraph("表格内容" , FontChinese));
                    table.addCell(cell);
                }
            }
            document.add(table);
        }
        catch (DocumentException de)
        {
            System.err.println(de.getMessage());
        }
        catch (IOException ioe)
        {
            System.err.println(ioe.getMessage());
        }
        //关闭document
        document.close();
        
        System.out.println("生成HelloPdf成功!");
     }
    
    
}

希望对你有帮助。

热心网友

一、iText介绍 iText是着名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。通过iText不仅可以生成PDF或rtf的文档,而且可以将XML、Html文件转化为PDF文件。 iText的安装非常方便,在http://www.lowagie.com/iText/down...

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com