VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > c#教程 >
  • C#教程之C#教程之Pdf File Writer 中文应用(PDF文件编写器C#(2)

本站最新发布   C#从入门到精通
试听地址  
https://www.xin3721.com/eschool/CSharpxin3721/

// 基本的 public PdfBookmark AddBookmark ( String Title, // bookmark title PdfPage Page, // bookmark page Double YPos, // bookmark vertical position relative to bottom left corner of the page Boolean OpenEntries // true is display children. false hide children ) //标题颜色和样式 public PdfBookmark AddBookmark ( String Title, // bookmark title PdfPage Page, // bookmark page Double YPos, // bookmark vertical position relative to bottom left corner of the page Color Paint, // bookmark color. Coloe.Empty is display title in default color TextStyle TextStyle, // bookmark text style: normal, bold, italic, bold-italic Boolean OpenEntries // true is display children. false hide children ) // PointX和缩放 public PdfBookmark AddBookmark ( String Title, // bookmark title PdfPage Page, // bookmark page Double XPos, // bookmark horizontal position relative to bottom left corner of the page Double YPos, // bookmark vertical position relative to bottom left corner of the page Double Zoom, // Zoom factor. 1.0 is 100%. 0.0 is ignore zoom. Boolean OpenEntries // true is display children. false hide children ) // 完整 public PdfBookmark AddBookmark ( String Title, // bookmark title PdfPage Page, // bookmark page Double XPos, // bookmark horizontal position relative to bottom left corner of the page Double YPos, // bookmark vertical position relative to bottom left corner of the page Double Zoom, // Zoom factor. 1.0 is 100%. 0.0 is ignore zoom. Color Paint, // bookmark color. Coloe.Empty is display title in default color TextStyle TextStyle, // bookmark text style: normal, bold, italic, bold-italic Boolean OpenEntries // true is display children. false hide children )
复制代码

  PdfBookmark类暴露一个方法GetChild您可以通过调用GetChild一个或多个整数参数来获取任何书签每个参数是级别中子位置的零基本参数。例如GetChild(2)第一级的第三项。GetChild(2, 3)是第三个第一级项目的第四个第二级项目。

2.10。图表支持

  PDF规范没有特定的图表支持。PDF文件编写器库通过允许开发人员创建Microsoft Charting对象并将此对象作为图像绘制到PDF文件中来提供图表支持。有关Microsoft图表控件注释MSDN库文档Visual Studio 2012图表控件的详细信息。图表名称空间的文档在“ 数据可视化图表命名空间”中提供。附上ChartExample.cs有四个图表的例子。如果您打算使用图表,您需要添加System.Windows.Forms.Visualization对您的项目的引用。在每个源模块使用Chart你需要引用System.Windows.Forms.DataVisualization.Charting命名空间。

  将图表添加到PDF文档是四个步骤的过程。

  • 创建图表对象。
  • 创建PdfChart对象。
  • 构建图表。
  • 绘制PdfChart到PdfContents。

  创建图表的推荐方法是使用PdfChart对象的静态方法

//  参数:文档对象,宽,高,分辨率
Chart MyChart = PdfChart.CreateChart(PdfDocument Document, Double Width, Double Height, Double Resolution);

  你可以Chart自己实例化类。

Chart MyChart = new Chart();
MyChart.RenderingDpiY = 300;    // example of 300 pixels per inch
MyChart.Width = 1950;        // example of 6.5 inches in pixels    
Mychart.Height = 1350;        // example of 4.6 inches in pixels

  接下来PdfChartChart上面创建一个或者,您可以覆盖分辨率。

// resolution is optional. It will override the resolution set above.
PdfChart MyPdfChart = new PdfChart(PdfDocument Document, Chart MyChart, Double Resolution);

  接下来,您构建您的图表。ChartExample.cs有四个例子。构建图表的文档超出了本文的范围。互联网上有很多例子。

  PdfChart有一种CreateFont方法来简化字体的创建。它将基于图表的分辨率计算字体大小。

// FontSizeUnit is an enumeration
// Available units: pixel, point, UserUnit, Inch, cm, mm
Font CreateFont(String FontFamilyName, FontStyle Style, Double FontSize, FontSizeUnit Unit);

  最后一步是绘制图表。

