using System;
using System.Data;
using System.IO;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.Data.OleDb;
namespace Unmi
{
class PdfTest
{
public static void Main(string[] args)
{
//查询 Excel 的 sheet1 获得 DataTable 对象
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\test.xls;Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
DataTable dt = new DataTable();
using (OleDbConnection conn = new OleDbConnection(strConn))
{
conn.Open();
//OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [sheet1$]", conn);
da.Fill(dt);
}
//为将要被创建的Pdf文档指定大小和颜色
Rectangle rec = new Rectangle(PageSize.A4.Rotate());//A4纸横向
//rec.BackgroundColor = new Color(System.Drawing.Color.Plum); //设置背景色
//创建Pdf文档
Document doc = new Document(rec);
//定义字体
Font fixedsysFont = FontFactory.GetFont("Fixedsys", 9);
//为Document创建多个PdfWriter对象
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream("c:\\test.pdf", FileMode.Create));
//例如创建 HtmlWriter 还能生成一个相应的 html 文件
//iTextSharp.text.html.HtmlWriter.GetInstance(doc, new FileStream("c:\\test.html", FileMode.Create));
//设置文档的边距,依次是 left, right, top, bottom
doc.SetMargins(17.2f, 18.8f, 15.8f, 15f);
//定义页眉
HeaderFooter header = new HeaderFooter(new Phrase(6f,"http://unmi.blogjava.net ", fixedsysFont),new Phrase(6f," "));
header.Border = Rectangle.NO_BORDER;
header.Alignment = Element.ALIGN_RIGHT;
doc.Header = header;
//可以在Open()方法调用前为doc添加摘要信息
doc.AddCreationDate();
doc.AddCreator("Unmi");
doc.AddAuthor("Unmi");
doc.AddTitle("iTextSharp 4 生成 PDF 文档示例");
doc.Open(); //打开文档
//向 PDF 文档添加一个 Table,其他的内容对象有 phrase、Paragraph、Graphic
Table pdfTable = new Table(dt.Columns.Count);
/*
* 要理解 Table 中的单元格怎么显示,先设定列数,然后逐个放 Cell,当前行的 Cell
* 数量到达列数时另起新行,可用单元格的 Rowspan,Colspan 设定跨行或跨列的数量
**/
pdfTable.Padding = 2;
pdfTable.Spacing = 2;
pdfTable.TableFitsPage = true;
pdfTable.Width = 98f;
//每一列的宽度比率,这里要求你的 Excel 第一张表有 6 列
pdfTable.Widths = new float[]{ 0.8f, 1f, 0.6f,0.6f,0.9f, 7f };
//让单元格内容能跨页显示
pdfTable.CellsFitPage = false;
//输出表头
foreach(DataColumn dc in dt.Columns)
{
Font headerFont = FontFactory.GetFont("Fixedsys", 10, Font.BOLD, Color.WHITE);
Cell cellHeader = new Cell(new Paragraph(dc.ColumnName, headerFont));
cellHeader.HorizontalAlignment = Element.ALIGN_CENTER;
cellHeader.Header = true;
cellHeader.BackgroundColor = Color.RED;
pdfTable.AddCell(cellHeader);
}
//pdfTable.EndHeaders();// 表头是否显示在每一页
//显示数据
foreach (DataRow dr in dt.Rows)
{
foreach (DataColumn dc in dt.Columns)
{
Cell cellData = new Cell(new Paragraph(dr[dc].ToString(), fixedsysFont));
pdfTable.AddCell(cellData);
}
}
doc.Add(pdfTable);
doc.Close();
}
}
}
[...] C# 使用 iTextSharp(4.1.2) 生成 PDF 文档 [...]