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

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

DisplayMedia.SetMediaWindow(MediaWindow.Floating, 640, 360, WindowPosition.Center, WindowTitleBar.TitleBarWithCloseButton, WindowResize.KeepAspectRatio, "Floating Window Example"); Double LineSpacing = ArialNormal.LineSpacing(12.0); Double TextPosX = PosX + 0.5 * AreaWidth; Double TextPosY = PosY + 0.5 * AreaHeight + LineSpacing; Double TextWidth = Contents.DrawText(ArialNormal, 12.0, TextPosX, TextPosY, TextJustify.Center, "Click this text to play video"); TextPosY -= LineSpacing; Contents.DrawText(ArialNormal, 12.0, TextPosX, TextPosY, TextJustify.Center, "in floating window"); // create annotation object PdfRectangle AnnotRect = new PdfRectangle(TextPosX - 0.5 * TextWidth, TextPosY - ArialNormal.DescentPlusLeading(12.0), TextPosX + 0.5 * TextWidth, TextPosY + ArialNormal.AscentPlusLeading(12.0) + LineSpacing); Page.AddScreenAction(AnnotRect, DisplayMedia);
复制代码

 2.14  播放声音文件

  该PdfFileWriter支持嵌入PDF文档中的声音文件。播放声音文件的完整示例在第7页中给出OtherExample.cs嵌入声音文件与视频文件基本相同。唯一明显的区别是没有什么可以显示。

复制代码
// create embedded media file
PdfDisplayMedia DisplayMedia = new PdfDisplayMedia(PdfEmbeddedFile.CreateEmbeddedFile(Document, "Ring01.wav"));
DisplayMedia.SetMediaWindow(MediaWindow.Hidden);
AnnotDisplayMedia RingSound = new AnnotDisplayMedia(DisplayMedia);

// display text area to activate the sound
Double LineSpacing = ArialNormal.LineSpacing(12.0);
Double TextPosX = PosX + 0.5 * AreaWidth;
Double TextPosY = PosY + 0.5 * AreaHeight + LineSpacing;
Contents.DrawTextWithAnnotation(Page, ArialNormal, 12.0, TextPosX, TextPosY, TextJustify.Center,
  DrawStyle.Normal, Color.Red, "Click this text to play", RingSound);
TextPosY -= LineSpacing;
Contents.DrawTextWithAnnotation(Page, ArialNormal, 12.0, TextPosX, TextPosY, TextJustify.Center,
  DrawStyle.Normal, Color.Red, "Ringing sound", RingSound);
复制代码

2.15  附加数据文件

  在PdfFileWriter支持PDF文档中嵌入数据文件。嵌入文件的完整示例在第7页中给出OtherExample.cs用户可以保存文件或显示文件。

复制代码
// create embedded media file
PdfEmbeddedFile EmbeddedFile = PdfEmbeddedFile.CreateEmbeddedFile(Document, "BookList.txt");
AnnotFileAttachment FileIcon = new AnnotFileAttachment(EmbeddedFile, FileAttachIcon.Paperclip);

// display text area to activate the file attachment
Double LineSpacing = ArialNormal.LineSpacing(12.0);
Double TextPosX = PosX + 0.5 * AreaWidth;
Double TextPosY = PosY + 0.5 * AreaHeight + LineSpacing;
Contents.DrawText(ArialNormal, 12.0, TextPosX, TextPosY, TextJustify.Center, "Right click on the paper clip");
TextPosY -= LineSpacing;
Double TextWidth = Contents.DrawText(ArialNormal, 12.0, TextPosX, TextPosY, TextJustify.Center, "to open or save the attached file");

// annotation
Double IconPosX = TextPosX + 0.5 * TextWidth + 0.1;
Double IconPosY = TextPosY;
PdfRectangle AnnotRect = new PdfRectangle(IconPosX, IconPosY, IconPosX + 0.15, IconPosY + 0.4);
Page.AddFileAttachment(AnnotRect, EmbeddedFile, FileAttachIcon.Paperclip);
TextPosY -= 2 * LineSpacing;
AnnotFileAttachment FileText = new AnnotFileAttachment(EmbeddedFile, FileAttachIcon.NoIcon);
Contents.DrawTextWithAnnotation(Page, ArialNormal, 12.0, TextPosX, TextPosY, TextJustify.Center,
  DrawStyle.Underline, Color.Red, "File attachment (right click)", FileText);
复制代码

2.16  重新排序页面

  在PdfFileWriter追加新的网页页面列表的末尾。如果要将页面从当前位置移动到新位置,请使用以下方法。