复制代码
// Draw the chart at OrigX, OrigY in user units
// The width and height of the chart are taken from the Chart object.
// They are calculated from the size in pixels and resolution of the chart.
public void PdfContents.DrawChart(PdfChart MyPdfChart, Double OrigX, Double OrigY);

// Draw the chart at OrigX, OrigY with Width and Height as specified, all in user units.
// NOTE: Width and Height should be selected to agree with the aspect ratio of the chart object.
public void PdfContents.DrawChart(PdfChart MyPdfChart, Double OrigX, Double OrigY, Double Width, Double Height);
复制代码

  本PdfChart类提供了一些可选的方法来控制图像的定位。

  该ImageSize方法返回具有适合给定区域的正确宽高比的最大矩形。

SizeD ImageSize(Double Width, Double Height);

  该ImageSizePosition方法返回具有适合给定区域的正确宽高比的最大矩形,并基于ContentAlignment枚举对其进行定位。

ImageSizePos ImageSizePosition(Double Width, Double Height, ContentAlignment Alignment);

2.11  打印文档支持

  打印文档支持允许您以打印到打印机和生成PDF文档的相同方式打印报告。这种产生PDF文件的方法和PdfContents用于产生PDF文件的方法之间的区别在于栅格图形与矢量图形之间的差异。打印文档支持每页创建一个jpeg图像。PrintExample.cs有创建三页文档的示例。

  通常每个页面是页面的完整图像。如果您的页面是Letter 尺寸,分辨率为每英寸300像素,每个像素为3个字节,页面的位图将是25.245MB长。PrintPdfDocument具有CropRect可以显着减小位图的大小的方法假设使用一英寸边距,位图的活动大小将减少到15.795 MB。减少37.4%。

复制代码
// main program
// Create empty document
Document = new PdfDocument(PaperType.Letter, false, UnitOfMeasure.Inch);

// create PrintPdfDocument producing an image with 300 pixels per inch 创建一个300像素每英寸的PrintPdfDocument
 PdfImageControl ImageControl = new PdfImageControl();
 ImageControl.Resolution = 300.0; 
PrintPdfDocument Print = new PrintPdfDocument(Document, ImageControl); 

// PrintPage in the delegate method PrintPageEventHandler 
// This method will print one page at a time to PrintDocument  
Print.PrintPage += PrintPage;
 // set margins in user units (Left, top, right, bottom) 边距设置
// note the margins order are per .net standard and not PDF standard 
Print.SetMargins(1.0, 1.0, 1.0, 1.0);
 // crop the page image result to reduce PDF file size //缩小尺寸
 // the crop rectangle is per .net standard. 

// The origin is top left. 原点在左上方
Print.CropRect = new RectangleF(0.95F, 0.95F, 6.6F, 9.1F); 

// initiate the printing process (calling the PrintPage method)启动打印进程
 // after the document is printed, add each page as an image to PDF file.在打印完文档之后,将每个页面作为一个图像添加到PDF文件中。


 Print.AddPagesToPdfDocument();
 // dispose of the PrintDocument object 

Print.Dispose(); 

// create the PDF file
 Document.CreateFile(FileName);
复制代码

  PrintPage方法的示例

复制代码
// Print each page of the document to PrintDocument class打印文档的每一页的PrintDocument类

// You can use standard PrintDocument.PrintPage(...) method.
// NOTE: The graphics origin is top left and Y axis is pointing down.图形原点是左上角,Y轴指向下方

