C#生成pdf文件实例代码

  作者:bea

PDF文档格式相信大家都和熟悉。我们在网上下载的资料就是希望下载pdf文件格式的,这样好阅读。这里我们使用C#生成pdf文件代码,供大家学习交流。 下面是实例代码: using System; using System.Collections.Generic; using System.Drawing.Imaging; using System.IO; using System.Text; using iTextSharp.text; using iTextSharp.t
PDF文档格式相信大家都和熟悉。我们在网上下载的资料就是希望下载pdf文件格式的,这样好阅读。这里我们使用C#生成pdf文件代码,供大家学习交流。

下面是实例代码:

using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace Pbreak.PDf

{

class MyPdf
{

#region Fields

///
/// pdf文档
///
private Document _pdfDocument;

///
/// 基本字体
///
private BaseFont _bfSun =
BaseFont.CreateFont(@"c:\Windows\fonts\SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

#endregion

#region Constructors

///
/// 构造函数
///
///
public MyPdf(string fileName,ListView lvi)
{
Font font = new Font(_bfSun,21,1);
_pdfDocument = new Document(PageSize.A4,10,10,25,25);
PdfWriter writer = PdfWriter.GetInstance(_pdfDocument,new FileStream(fileName,FileMode.Create));

//添加页脚
HeaderFooter footer = new HeaderFooter(new Phrase(Program._resourceManager.GetString("page")), true);
footer.Alignment = 1;
footer.Border = Rectangle.ALIGN_CENTER; _pdfDocument.Footer = footer;

_pdfDocument.Open();

//添加标题
Paragraph Header = new Paragraph(new Paragraph(Program._resourceManager.GetString("weldTable"), font));
Header.Alignment = 1;
_pdfDocument.Add(Header);

//添加数据表格
_pdfDocument.NewPage();
_pdfDocument.Add(AddTable(lvi));

//添加图片
_pdfDocument.NewPage();
if(PrintHeads.ImageAddress != null && PrintHeads.ImageAddress.Length != 0)
{
foreach(string str in PrintHeads.ImageAddress)
{
iTextSharp.text.Image image =
iTextSharp.text.Image.GetInstance(str);
image.Alignment = iTextSharp.text.Image.MIDDLE_ALIGN;
_pdfDocument.Add(image);
}
}

_pdfDocument.Close();
}

#endregion

#region Methods

///
/// 添加数据表格
///
///
private Table AddTable(ListView lvi)
{
Font font = new Font(_bfSun,12,1);
Table myTable = new Table(4);
myTable.BorderWidth = 0;
myTable.BorderColor = new Color(0, 0, 255);
myTable.Cellpadding = 1;
myTable.TableFitsPage = true;

for(int columNum = 0; columNum != lvi.Columns.Count; columNum++)
{
Cell myCell = new Cell(new Phrase(lvi.Columns[columNum].Text, font));
myCell.BackgroundColor = iTextSharp.text.Color.LIGHT_GRAY;
myTable.AddCell(myCell);
myTable.EndHeaders();
}

for(int rowNum = 0; rowNum != lvi.Items.Count; rowNum++)
{
for(int columNum = 0; columNum != lvi.Columns.Count; columNum++)
{
myTable.AddCell(new Phrase(lvi.Items[rowNum].SubItems[columNum].Text,font));
}
}
return myTable;
}

#endregion
}

}

如果上面的代码还是不能解决您的问题,那么我们提供您一个更加详细讲解的文章链接:http://www.cnblogs.com/zhuor/archive/2005/12/31/308908.html
以上相关信息由信鸽网收集整理,转载请保留此链接:www.xinge360.com
有用  |  无用

猜你喜欢