Document.MovePage(Int32 SourceIndex, Int32 DestinationIndex);

2.17  PDF文档输出

  PdfFileWriter创建PDF文档。主类PdfDocument构造函数给你两个选择来保存文档。第一种选择是将PDF文件保存到磁盘文件。在这种情况下,你提供了一个文件名。在文件创建结束时调用PdfDocument.CreateFile。

  此方法将PDF写入文件并关闭文件。

// create main class
PdfDocument Document = new PdfDocument(PaperType.Letter, false, UnitOfMeasure.Inch, FileName);

// terminate
Document.CreateFile();

  第二个选择是流。您创建一个流,内存流或文件流,并将该流作为参数传递给PdfDocument构造函数。执行CreateFile方法后,您的流包含PDF文档。根据应用程序,从流中提取文档。您必须在应用程序中关闭流。

复制代码
// create memory stream
MemoryStream PdfStream = new MemoryStream();

// create main class
PdfDocument Document = new PdfDocument(PaperType.Letter, false, UnitOfMeasure.Inch, PdfStream);

// terminate
Document.CreateFile();

// save the memory stream to a file
FileStream FS = new FileStream(FileName, FileMode.Create);
PdfStream.WriteTo(FS);
PdfStream.Close();
FS.Close();
复制代码

2.18  文档信息字典

  PDF文档信息字典由PDF阅读器在文档属性的“说明”选项卡中显示。信息包括:标题,作者,主题,关键字,创建的日期和时间,修改的日期和时间,生成文件的应用程序,PDF生成器。

  在应用程序中包含文档信息的步骤如下:

PdfInfo Info = new PdfInfo(Document);
Info.Title("Article Example");
Info.Author("Uzi Granot Granotech Limited");
Info.Keywords("PDF, .NET, C#, Library, Document Creator");
Info.Subject("PDF File Writer C# Class Library (Version 1.15.0)");

  PdfInfo对象被创建,四个额外的字段被添加到词典中。您可以在代码中覆盖所有这些。

复制代码
// set creation and modify dates
DateTime LocalTime = DateTime.Now;
Info.CreationDate(LocalTime);
Info.ModDate(LocalTime);

// set creator and producer
Info.Creator("PdfFileWriter C# Class Library Version " + PdfDocument.RevisionNumber);
Info.Producer("PdfFileWriter C# Class Library Version " + PdfDocument.RevisionNumber);
复制代码

2.19  内存控制

  在构建文档时,PDF文件编写器会累积创建PDF文件所需的所有信息。信息保存在内存中,除了图像和嵌入文件。图像和嵌入文件在声明时会自动写入输出文件。对于非常大的文档,使用的内存不断增长。库提供方法(CommitToPdfFile)将内容信息写入输出文件,并调用垃圾收集器释放未使用的内存。GC.Collect方法需要时间来执行。如果执行时间是问题,请GCCollect每几页设置一次参数。换句话说,CommitToPdfFile必须针对每个页面运行,但每几页清理一次。执行提交后,不能添加其他信息。PdfTable 当下一行不能容纳在当前页面的底部时自动启动新页面。PdfTable班有两个成员CommitToPdfFile,并CommitGCCollectFreq同时表被构建以控制内存的使用情况。PdfChart类生成从.NET类图的图像。DrawChart方法PdfContents将执行提交。或者,您可以调用的CommitToPdfFile方法PdfChart

// PdfContents, PdfXObject and PdfTilingPattern
// Commit the contents to output file.
// Once committed, this PdfContents cannot be used.
// The argument is GCCollect
Contents.CommitToPdfFile(true); 

2.20  Windows Presentation Foundation WPF

  绘制WPF图形是一个四个步骤的过程。

  • 步骤1:创建DrawWPFPath对象。输入参数是路径和Y轴方向。
  • 步骤2:可选择通过调用七种SetBrush方法之一或调用UseCurrentBrush方法添加画笔
  • 步骤3:可选择通过调用两种SetPen方法之一或调用UseCurrentPen方法添加笔
  • 步骤4:通过调用绘制图形对象PdfContents.DrawWPFPath

  如果System.Windows.Media引用不可用(即您的应用程序是Windows窗体),则需要向应用程序添加PresentationCoreWindowsBase程序集。

  Example8 OtherExample.cs和Example8f 中给出了使用WPF图形类绘制的编程示例

  如果未定义画笔和笔,则绘制图形将作为剪辑路径。

  下面你会发现更多的细节如何使用DrawWPFPath类WPF应用程序和其他应用程序。

  DrawWPFPath构造函数接受两个参数:路径和Y轴方向。路径是字符串或System.Windows.Media.PathGeometry文本字符串在路径标记语法中定义路径几何类在PathGeometry类中进行了描述当为WPF环境定义路径时,Y轴方向为向下。Y轴适用于PDF环境。