// In other words this is not PdfContents printing.换句话说,这不是PdfContents的打印
 public void PrintPage(object sender, PrintPageEventArgs e) { 

// graphics object short cut Graphics G = e.Graphics; 

// Set everything to high quality 
G.SmoothingMode = SmoothingMode.HighQuality;
 G.InterpolationMode = InterpolationMode.HighQualityBicubic;
 G.PixelOffsetMode = PixelOffsetMode.HighQuality;
 G.CompositingQuality = CompositingQuality.HighQuality;
 // print area within margins 
Rectangle PrintArea = e.MarginBounds; 

// draw rectangle around print area 

G.DrawRectangle(Pens.DarkBlue, PrintArea);
 // line height 
Int32 LineHeight = DefaultFont.Height + 8;
 Rectangle TextRect = new Rectangle(PrintArea.X + 4, PrintArea.Y + 4, PrintArea.Width - 8, LineHeight); 

// display page bounds
 // DefaultFont is defined somewhere else 
String text = String.Format("Page Bounds: Left {0}, Top {1}, Right {2}, Bottom {3}", e.PageBounds.Left, e.PageBounds.Top, e.PageBounds.Right, e.PageBounds.Bottom);
 G.DrawString(text, DefaultFont, Brushes.Black, TextRect); TextRect.Y += LineHeight; 

// display print area 
text = String.Format("Page Margins: Left {0}, Top {1}, Right {2}, Bottom {3}", 
    PrintArea.Left, PrintArea.Top, PrintArea.Right, PrintArea.Bottom); 
G.DrawString(text, DefaultFont, Brushes.Black, TextRect); TextRect.Y += LineHeight; 
// print some lines 

for(Int32 LineNo = 1; ; LineNo++)
 {
 text = String.Format("Page {0}, Line {1}", PageNo, LineNo); 
G.DrawString(text, DefaultFont, Brushes.Black, TextRect); 
TextRect.Y += LineHeight; 
if(TextRect.Bottom > PrintArea.Bottom)
 break;
 } 

// move on to next page 
PageNo++;
 e.HasMorePages = PageNo <= 3; 

return; }
复制代码

2.12  数据表(table)支持

  数据表类允许您在PDF文档中显示数据表。PdfTable是控制一个表的显示的主类。表由标题行和数据行组成。每行被划分为单元格。PdfTableCell控制一个标题单元或一个数据单元的显示。如果使用头,它将显示在表的顶部。可选地,它将显示在每个附加页面的顶部。要在单元格中显示数据,请将数据加载到的Value属性中PdfTableCell 数据可以是:文本字符串,基本数值,布尔,字符TextBox,图像,QR码或条形码。独立于数据,您可以加载文档链接,网络链接,视频,音频或嵌入文件的单元格。单击单元格区域内的任何位置将使PDF阅读器激活文档链接,网络链接,视频,音频或嵌入式文件数据的显示由PdfTableStyle 类控制。PdfTable类包含默认单元格样式和默认标题样式。您可以覆盖其中的私有样式的默认样式PdfTableCell要显示表,请创建一个PdfTable对象。接下来,您将初始化表,标题单元格,数据单元格和样式对象。最后,设置一个循环并加载一行的单元格值,然后绘制此行。此循环继续,直到显示所有数据。下面您将看到生成表所需的步骤顺序。

  调用DrawRow方法时,软件计算所需的行高。行高是最高单元格的高度。如果表中有足够的空间,将绘制该行。当底部的可用空间太小时,将调用新页面,并且可选标题和当前行显示在表格的顶部。如果所需的行高度过大,将不适合全空表,则会引发异常。为了适应长多行字符串,或TextBoxes软件可以灵活地处理这些情况。多行字符串由PdfTable转换为a TextBoxPdfTableStyle类有一个TextBoxPageBreakLines属性。如果此属性设置为零(默认值),则将TextBox其视为其他数据值。TextBox高度必须适合页面。如果TextBoxPageBreakLines设置为正整数,系统将计算单元格的高度作为TextBox高度或高度的前几行指定TextBoxPageBreakLines系统将绘制具有适合页面的行数的行。将创建一个新页面,并绘制其余的线条。换句话说,long的第一行块TextBox将至少是TextBoxPageBreakLines长的。TableExample.cs源包含长TextBox单元格的示例

  创建PdfTable对象。

// create table
PdfTable Table = new PdfTable(Page, Contents, Font, FontSize);

  page是当前的PdfPage。内容是当前的PdfContents。Font是表默认字体。FontSize是以点为单位的默认字体大小。

  在页面上定义表的区域。

// table's area on the page
Table.TableArea = new PdfRectangle(Left, Bottom, Right, Top);

// first page starting vertical position
Table.RowTopPosition = StartingTopPosition;

  四个参数是表格相对于左下角和用户单位的四边。如果在第一页上,表顶部位置不在设置RowTopPosition为开始顶部位置的页面的顶部。在后续页面上,表格将始终从顶部开始。如果TableArea未指定,库将其设置为默认页面大小减少1英寸边距。

  将表宽度划分为列。

