C# 导pdf之学习 (Rotativa)

public ActionResult PrintPDF(string id)
{
var dto = ;
return new ViewAsPdf("Print", dto)
{
PageMargins = new Margins(0, 0, 0, 0),
PageSize = Rotativa.Options.Size.A4
};//FileName = "Test.pdf",
}

 

 

主要使用的是ITextSharp方法,

参考文档:

(1)http://www.docin.com/p-23672859.html

(2) http://www.cnblogs.com/islands/archive/2008/06/27/1231288.html

(3)http://www.cnblogs.com/julyluo/p/3839788.html

1,iTextSharp
2,service stack
3,TestDriven
4,fastreport

 

 

iTextSharp开发步骤

class        所代表的含义
Paragraph 报表中的文本
Image 报表中的图片
PdfPTable 表格
PdfPCell 单元格
知道这4个类之后就是开发的步骤了:

1. 往单元格PdfPCell类中添加内容。

2.将单元格PdfPCell添加到PdfPTable。

3.将表格PdfPTable添加到Document。
在以上的步骤中最重要的就是第一步也就是往PdfPCell中添加内容,而PdfPCell中的内容又可以分为以下三种情况:
文本 Paragraph
图片 Image
表格 PdfPTable

一、  文本由Paragraph来表示,在添加之前还要注意一下字体的问题,因为我们用的是中文字体,如果用默认英文字体渲染则会乱码,
所以我们要先定义中文字体:
BaseFont BF_Light = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);


二、画图用的就是PdfContentByte类
//画线
canvas.SaveState();
canvas.SetLineWidth(2f);
canvas.MoveTo(100, 100);
canvas.LineTo(200, 200);
canvas.Stroke();
canvas.RestoreState();

//文本
ColumnText.ShowTextAligned(canvas, Element.ALIGN_RIGHT, new Phrase("JulyLuo测试", new Font(BF_Light, 10)), 100, 20, 0);


public void CellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases)
IPdfPCellEvent接口的意思就是在单元格添加到文档之后暴露的方法。很明显,通过postion参数我们可以获取坐标,canvases参数可以获取画板。
所以要画图就创建一个实现接口IPdfPCellEvent的类,然后在CellLayout方法中画线和文本:

//画图的类,和cell关联
ResolutionChart chart = new ResolutionChart(fileName, yMax, yScale);
cell.CellEvent = chart;

用iTextSharp进行开发,如果报表只有文本,图片则PdfPCell一个类就可以搞定。但如果要画一些bar chart,bar chart,这些图是需要
坐标来呈现,我们可以通过IPdfPCellEvent接口获取坐标,然后画相应的图

三、PdfPTable 

PdfPTable table
table.WidthPercentage=100;
table.HorizontalAlignment = Element.ALIGN_RIGHT;
table.SpacingBefore = 100f;
table.SpacingAfter = 100f;
table.TotalWidth = 100;
table.LockedWidth = true;

table.DefaultCell.BorderColor = new BaseColor(255,0,0);//改变默认列样式
PdfPTable 不提供合并列的功能,必须采用 嵌套表的方式实现 AddCell(PdfPTable table)

四、PdfPCell 

PdfPCell 通过cell1.Colspan = 2;设置跨列
单元格的高度:
cell1.NoWrap = true;//禁止文字自动换行,默认是自动换行的
cell1.FixedHeight = 100;//设置行的高度为固定值(超过内容部分丢失)
cell1.MinimumHeight= 100;//最小高度
单元格的对齐:
HorizontalAlignment水平对齐,VerticalAlignment垂直对齐
单元格的补白、行间距
补白:Padding,PaddingBottom,PaddingLeft,PaddingRight,PaddingTop
行间距:SetLeading(float fixedLeading, float multipliedLeading)
fixedLeading表示行间距的值,
multipliedLeading表示 字体大小的倍数
UseBorderPadding:强制将边框的宽度计算在内
UseAscender:递增
UseDescender:递降

跨页面的表 分割
HeaderRows,标题行的行数
SplitRows,是否拆分行,(默认是行优先,只有当一整页都无法显示一行时,才会拆分行)
页优先:SplitLate=false

在绝对位置添加table
public float WriteSelectedRows(int rowStart, int rowEnd, float xPos,
float yPos, PdfContentByte canvas);

大表格的内存管理
解决办法是,将大表格分解成若干表格,将这些表格首尾相连,输出的结果跟一张表格并无区别

 

posted @ 2015-04-07 15:42  小良哥  阅读(837)  评论(0编辑  收藏  举报