注意世界任何地方的程序员使用除了句点之外的数字小数分隔符。表示路径的文本字符串输入必须完全按照路径标记语法中的定义来构造。具有分数的小数必须使用周期,而不考虑世界区域。如果在x和y值之间使用可选分隔符,它必须是逗号。如果字符串是由另一个应用程序生成的,请确保使用PathGeometry.ToString(System.Globalization.CultureInfo.InvariantCulture)调用PathGeometry ToString。换句话说,Microsoft的PathGeometry.Parse方法将无法读取意大利产生的文本字符串,例如,通过PathGeometry.ToString方法,而不将IFormatProvider设置为InvariantCulture

有三种方法来为WPF应用程序定义画刷。所有这些方法将同时设置画笔不透明度。

  • System.Windows.Media.SolidColorBrush 请参阅SolidColorBrush类
  • System.Windows.Media.LinearGradientBrush请参阅LinearGradientBrush类
  • System.Windows.Media.RadialGradientBrush请参阅RadialGradientBrush类

有五种方法为所有应用程序定义画笔。所有这些方法将同时设置画笔不透明度。

  • 将画笔设置为System.Drawing.Color
  • 将画笔设置为 PdfAxialShading
  • 将画笔设置为 PdfRadialShading
  • 将画笔设置为 PdfTilingPattern
  • 将画笔设置为 UseCurrentBrush

如果你想让DrawWPFPath类将画笔设置为当前选择的画笔,调用UseCurrentBrush方法。

有一种方法为WPF应用程序定义笔。调用SetPen方法与System.Windows.Media.Pen类(请参阅 Pen)。注意,Pen.Brush属性必须是SolidColorBrush笔类包含绘制线所需的所有信息,例如颜色和宽度。

有一种方法为所有应用程序定义笔。调用SetPenSystem.Drawing.Color参数。color参数定义了alpha,红,绿和蓝色分量。要设置其他笔特性,请设置以下任何或全部属性和方法:

  • SetPenWidth
  • DashArray
  • DashPhase
  • LineCap
  • LineJoin
  • MiterLimit

如果您希望DrawWPFPath类将笔设置为当前选择的笔调用UseCurrentPen方法。

一旦DrawWPFPath类设置了绘制路径所需的所有信息,调用PdfContents.DrawWPFPath方法。DrawWPFPath类基于路径边界框和绘制矩形和对齐,计算将输入路径转换为绘图矩形所需的变换矩阵。对齐零(默认值)将拉伸路径以适合绘图区域。所有其他对齐值根据参数枚举值在绘图区域中定位路径。

复制代码
public void DrawWPFPath(
    DrawWPFPath Path,   // path to be drawn
    double OriginX,     // Drawing rectangle in user units left side
    double OriginY,     // Drawing rectangle in user units bottom side
    double Width,       // Drawing rectangle in user units width
    double Height,      // Drawing rectangle in user units height
                            // path alignment within drawing rectangle
                            // Alignment=0 means the path will be stretched 
                            // in either horizontal or vertical direction
                            // to fit the drawing rectangle
    ContentAlignment Alignment = 0)
复制代码

2.21  透明度,不透明度,Alpha颜色成分和混合

  默认情况下,PDF成像模型会将对象(形状,线条,文本和图像)不透明地绘制到页面上。每个新对象完全掩盖了它下面的图像。PDF有两种机制来改变这种行为不透明度和混合。图形状态字典具有用于描边(笔)和非描边(刷)操作的不透明度值。完全不透明的不透明度值为1.0,完全透明度为0.0。不透明度值对应于颜色结构的α分量,使得1.0为255,α为0。如果不透明度值为0.5,则在页面上绘制的新对象将是50%透明的。要设置不透明度,请调用SetAlphaStroking线或SetAlphaNonStroking 方法的形状的方法。混合是将页面上的颜色与正在绘制的新项目的颜色组合的过程。要设置一个bland模式调用的SetBlendMode方法PdfContents 参数是BlendMode枚举。有关详细说明,请参阅PDF规格文档的7.2.4混合模式。例如,请参见OtherExample.cs第8页。