// divide table area width into columns
StockTable.SetColumnWidth(Width1, Width2, Width3, ...);

  参数的数量是列数。表格宽度减去总边界线将与这些参数成比例。

  一旦使用SetColumnWidth方法设置列的数量,库将创建两个PdfTableCell数组。一个用于标题单元的数组和一个用于数据单元的数组。

  数据表的行和列可以用边框线分隔。边框线属性由PdfTableBorder定义PdfTableBorderStyle有四个水平边框线:TopBorderBottomBorderHeaderHorBorder标题行和第一个数据行之间以及CellHorBorder数据行之间。有两组垂直边框线:HeaderVertBorder用于标题行CellVertBorder中的垂直边框线的数组,以及用于表的数据部分中的列之间的垂直边框线的数组。数组大小是列数加一。数组元素零是表的左边框。数组元素列是表的右边框。所有其他元素是分隔列的行。这些行中的每一行可以单独定义。有一些方法可以一次定义所有边界线,或定义每个单独的边界线。

  定义所有边框线的方法:

复制代码
// clear all border lines
Table.Borders.ClearAllBorders();

// set all border lines to default values (no need to call)
// All frame lines are one point (1/72") wide
// All grid lines are 0.2 of one point wide
// All borders are black
Table.Borders.SetDefaultBorders();

// set all borders to same width and black color
Table.Borders.SetAllBorders(Double Width);

// set all borders to same width and a specified color
Table.Borders.SetAllBorders(Double Width, Color LineColor);

// set all borders to one width and all grid lines to another width all lines are black
Table.Borders.SetAllBorders(Double FrameWidth, Double GridWidth);

// set all borders to one width and color and all grid lines to another width and color
Table.Borders.SetAllBorders(Double FrameWidth, Color FrameColor, Double GridWidth, Color GridColor);

// set all frame borders to same width and black color and clear all grid lines
Table.Borders.SetFrame(Double Width);

// set all frame borders to same width and a specified color and clear all grid lines
Table.Borders.SetFrame(Double Width, Color LineColor);
复制代码

  可以清除或设置每个水平边界线。示例是顶部边框线:

复制代码
// clear border
Table.Borders.ClearTopBorder();

// set border with default color set to black
// Zero width means one pixel of the output device.
Table.Borders.SetTopBorder(Double LineWidth);

// set border
Table.Borders.SetTopBorder(Double LineWidth, Color LineColor);
复制代码

  可以清除或设置每个垂直边界线。示例是单元格的垂直边框线:

复制代码
// clear border
Table.Borders.ClearCellVertBorder(Int32 Index);

// set border with default color set to black
Table.Borders.SetCellVertBorder(Int32 Index, Double LineWidth);

// set border
Table.Borders.SetCellVertBorder(Int32 Index, Double LineWidth, Color LineColor);
复制代码

  设置其他可选的表属性。下面的示例中给出的值是默认值。

// header on each page
HeaderOnEachPage = true;

// minimum row height
MinRowHeight = 0.0;

  表信息每次处理一行。每行由单元格组成。每列一个单元格。单元格信息的显示由PdfTableStyle类控制。有大约20个样式属性。对于完整的列表视图的源代码或帮助文件。这些样式中的一些特定于要显示的信息的类型。这里是一个例子

复制代码
// make some changes to default header style
Table.DefaultHeaderStyle.Alignment = ContentAlignment.BottomRight;

// create private style for header first column
Table.Header[0].Style = Table.HeaderStyle;
Table.Header[0].Style.Alignment = ContentAlignment.MiddleLeft;

// load header value
Table.Header[0].Value = "Date";

// make some changes to default cell style
Table.DefaultCellStyle.Alignment = ContentAlignment.MiddleRight;
Table.DefaultCellStyle.Format = "#,##0.00";

// create private style for date column
Table.Cell[0].Style = StockTable.CellStyle;
Table.Cell[0].Style.Alignment = ContentAlignment.MiddleLeft;
Table.Cell[0].Style.Format = null;
复制代码

  初始化完成后,显示数据。下面的例子是从TableExample.cs这是一张股票价格表。有6列。

复制代码
// open stock daily price
StreamReader Reader = new StreamReader("SP500.csv");

// ignore header
Reader.ReadLine();