2.22  文档链接和命名目标

  文档链接允许PDF文档用户单击链接并跳转到文档的另一部分。添加文档链接分为两部分。目标定义为位置标记。位置标记必须具有唯一的名称,范围(LocalDestNamedDest)和文档位置(页面和位置)。NamedDest 范围可用于文档链接或命名目标或两者。第二部分是链接位置。这两个部分可以按任何顺序定义。他们被绑在一起的名字。名称区分大小写。许多链接可以指向同一位置标记。

  命名目标是PDF文档中的目标。它们使用位置标记以与文档链接相同的方式定义。范围必须设置为NamedDest当诸如Adobe Acrobat的PDF阅读器打开PDF文档时,它可以在查看窗口中显示目标时打开文档。

要嵌入位置标记,调用的AddLocationMarker方法PdfPage注意:名称区分大小写。

复制代码
// Add location marker to the document (PdfPage method)
public void AddLocationMarker
  (
  string          LocMarkerName, // unique destination name (case sensitive)
  LocMarkerScope  Scope,         // eigther LocalDest or NamedDest
  DestFit         FitArg,        // fit argument (see below)
  params double[] SideArg        // 0, 1 or 4 side dimension argument (see below)
  )
复制代码

  添加链接位置调用PdfPage的AddLinkLocation方法。

public PdfAnnotation AddLinkAction
  (
  string LocMarkerName,    // location marker name
  PdfRectangle AnnotRect   // rectangle area on the page to activate the jump
  )

  有关命名目的地的详细信息,请参阅Adobe PDF文件规范“PDF参考,第六版,Adobe便携式文档格式版本1.7,2006年11月”第582页的表8.2。

  • DestFit.Fit (无参数):显示页面,其内容放大刚好足以适合水平和垂直窗口内的整个页面。
  • DestFit.FitH (1 arg Top):显示页面,垂直坐标顶部位于窗口的顶部边缘,并且页面的内容放大刚好足以适合窗口内页面的整个宽度。
  • DestFit.FitV (1 arg Left):显示页面,水平坐标左边位于窗口的左边缘,页面的内容放大刚好足以适合窗口内页面的整个高度。
  • DestFit.FitR (4 args Left Bottom Right Top):显示页面,其内容被放大,刚好足以适合由水平和垂直方向的窗口内的左,右,底和坐标指定的矩形。
  • DestFit.FitB (无参数):显示页面,其内容放大刚刚足以适合水平和垂直的窗口内的整个边界框。
  • DestFit.FitBH (1 arg Top):显示页面,垂直坐标顶部位于窗口的顶部边缘,页面的内容放大刚好足以适合窗口内边界框的整个宽度。
  • DestFit.FitBV (1 arg Left):显示页面,水平坐标左边位于窗口的左边缘,页面的内容放大刚好足以适合窗口内其边界框的整个高度。

  PDF阅读器的调用参数在Adobe的“打开PDF文件的参数”中定义如果PDF在台式计算机上打开,呼叫线路必须是:

  “path \ AcroRd32.exe”/ A“nameddest = ChapterXX”“path \ Document.pdf”

  如果PDF文档由网页中的链接指向,则目标将附加到链接:

  <a href="http://example.org/Document.pdf#ChapterXX">目标说明</a>

  或者:<a href="http://example.org/Document.pdf#namedsest=ChapterXX">目标说明</a>

2.23  安装

  集成PdfFileWriter到您的应用程序需要以下步骤。PdfFileWriter.dll在开发区域中安装附加文件。启动Visual C#程序并打开您的应用程序。转到解决方案资源管理器,右键单击引用,然后选择添加引用。

  选择“浏览”选项卡,并将文件系统导航到的位置PdfFileWriter.dll当您的应用程序发布时,必须包含代码> PdfFileWriter.dll。

  源代码文档作为帮助文件提供PdfFileWriter.chm 该文件由Sandcastle生成。结果看起来像Microsoft文档页。

  如果要访问PdfFileWriter项目的源代码,请PdfFileWriter在开发区域中安装项目。PdfFileWriter.dll会在PdfFileWriter\bin\Release目录中。

  使用此库将以下语句添加到所有源模块。

  using PdfFileWriter;

如果您打算使用图表,您需要添加引用:System.Windows.Forms.Visualization在每个源模块使用Chart你需要添加

  using System.Windows.Forms.DataVisualization.Charting; 