// read all daily prices
for(;;)
    {
    String TextLine = Reader.ReadLine();
    if(TextLine == null) break;

    String[] Fld = TextLine.Split(new Char[] {','});

    Table.Cell[ColDate].Value = Fld[ColDate];
    Table.Cell[ColOpen].Value = Double.Parse(Fld[ColOpen], NFI.PeriodDecSep);
    Table.Cell[ColHigh].Value = Double.Parse(Fld[ColHigh], NFI.PeriodDecSep);
    Table.Cell[ColLow].Value = Double.Parse(Fld[ColLow], NFI.PeriodDecSep);
    Table.Cell[ColClose].Value = Double.Parse(Fld[ColClose], NFI.PeriodDecSep);
    Table.Cell[ColVolume].Value = Int32.Parse(Fld[ColVolume]);
    StockTable.DrawRow();
    }

StockTable.Close();
复制代码

  该DrawRow(NewPage)方法具有可选参数Boolean NewPage = false默认值为false如果希望下一行打印在下一页的顶部,请将参数设置为true

  交互功能示例。

复制代码
// set cell number 6 with web link
BookList.Cell[6].WebLink = WebLinkString;

// another way to set weblink
BookList.Cell[6].AnnotAction = new AnnotWebLink(WebLinkString);

// set cell with document link to chapter 3
BookList.Cell[6].AnnotAction = new AnnotLinkAction("Chapter3");

// play video
PdfDisplayMedia Omega = new PdfDisplayMedia(PdfEmbeddedFile.CreateEmbeddedFile(Document, "Omega.mp4"));
BookList.Cell[6].AnnotAction = new AnnotDisplayMedia(Omega);

// play audio
PdfDisplayMedia RingSound = new PdfDisplayMedia(PdfEmbeddedFile.CreateEmbeddedFile(Document, "Ring01.wav"));
BookList.Cell[6].AnnotAction = new AnnotDisplayMedia(RingSound);

// allow user to save or view embedded file
PdfEmbeddedFile EmbeddedFile = PdfEmbeddedFile.CreateEmbeddedFile(Document, "BookList.txt");
BookList.Cell[6].AnnotAction = new AnnotFileAttachment(EmbeddedFile, FileAttachIcon.NoIcon);
复制代码

  对于数据表的源代码,更多的例子看看ArticleExample.csTableExample.cs有关类的更多详细信息PdfTable请查看帮助文件。PdfTableCellPdfTableStylePdfTableBorderPdfFileWriter.chm

2.13  播放视频文件

  该PdfFileWriter支持嵌入PDF文档中的视频文件。播放视频文件的完整示例在第7页OtherExample.cs 添加视频文件需要使用三个类。

    首先,您需要将视频文件嵌入到PDF文档中。

    第二,你需要定义如何播放视频。PdfDisplayMedia 类有许多方法来控制视频显示。请参考类的源代码和文档帮助文件。例如:RepeatCountScaleMedia 如果要在浮动窗口中播放视频,您必须使  用SetMediaWindow方法。

    第三,您需要在PDF页面上定义用户必须单击以激活视频的区域。如果要在注释区域可见时激活视频,请使用ActivateActionWhenPageIsVisible

复制代码
// define annotation rectangle that has the same aspect ratio as the video
PdfRectangle AnnotRect = ImageSizePos.ImageArea(480, 360,
AreaLeft, AreaBottom, AreaRight - AreaLeft, AreaTop - AreaBottom, ContentAlignment.MiddleCenter);

// create display media object
PdfDisplayMedia DisplayMedia = new PdfDisplayMedia(PdfEmbeddedFile.CreateEmbeddedFile(Document, "LooneyTunes.mp4"));

// create annotation object
PdfAnnotation Annotation = Page.AddScreenAction(AnnotRect, DisplayMedia);

// activate the video when the page becomes visible
// Annotation.ActivateActionWhenPageIsVisible(true);

// define X Object to paint the annotation area when the video is not playing
PdfXObject AnnotArea = AnnotationArea(AnnotRect.Width, AnnotRect.Height, Color.Lavender, Color.Indigo, "Click here to play the video");
Annotation.Appearance(AnnotArea);
复制代码

  浮动窗口视频显示

复制代码
// create display media object
PdfDisplayMedia DisplayMedia = new PdfDisplayMedia(PdfEmbeddedFile.CreateEmbeddedFile(Document, "Omega.mp4"));

// activate display controls
DisplayMedia.DisplayControls(true);

// repeat video indefinitly
DisplayMedia.RepeatCount(0);

// display in floating window
      



  
相关教程