3  实例开发指南

  本节介绍PDF文件编写器C#类库到您的应用程序的集成。测试程序TestPdfFileWriter程序是对自己的应用程序的模拟。当按下“文章示例”按钮时,程序将执行ArticleExample.cs源文件中的代码上图显示了生成的PDF文件。此方法演示了如何创建一个包含一些文本和图形的页面文档。通过这个例子,你应该有一个很好的了解的过程。其他示例按钮生成各种PDF文档。总的来说,实际上这个库的每个特征都通过这些实施例来证明。

  调试复选框(如果选中)将创建一个PDF文件,可以使用文本编辑器查看,但无法加载到PDF阅读器。生成的文件未压缩,图像和字体文件将替换为文本占位符。调试复选框应仅用于调试。

  TestPdfFileWriter程序是使用Microsoft Visual C#2012开发的。它已针对Windows XP,Vista,7和8进行了测试。

 

3.1  文档创建概述

  下面的测试方法演示了创建PDF文件的介绍中描述的六个步骤。当您按下演示程序的“文章示例”按钮时,将执行该方法。以下小节详细描述每个步骤。

 

复制代码
/// Create “article example” test PDF document
public void Test(Boolean Debug, String FileName)
{
// Step 1: Create empty document
// Arguments: page width: 8.5”, page height: 11”, Unit of measure: inches
// Return value: PdfDocument main class
Document = new PdfDocument(PaperType.Letter, false, UnitOfMeasure.Inch, FileName);

// for encryption test
// Document.SetEncryption(Permission.All & ~Permission.Print);

// Debug property
// By default it is set to false. Use it for debugging only.
// If this flag is set, PDF objects will not be compressed, font and images will be replaced
// by text place holder. You can view the file with a text editor but you cannot open it with PDF reader.
Document.Debug = Debug;

// Step 2: create resources
// define font resources
DefineFontResources();

// define tiling pattern resources
DefineTilingPatternResource();

// Step 3: Add new page
Page = new PdfPage(Document);

// Step 4:Add contents to page
Contents = new PdfContents(Page);

// Step 5: add graphics and text contents to the contents object
DrawFrameAndBackgroundWaterMark();
DrawTwoLinesOfHeading();
DrawHappyFace();
DrawBarcode();
DrawBrickPattern();
DrawImage();
DrawHeart();
DrawChart();
DrawTextBox();
DrawBookOrderForm();

// Step 6: create pdf file
// argument: PDF file name
Document.CreateFile();

// start default PDF reader and display the file
Process Proc = new Process();
Proc.StartInfo = new ProcessStartInfo(FileName);
Proc.Start();

// exit
return;
}
复制代码

3.2  字体资源

  该DefineFontResources方法创建此示例中使用的所有字体资源。要查看可用于任何字体的所有字符,请按“字体家庭”按钮。选择一个族并查看为每个字符定义的字形。要查看单个字形按下视图或双击。

 

复制代码
// Define Font Resources
private void DefineFontResources()
{
// Define font resources
// Arguments: PdfDocument class, font family name, font style, embed flag
// Font style (must be: Regular, Bold, Italic or Bold | Italic) All other styles are invalid.
// Embed font. If true, the font file will be embedded in the PDF file.
// If false, the font will not be embedded
String FontName1 = "Arial";
String FontName2 = "Times New Roman";

ArialNormal = PdfFont.CreatePdfFont(Document, FontName1, FontStyle.Regular, true);
ArialBold = PdfFont.CreatePdfFont(Document, FontName1, FontStyle.Bold, true);
ArialItalic = PdfFont.CreatePdfFont(Document, FontName1, FontStyle.Italic, true);
ArialBoldItalic = PdfFont.CreatePdfFont(Document, FontName1, FontStyle.Bold | FontStyle.Italic, true);
TimesNormal = PdfFont.CreatePdfFont(Document, FontName2, FontStyle.Regular, true);
Comic = PdfFont.CreatePdfFont(Document, "Comic Sans MS", FontStyle.Bold, true);
return;
}
复制代码

3.3  平铺模式资源

  该DefineTilingPatternResource方法为示例区域定义背景图案资源。模式是在浅蓝色背景白色的单词“PdfFileWriter”。该模式由两行重复关键字组成。这两条线偏移半字长度。

  如果你想找到有趣的模式,在互联网上搜索公司的目录制作floor或wall tiles

复制代码
//// Define Tiling Pattern Resource
private void DefineTilingPatternResource()
{
// create empty tiling pattern
WaterMark = new PdfTilingPattern(Document);

// the pattern will be PdfFileWriter layed out in brick pattern
String Mark = "PdfFileWriter";

// text width and height for Arial bold size 18 points
Double FontSize = 18.0;
Double TextWidth = ArialBold.TextWidth(FontSize, Mark);
Double TextHeight = ArialBold.LineSpacing(FontSize);

// text base line
      



  
相关教程