zoukankan      html  css  js  c++  java
  • PDF文件编写者c#类库(版本1.26.0)

    1. 介绍 PDF文件编写器c#类库PdfFileWriter允许您直接从。net应用程序创建PDF文件。这个库使您无法了解PDF文件结构的细节。要使用该库,您需要添加一个对附加的pdffilewritl .dll类库文件的引用,在使用该库并将pdffilewritl .dll包含在您的发行版中的每个源文件中添加一个using PdfFileWriter语句。详情见第4页。安装。代码使用。net Framework 4.6.2和Visual Studio 2019开发。 版本1.26.0增强:支持PDF XMP元数据和支持二维码ECI授权号。 PDF文件编写者c#类库支持以下PDF文档的功能: 图形:绘制线,矩形,多边形,贝塞尔曲线,前景和背景色,模式和阴影。第2.1节坐标系。十进制分隔符注意,世界区域的用户使用逗号表示分数。参见2.2节十进制分隔符。绘制文本。语言支持,字体和字符集。绘图图像:绘制光栅(位图)图像和矢量(元文件)图像。2.4节。图像的支持。条码:支持条码128、条码39、条码交叉2 5、条码EAN13、条码UPC-A。条码支持。二维码:支持二维条码。二维码支持。PDF417条码。第2.7节PDF417条码网络链接:网络链接交互式支持。第2.8节Web链接支持。书签:支持文档大纲。章节2.9书签支持。图表:支持微软的图表。第2.10节图表支持。打印成PDF:从打印文档过程创建PDF文档。第2.11节PrintDocument支持。显示数据表。第2.12节数据表支持播放视频文件。第2.13节播放视频文件播放声音文件。第2.14节播放声音文件附加数据文件。第2.15节附加数据文件重新排序页。第2.16节重新排序页pdf文档输出到一个文件或流。第2.17节PDF文件输出。PDF文档信息字典。PDF阅读器在文档属性的Description选项卡中显示此信息。这些信息包括:标题、作者、主题、关键字、创建的日期和时间、修改的日期和时间、生成文件的应用程序、PDF生成器。第2.18节文档信息词典。内存控制:将已完成页面的内容信息写入输出文件,使用垃圾收集器释放未使用的内存。2.19节。内存控制。绘制由System.Windows.Media定义的美术作品。PathGeometry类。输入参数可以是文本字符串或PathGeometry类。透明或不透明可用于绘制形状、线条、文本和图像。你的应用程序可以为所有的图形和文字设置颜色的alpha组件。Section 2.21透明度,不透明度,阿尔法颜色组件和混合混合。该库支持PDF的颜色混合方案。混合定义如何处理涂在前一项上的新项的颜色。Section 2.21透明度,不透明度,阿尔法颜色组件和混合文件链接和命名的目的地。第2.22节文档链接和指定目的地。加密:支持AES-128加密。第2.23节加密支持。便利贴或文本注释。层或可选内容。2.25层或可选内容。最初的文件显示。2.26初始文件显示。XMP元数据。2.27 XMP元数据。 创建PDF需要六个步骤。 步骤1:创建一个文档对象PdfDocument。步骤2:创建资源对象,如字体或图像(即PdfFont或PdfImage)。步骤3:创建页面对象PdfPage。步骤4:创建内容对象PdfContents。步骤5:向contents对象添加文本和图形(使用PdfContents方法)。步骤6:通过调用PdfDocument的CreateFile方法创建PDF文档文件。 第5步是你大部分编程工作要花费的地方。添加内容是通过调用PdfContents类的方法来呈现图形和文本来实现的。contents类有一组丰富的方法(大约100个)用于向文档中添加文本和图形。 PdfDocument实现了IDisposable接口来释放非托管资源。创建PDF文件后,CreateFile方法调用Document.Dispose()。但是,为了确保资源的释放,您应该用using语句或try/catch块/p>包装PdfDocument创建和最终的CreateFile; 本文附带的演示程序是为调试库而开发的测试程序。TestPdfFileWriter在主屏幕上有六个按钮。五个按钮用于生成PDF文件示例,一个按钮用于显示计算机上可用的所有字体。第一个按钮“Article Example”创建了显示在顶部的PDF文件篇文章。第三节。实例开发指南。 如前所述,PdfFileWriter c#类库使您免受PDF文件结构的复杂性的影响。然而,良好的理解PDF文件总是一个优势。adobepdf文件规范文件可从Adobe网站下载:" PDF参考第六版,adobeportable document Format Version 1.7 2006年11月"。这是一份令人生畏的1310页的文件。我强烈建议阅读第4章图形和第5章正文中的第5.2和5.3节。 如果你想分析这个项目创建的PDF文件,或者你想了解PDF文件的一般结构,你可以使用我上一篇文章“PDF文件分析器与c#解析类”附带的演示程序。本文提供了PDF规范的简明概述。 2. PDF文件编写者库一般说明 2.1。坐标系和测量单位 PDF坐标系的原点在页面的左下角。x轴是向右的。y轴是向上的。 PDF的度量单位是点。一英寸有72个点。PDF文件编写器允许您选择自己的度量单位。所有表示位置、宽度或高度的方法参数都必须使用度量单位。有两个例外:字体大小和分辨率。字体大小总是以点为单位。分辨率总是以像素/英寸为单位。PDF文件编写器将所有输入参数转换为点。所有内部测量值和计算均采用双精度。在创建PDF文件的最后一步,将值转换为文本字符串。转换精度为六位数。换算公式为: 隐藏,复制Code

    // Value is Double
    if(Math.Abs(Value) < 0.0001) Value = 0.0;
    String Result = ((Single) Value).ToString();

    2.2。十进制分隔符 PDF阅读器(如adobeacrobat)希望使用带有分数的实数作为十进制分隔符。世界上有些地区使用其他十进制分隔符,如逗号。因为版本1.1的PDF文件编写器库将使用句点作为十进制分隔符,而与您的计算机的区域设置无关。 2.3。语言支持,字体和字符集 PDF文件编写器库支持安装在计算机上的大多数字体。唯一的例外是设备字体。受支持的字体遵循OpenType字体规范。更多信息可在Microsoft Typography - OpenType规范中获得。要绘制的文本存储在Unicode字符组成的字符串中。库将接受除控制码0到31和128到159之外的任何字符(0到65536)。每个字符都被翻译成字形。在页面上从左到右绘制符号的顺序与它们在字符串中存储的顺序相同。大多数字体文件只支持所有可能的Unicode字符的子集。换句话说,您必须选择一种字体来支持您的项目的语言或您试图显示的符号。如果输入字符串包含不受支持的符号,PDF阅读器将显示“未定义符号”。通常它是一个小矩形。本文附带的测试程序有一个“字体家族”按钮。如果你点击它,你可以看到你的计算机上所有可用的字体和在每种字体内所有可用的字符。如果项目的语言是从左到右的语言,并且每个字符被翻译成一种字形,字形在字体中定义,那么结果应该是您所期望的。如果结果不是你所期望的,这里有一些额外的注意事项: Unicode控制字符。Unicode控制字符用于控制文本的解释或显示,但这些字符本身没有视觉或空间表示。PDF文件编写器不能识别这些字符。库假设每个字符都是一个显示字符。它们将以未定义字符的形式显示。 从右到左的语言。通常,文本字符串中字符的顺序就是人们读取它们的顺序。由于库从左到右绘制,因此文本将向后书写。ReverseString方法反转字符顺序。如果文本仅由从右到左的字符组成,这将解决问题。如果文本由右到左、从左到右、数字和一些字符(如方括号()[]<>{})混合而成,则不会产生所需的结果。另一个限制是TextBox类不能将从右到左的长文本分割成行。 结扎。在某些语言中,将两个或多个字符组合在一起以显示一个字形。您的软件可以识别这些序列,并用适当的符号替换它们。 虚线圆。如果您查看字形度量屏幕的字形列,您可以看到一些字形有一个小的虚线圆(即字符代码2364和2367)。这些字符是字符序列的一部分。虚线圆不显示。如果前进宽度为零,并且边界框位于Y轴的左侧,则绘制该符号将是ok的。它将被显示为on在前一个字符的顶部。如果前进宽度不为零,则该符号应显示在前一个字符之前。您的软件可以通过颠倒这两个字符来实现。 2.4。形象支持 在PDF文档中显示图像是由PdfImage类处理的。这个类是一个PDF资源。图像来源可以是: 。net Image file . net Image派生类如bitmap一个黑白像素布尔数组qrcode条形码由QREncoder类pdf 417表示的条形码由Pdf417Encoder类pdfchart是PdfImage的派生类,pdfprintdocument是使用内部的PdfImage来捕获打印页面的 图像以下列其中一种格式保存为PDF文件: Jpeg格式索引位图(无损压缩)灰度位图(无损压缩)黑白位图(无损压缩) 彩色图片应保存为Jpeg格式。要控制图像的大小,可以降低分辨率或改变图像质量。彩色图片可以保存为灰色阴影。数据的大小被削减了3,但是你失去了颜色。如果图像像图表一样以编程方式创建,并且颜色的数目小于256,则图像可以保存为索引位图。每种颜色用一个字节(或更少)表示,而用3个字节表示。这将导致文件大小的显著减小。例如,ChartExample.pdf文件从642KB减少到72KB。如果图像是黑白的,如在PdfPrintDocument图像的文本,该图像可以保存为BWImage。在PrintExample.pdf中,Jpeg文件是1795KB,黑白版本是66KB。 添加图像到您的PDF文件 创建一个PdfImage类。 隐藏,复制Code

    // create PdfImage object
    PdfImage MyImage = new PdfImage(Document);

    如果需要设置可选参数。所有参数都有一个默认值。 隐藏,收缩,复制Code

    // saved image format (default SaveImageAs.Jpeg)
    // other choices are: IndexedImage, GrayImage, BWImage
    MyImage.SaveAs = SaveImageAs.Jpeg;
    
    // Crop rectangle is the image area to be cropped.
    // The default is no crop (empty rectangle).
    // The origin is at top left and Y axis is pointing down.
    // The dimensions are in pixels.
    // The crop rectangle must be contained within the image.
    MyImage.CropRec = new Rectangle(x, y, width, height);
    
    // Crop percent rectangle is the image area to be cropped.
    // The default is no crop (empty rectangle).
    // The origin is at top left and Y axis is pointing down.
    // The dimensions are in percent of image.
    // The crop rectangle must be contained within the image.
    MyImage.CropPercent = new RectangleF(x, y, width, height);
    
    // Image Quality is an integer in the range of 0 to 100.
    // representing poor to best quality image.
    // The default (-1) is save image with Bitmap default quality.
    // For your information Bitmap class default image quality is 75.
    // Lower image quality means smaller PDF file.
    MyImage.ImageQuality = PdfImage.DefaultQuality;
    
    // Image resolution sets the image resolution provided
    // that it is smaller than the resolution of source image.
    // Default of 0, is keeping the original image resolution.
    // Resolution is specified in pixels per inch.
    // Reduced resolution means smaller PDF file.
    MyImage.Resolution = 0;
    
    // Cutoff value for gray conversion to black and white.
    // The range is 1 to 99. The default is 50.
    // If shade of gray is below cutoff, the result is black.
    // If shade of gray is above cutoff, the result is white.
    MyImage.GrayToBWCutoff = 50;
    
    // Reverse black and white
    // Default is false
    // In Gray or BW images the color is reversed
    MyImage.ReverseBW = false;
    
    // Attach to layer control
    // Image visibility will be controlled by viewer application.
    MyImage.LayerControl = PdfLayer;

    加载图像到PdfImage对象。注意:加载方法将图像保存在PDF输出文件中。完成此步骤后,就不能更改映像。 隐藏,复制Code

    // use one of 5 methods to load the image.
    // image source can be a file, Bitmap,
    // BW bool array, QRCode or Pdf417 barcode
    MyImage.LoadImage(image_source);

    绘制图像到PDF文档。 隐藏,复制Code

    // draw the image
    Contents.DrawImage(MyImage, PosX, PosY, Width, Height);

    如果您希望图像保持正确的纵横比,请使用ImageSize或ImageSizePosition来计算宽度和高度。如果宽度和高度的比率与图像不一样,图像看起来会在其中一个方向上被拉伸。 隐藏,复制Code

    // calculate the largest rectangle with the correct
    // aspect ratio 
    SizeD MyImage.ImageSize(Double Width, Double Height);

    隐藏,复制Code

    // calculate the largest rectangle with
    // correct aspect ratio that will fit in a given area and
    // position. It based on <code>ContentAlignment</code> enumeration.
    ImageSizePos ImageSizePosition(Double Width, Double Height, ContentAlignment Alignment);

    2.5。条形码的支持 下面的代码演示了如何在PDF文档中包含UPC-A条形码。 隐藏,复制Code

    // create barcode object
    BarcodeEAN13 Barcode = new BarcodeEAN13("123456789010");
    
    // draw the barcode including text under the barcode
    Contents.DrawBarcode(PosX, PosY, BarWidth, BarcodeHeight, Barcode, Font, FontSize);

    在本例中,该类是BarcodeEAN13,具有12位输入字符串。其结果就是UPC-A条形码。 PDF文件编写器库包括基类条形码。对于每个支持的条形码,都需要一个派生类。类库包括四个派生类:Barcode128、Barcode39、BarcodeInterleaved2of5和BarcodeEAN13。如果输入字符串是13位数字,BarcodeEAN13将生成EAN-13条码;如果输入字符串是12位数字,则生成UPC-A条码。具有13位数字和前导零的输入字符串被认为是UPC-A。 DrawBarcode方法有许多重载。您可以指定条形码左下角的位置、窄条的宽度、条形码的高度和派生的条形码类。有一些可选的参数:显示文本的对齐(左、中、右)、颜色和字体。条码周围的安静区是你的责任。可选文本显示在条形码下方。如果你选择的颜色不是黑色,你应该确保与背景的对比是显著的。用法示例在3.7绘制条形码,ArticleExample.cs和OtherExample.cs中给出。 如果希望为另一个条形码创建派生类,请使用包含的三个类的源代码作为示例。 2.6。二维码的支持 PDF文件编写器库提供了对二维码的支持。它是基于article QR Code Encoder and Decoder . net(框架、标准、核心)类库,用c#编写的。该程序支持三种字符集:数字、字母数字和八位字节。该程序不支持汉字字符。该程序将扫描输入的数据字符串,并选择最有效的字符集。如果您的数据可以被分割成只有数字或只有字母数字字符的片段,您可以创建一个带有数据字符串数组的二维码对象。 在PDF文档中添加QRCode条形码必须遵循以下步骤。 创建QREncoder对象。设置编码选项。所有编码选项都有默认值。对数据字符串或数据字节数组进行编码。创建PdfImage。用PdfContent.DrawImage绘制条形码图像 QR代码示例 隐藏,复制Code

    // create QRCode barcode
    QREncoder QREncoder = new QREncoder();
    
    // set error correction code (default is M)
    QREncoder.ErrorCorrection = ErrorCorrection.M;
    
    // set module size in pixels (default is 2)
    QREncoder.ModuleSize = 1;
    
    // set quiet zone in pixels (default is 8)
    QREncoder.QuietZone = 4;
    
    // ECI Assignment Value (default is -1 not used)
    // The ECI value is a number in the range of 0 to 999999.
    // or -1 if it is not used
    Encoder.ECIAssignValue = -1;
    
    // encode your text or byte array
    QREncoder.Encode(ArticleLink);
    
    // convert QRCode to PdfImage in black and white
    PdfImage BarcodeImage = new PdfImage(Document, QREncoder);
    
    // draw image (height is the same as width for QRCode)
    Contents.DrawImage(BarcodeImage, 6.0, 6.8, 1.2);

    编码示例请回顾3.7绘制条形码,ArticleExample.cs和OtherExample.cs源代码。 2.7。PDF417条码 PDF417条码支持软件基于文章PDF417 barcode Encoder类库和Demo App。PDF417条码文档和规范可以在以下网站找到。Wikipedia为PDF417提供了一个很好的介绍。点击这里进入该页面。PDF417标准可在本网站向ISO组织购买。该规范的早期版本可以从这个网站免费下载。如果你想完全理解编码选项,我强烈建议你下载这个文档。 PDF417条形码将字节数组编码为黑白条的图像。编码Unicode文本需要将Unicode字符转换为字节。译码器必须做相反的过程来恢复文本。字节被转换成码字。这个转换过程将字节压缩成码字。编码器添加用于错误检测和恢复的错误纠正码字。一旦知道了数据码字和纠错码字的总数,编码器将码字分为数据行和数据列。最后一步是创建一个黑白图像。 在PDF文档中添加PDF417条形码必须遵循以下步骤。 创建Pdf417Encoder对象。设置编码选项。所有编码选项都有默认值。对数据字符串或数据字节数组进行编码。检查图像的宽度和高度或数据列和数据行数,以确保图像大小适合您的应用程序。如果不是,调整布局。创建PdfImage。用PdfContent.DrawImage绘制条形码图像 PDF417条码绘制示例 隐藏,复制Code

    private void DrawPdf417Barcode()
    {
    // save graphics state
    Contents.SaveGraphicsState();
    
    // create PDF417 barcode
    Pdf417Encoder Pdf417 = new Pdf417Encoder();
    
    string ArticleLink = "http://www.codeproject.com/Articles/570682/PDF-File-Writer-Csharp-Class-Library-Version";
    
    // encode text 
    Pdf417.Encode(ArticleLink);
    Pdf417.WidthToHeightRatio(2.5);
    
    // convert Pdf417 to black and white image
    PdfImage BarcodeImage = new PdfImage(Document, Pdf417);
    
    // draw image
    Contents.DrawImage(BarcodeImage, 1.1, 5.2, 2.5);
    
    // restore graphics sate
    Contents.RestoreGraphicsState();
    return;
    }

    PDF417条码的对象 创建PDF417条形码对象。可以串行重用此对象以生成多个条形码。 隐藏,复制Code

    // create PDF417 barcode
    Pdf417Encoder Pdf417 = new Pdf417Encoder();

    设置可选参数来控制编码过程。 编码控制 PDF417编码器将输入字节编码为码字。有三种类型的代码字:字节、文本和数字。该程序有一个算法,将数据输入划分为这三种类型,以压缩数据。默认值是Auto。但是,您可以将编码限制为仅字节或仅文本和字节。 隐藏,复制Code

    Pdf417.EncodingControl = Pdf417EncodingControl.Auto;
    // or
    Pdf417.EncodingControl = Pdf417EncodingControl.ByteOnly;
    // or
    Pdf417.EncodingControl = Pdf417EncodingControl.TextAndByte;

    误差校正水平 PDF417添加了纠错码字来检测错误并纠正它们。纠错码字的增加提高了条码的可靠性。然而,它使条形码变大了。纠错级别允许您控制条码的质量。ErrorCorrectionLevel枚举有两种类型的值。固定水平从0到8。以及基于数据码字数量的推荐值的级别。error correctionlevel. autonnormal中的默认值。要了解更多细节,请参阅PDF417规范中的表6和表7。 隐藏,复制Code

    Pdf417.ErrorCorrection = ErrorCorrectionLevel.Level_0; // up to Level_8
    // or
    Pdf417.ErrorCorrection = ErrorCorrectionLevel.AutoNormal;
    // or
    Pdf417.ErrorCorrection = ErrorCorrectionLevel.AutoLow; // one less than normal
    // or
    Pdf417.ErrorCorrection = ErrorCorrectionLevel.AutoMedium; // one more than normal
    // or
    Pdf417.ErrorCorrection = ErrorCorrectionLevel.AutoHigh; // two more than normal

    窄条的宽度 窄条码条的像素宽度。默认值是2。如果更改了该值,程序将确保rowh8至少是该值的三倍。这个相当区域至少是这个值的两倍。 隐藏,复制Code

    Pdf417.NarrowBarWidth = value;

    行高 一行的高度(以像素为单位)。此值必须大于或等于窄宽度值的3倍。默认值是6。 隐藏,复制Code

    Pdf417.RowHeight = value;

    安静的区域 条码周围安静区域的宽度。安静区是白色的。此值必须大于或等于窄宽度值的2倍。默认值是4。 隐藏,复制Code

    Pdf417.QuietZone = value;

    默认的数据列 默认数据列值。该值的范围必须在1到30之间。默认值是3。输入数据编码后,软件将数据列数设置为默认数据列,并计算数据行数。如果数据行数超过允许的最大行数(90),则软件将行数设置为允许的最大行数,并重新计算数据列数。如果结果大于允许的最大列,则抛出异常。 隐藏,复制Code

    Pdf417.DefaultDataColumns = value;

    全局标签ID字符集 将全局标签ID字符集设置为ISO 8859标准。n可以是1到9 13或15。如果字符串为null,则使用默认的ISO-8859-1。这里定义了语言支持。 隐藏,复制Code

    Pdf417.GlobalLabelIDCharacterSet = "ISO-8859-n";

    全局标签ID用户定义 设置全局标签ID用户定义值。不使用默认值。我没有找到任何解释该值用法的参考资料。用户定义的值必须在810900到811799之间。 隐藏,复制Code

    Pdf417.GlobalLabelIDUserDefined = UserDefinedValue;

    通用标签ID 设置全局标签ID通用值。不使用默认值。我没有找到任何解释该值用法的参考资料。用户定义的值必须在900到810899之间。 隐藏,复制Code

    Pdf417.GlobalLabelIDGeneralPurpose = UserDefinedValue;

    编码数据 有两种编码方法。一个接受文本字符串作为输入,另一个接受字节数组作为输入。 隐藏,复制Code

    Pdf417.Encode(string StringData);
    // or
    Pdf417.Encode(byte[] BinaryData);

    条形码是为二进制数据设计的。因此,上面的第一个方法必须将字符串从16位字符编码为字节数组。具有字符串输入的encode方法具有以下转换逻辑。全局标签ID字符集属性控制转换。它分两步完成。步骤一个字符串到UTF8,步骤两个UTF8到ISO-8859-n。如果您想对希伯来语进行编码,您应该将字符集设置为ISO-8859-8。 隐藏,复制Code

    public void Encode(string StringData)
    {
    // convert string to UTF8 byte array
    byte[] UtfBytes = Encoding.UTF8.GetBytes(StringData);
    
    // convert UTF8 byte array to ISO-8859-n byte array
    Encoding ISO = Encoding.GetEncoding(_GlobalLabelIDCharacterSet ?? "ISO-8859-1");
    byte[] IsoBytes = Encoding.Convert(Encoding.UTF8, ISO, UtfBytes);
    
    // call the encode binary data method
    Encode(IsoBytes);
    Return;
    }

    最后一个条形码布局 在对数据进行编码之后,您可以通过检查这些值来检查条形码的布局:ImageWidth、ImageHeight、DataColumns或DataRows。如果要重新调整条码的宽度和高度,可以使用下面的方法之一。此外,您还可以重新调整可选参数:NarrowBarWidth、RowHeight或QuietZonevalues。 宽高比 此方法将计算数据行和数据列的数量,以实现所需的宽高比。这个比例包括安静区。检查返回值是否成功。 隐藏,复制Code

    Bool Pdf417.WidthToHeightRatio(double Ratio);

    设置数据列 该方法将根据所需的数据列数计算数据行数。检查返回值是否成功。 隐藏,复制Code

    Bool Pdf417.SetDataColumns(int Columns);

    设置数据行 该方法将根据所需的数据行数计算数据列的数量。检查返回值是否成功。 隐藏,复制Code

    Bool Pdf417.SetDataRows(int Rows);

    创建PDF文档图像资源 在这个步骤中,我们从PDF417条形码创建一个PDF文档图像资源。 隐藏,复制Code

    PdfImage BarcodeImage = new PdfImage(Document, Pdf417);

    画出条形码 最后一步是将条形码添加到PDF文档页面的内容中。 隐藏,复制Code

    // PosX and PosY are the page coordinates in user units.
    // Width is the width of the barcode in user units.
    // The height of the barcode is calculated to preserve aspect ratio.
    // Height = Width * BarcodeImage.ImageHeight / BarcodeImage.ImageWidth
    Contents.DrawImage(BarcodeImage, PosX, PosY, Width);

    2.8。网页链接的支持 PDF文件编写器库提供对web链接的支持。此功能是PDF参考手册第8节交互功能中描述的PDF交互功能之一。它是注释和行动的结合。注释将web链接与页面上的区域关联起来。当用户单击该区域时,PDF阅读器将激活缺省web浏览器,导航到所需的web页面。 注释区域是一个矩形区域,由相对于页面左下角的绝对坐标定义。要添加一个web链接,请调用PdfPage类的AddWebLink方法。 隐藏,复制Code

    Page.AddWebLink(Double LeftPos, Double BottomPos, Double RightPos, Double TopPos, String WebLink);

    注释不是页面内容的一部分。为了让您的PDF文档的读者知道在哪里单击,您需要在页面的同一区域显示适当的文本或图形。换句话说,您需要调用两个方法。与页面关联的AddWebLink方法和与内容关联的第二个方法。第二种方法可以是图形对象,如图像、矩形或文本。因为AddWebLink需要相对于页面左下角的坐标,所以图形对象的坐标必须是相同的。换句话说,不要使用平移、缩放或旋转。如果你这样做了,你需要确保这两个区域是重合的。 PDF文件编写器有几个支持文本注释的PdfContents方法。 画一行文字与相关的网页链接。文本将左对齐、下划线和蓝色。文本位置相对于页面的左下角。 隐藏,复制Code

    // font size in points
    PdfContents.DrawWebLink(PdfPage Page, PdfFont Font, Double FontSize,
    	Double TextAbsPosX, Double TextAbsPosY, String Text, String WebLink);

    画一行文字与相关的网页链接。文本位置相对于页面的左下角。 隐藏,复制Code

    // font size in points
    PdfContents.DrawWebLink(PdfPage Page, PdfFont Font, Double FontSize, Double TextAbsPosX, Double TextAbsPosY,
    	TextJustify Justify, DrawStyle DrawStyle, Color TextColor, String Text, String WebLink);

    在文本框内绘制web链接是一个两个步骤的过程。首先,使用TextBox类的一个AddText方法将文本和web链接字符串添加到框中。其次,使用PdfContents的DrawText方法之一将文本框绘制到页面内容。 添加web链接到文本框。文本将显示带下划线和蓝色。 隐藏,复制Code

    TextBox.AddText(PdfFont Font, Double FontSize, String Text, String WebLink);

    添加web链接到文本框。文本属性由DrawStyle和FontColor定义。 隐藏,复制Code

    TextBox.AddText(PdfFont Font, Double FontSize, DrawStyle DrawStyle, Color FontColor, String Text, String WebLink);

    第二步绘制文本到内容。此方法假定没有额外的行或段间距。注意,如果你在没有PdfPage参数的情况下调用带有WebLink信息的文本框中的DrawText, ApplicationException将被抛出。 隐藏,复制Code

    // note: PosYTop is by reference.
    // On exit from the method the PosYTop will have the next Y position
    PdfContents.DrawText(Double PosX, ref Double PosYTop, Double PosYBottom, Int32 LineNo, TextBox Box, PdfPage Page);

    此方法允许您定义额外的行或段落间距。注意,如果你在没有PdfPage参数的情况下调用带有WebLink信息的文本框中的DrawText, ApplicationException将被抛出。 隐藏,复制Code

    // note: PosYTop is by reference.
    // On exit from the method the PosYTop will have the next Y position
    PdfContents.DrawText(Double PosX, ref Double PosYTop, Double PosYBottom, Int32 LineNo,
    	Double LineExtraSpace, Double ParagraphExtraSpace, Boolean FitTextToWidth, TextBox Box, PdfPage Page);

    编写示例请查看3.4 Draw Frame, ArticleExample.cs和OtherExample.cs源代码。 2.9。书签支持 书签在PDF规范(章节8.2.2文档大纲)中有如下描述:“PDF文档可以在屏幕上选择性地显示文档大纲,允许用户交互地从文档的一部分导航到另一部分。大纲由大纲项目(有时称为书签)的树形结构层次结构组成,它们充当一个可视化的目录,向用户显示文档的结构。用户可以通过点击鼠标来交互地打开和关闭单个项目。” cs源代码中有一个书签的例子。在一个地方有三个层次。你可以看到结果在OtherExample.pdf文件中。 在应用程序中添加书签的第一步是: 隐藏,复制Code

    // set the program to display bookmarks
    // and get the bookmark root object
    PdfBookmark BookmarkRoot = Document.GetBookmarksRoot();

    此步骤激活文档中的书签并返回根节点。 添加书签类似于向windows窗体添加控件。第一级书签被添加到根目录中。将后续级别添加到现有书签。至少需要定义标题、页面、页面上的垂直位置和打开条目标志。Page是要去的页面的PdfPage对象。YPos是相对于页面左下角的垂直位置。如果较低级别的书签是可见的,打开条目标志为true,如果较低级别的书签是隐藏的,标志为false。默认情况下,第一级总是可见的。 隐藏,复制Code

    // hierarchy example
    PdfBookmark FirstLevel_1 = BookmarkRoot.AddBookmark("Chapter 1", Page, YPos, false);
    PdfBookmark SecondLevel_11 = FirstLevel_1.AddBookmark("Section 1.1", Page, YPos, false);
    PdfBookmark SecondLevel_12 = FirstLevel_1.AddBookmark("Section 1.2", Page, YPos, false);
    PdfBookmark ThirdLevel_121 = SecondLevel_12.AddBookmark("Section 1.2.1", Page, YPos, false);
    PdfBookmark ThirdLevel_122 = SecondLevel_12.AddBookmark("Section 1.2.2", Page, YPos, false);
    PdfBookmark SecondLevel_13 = FirstLevel_1.AddBookmark("Section 1.3", Page, YPos, false);
    PdfBookmark FirstLevel_2 = BookmarkRoot.AddBookmark("Chapter 2", Page, YPos, false);
    PdfBookmark SecondLevel_21 = FirstLevel_2.AddBookmark("Section 2.1", Page, YPos, false);
    PdfBookmark SecondLevel_22 = FirstLevel_2.AddBookmark("Section 2.2", Page, YPos, false);

    AddBookmark()方法有四种重载变体: 隐藏,收缩,复制Code

    // basic
    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
        )
    
    // title color and style
    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
        )
    
    // XPos and zoom
    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
        )
    
    // all options
    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)是第3个一级项的第4个二级项。 2.10。图表支持 PDF规范对图表没有特定的支持。PDF文件编写器库通过允许开发人员创建Microsoft制图对象并将该对象作为图像绘制到PDF文件中来提供绘图支持。有关Microsoft图表控件的更多信息请注意MSDN库文档Visual Studio 2012图表控件。图表名称空间的文档可以在数据可视化图表命名空间中找到。附上的ChartExample.cs有四个图表示例。如果您打算使用图表,您需要添加System.Windows.Forms。项目的可视化引用。在每个使用图表的源模块中,您需要添加使用system . windows . forms . datavisualize . charting;。 向PDF文档添加图表有四个步骤。 创建表对象。创建PdfChart对象。构建图表。绘制PdfChart to PdfContents。 推荐的创建图表的方法是使用PdfChart对象的静态方法。 隐藏,复制Code

    // Document is your PdfDocument object.
    // Width and height are in user units.
    // Resolution is in pixels per inch.
    // Resolution is optional. If not included the library will take the .net default.
    // Library will create Chart object with width and height in pixels and set resolution in pixels per inch
    Chart MyChart = PdfChart.CreateChart(PdfDocument Document, Double Width, Double Height, Double Resolution);

    您可以自己实例化图表类。 隐藏,复制Code

    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

    接下来,根据上面创建的图表创建一个PdfChart。您可以选择重写解析。 隐藏,复制Code

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

    接下来你建立你的图表。ChartExample.cs有四个例子。构建图表的文档超出了本文的范围。互联网上有很多这样的例子。 PdfChart有一个CreateFont方法来简化字体的创建。它将根据图表的分辨率计算字体大小。 隐藏,复制Code

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

    最后一步是绘制图表。 隐藏,复制Code

    // 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方法返回适合给定区域的具有正确长宽比的最大矩形。 隐藏,复制Code

    SizeD ImageSize(Double Width, Double Height);

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

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

    2.11。打印文档支持 打印文档支持允许您以与打印到打印机并生成PDF文档相同的方式打印报表。这种生成PDF文件的方法与使用PdfContents生成PDF文件的方法之间的区别就是光栅图形与矢量图形之间的区别。打印文档支持为每个页面创建一个jpeg图像。cs有一个创建三页文档的例子。 通常每个页面都是页面的完整图像。如果页面是字母大小,分辨率是每英寸300像素,每个像素是3字节,那么页面的位图将是25.245MB长。PrintPdfDocument有一个方法CropRect,它可以显著减少位映射的大小。假设使用了一英寸的裕度,位图的活动大小将减少到15.795 MB,即减少37.4%。 隐藏,收缩,复制Code

    // main program
    // Create empty document
    Document = new PdfDocument(PaperType.Letter, false, UnitOfMeasure.Inch);
    
    // create PrintPdfDocument producing an image with 300 pixels per inch
    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.
    Print.AddPagesToPdfDocument();
    
    // dispose of the PrintDocument object
    Print.Dispose();
    
    // create the PDF file
    Document.CreateFile(FileName);

    PrintPage方法的示例 隐藏,收缩,复制Code

    // Print each page of the document to PrintDocument class
    // You can use standard PrintDocument.PrintPage(...) method.
    // NOTE: The graphics origin is top left and Y axis is pointing down.
    // In other words, this is not PdfContents printing.
    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。数据表支持 数据表类允许您在PDF文档中显示数据表。PdfTable是控制表显示的主要类。表由头行和数据行组成。每行被划分为单元格。PdfTableCell控制一个标题单元格或一个数据单元格的显示。如果使用了header,它将显示在表的顶部。可选地,它将显示在每个附加页面的顶部。要在单元格中显示数据,需要将数据加载到PdfTableCell的Value属性中。数据可以是文本字符串,基本数值,布尔值,字符,文本框,图像,二维码或条形码。独立于数据,您可以加载带有文档链接、web链接、视频、音频或嵌入式的单元格文件。点击单元格区域内的任何地方,PDF阅读器都会激活文档链接、web链接、视频、音频或嵌入式文件。数据的显示由PdfTableStyle类控制。PdfTable类包含默认的单元格样式和默认的标题样式。您可以使用PdfTableCell中的私有样式覆盖默认样式。要显示表,需要创建一个PdfTable对象。接下来,初始化表、标题单元格、数据单元格和样式对象。最后,设置一个循环并加载一行的单元格值,然后绘制这一行。此循环将继续,直到显示所有数据为止。下面您将看到生成表所需的步骤序列。 当调用DrawRow方法时,软件计算所需的行高度。行高是最高单元格的高度。如果表中有足够的空间,就会绘制行。当底部的可用空间太小时,将调用一个新页面,并在表的顶部显示可选的标题和当前行。如果所需的行高度太大,无法装入完整的空表,则会引发异常。为了适应长多行字符串或文本框,软件可以灵活地处理这些情况。多行字符串被PdfTable转换为一个文本框。PdfTableStyle类有一个TextBoxPageBreakLines属性。如果该属性设置为零(默认值),文本框将被视为其他数据值。文本框的高度必须适合页面。如果TextBoxPageBreakLines被设置为正整数,系统将计算单元格的高度作为文本框的高度或由TextBoxPageBreakLines指定的前几行高度。系统将绘制与页面大小相同的行。将创建一个新页面,并绘制其余的线条。换句话说,一个长文本框的第一个行块至少是TextBoxPageBreakLines长。cs源包含一个长文本框单元格的例子。 创建一个PdfTable对象。 隐藏,复制Code

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

    页面是当前的PdfPage。内容是当前的PdfContents。字体是表格的默认字体。FontSize是默认的字体大小,以点为单位。 在页面上定义表的区域。 隐藏,复制Code

    // table's area on the page
    Table.TableArea = new PdfRectangle(Left, Bottom, Right, Top);
    
    // first page starting vertical position
    Table.RowTopPosition = StartingTopPosition;

    这四个参数是相对于左下角和用户单位的表的四个边。如果在首页,桌面位置不在页面顶部,则将RowTopPosition设置为起始顶部位置。在随后的页面中,该表总是从顶部开始。如果没有指定TableArea,库会将其设置为小于一英寸边距的默认页面大小。 将表宽度划分为列。 隐藏,复制Code

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

    参数的数量是列的数量。表格宽度小于边框线的部分将按这些参数的比例进行划分。 一旦用SetColumnWidth方法设置了列数,库就会创建两个PdfTableCell数组。一个数组用于标题单元格,一个数组用于数据单元格。 数据表的行和列可以用边框线分隔。Border lines属性由PdfTableBorder和PdfTableBorderStyle定义。有四个水平边框行:标题行和第一个数据行之间的TopBorder、BottomBorder、HeaderHorBorder以及数据行之间的CellHorBorder。有两组垂直边框行:header vertborder数组用于标题行内的垂直边框行,CellVertBorder数组用于表数据部分内的列之间的垂直边框行。数组的大小是列数加1。数组元素0是表格的左边框。数组元素列是表的右边框。所有其他元素都是分隔列的行。每一行都可以单独定义。有一些方法可以一次性定义所有的边界线或定义每个单独的边界线。 定义所有边框线的方法: 隐藏,复制Code

    // 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);

    每个水平边框线都可以被清除或设置。以顶部边框线为例: 隐藏,复制Code

    // 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);

    可以清除或设置每个垂直边框线。例如单元格的垂直边框线: 隐藏,复制Code

    // 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);

    设置其他可选表属性。下面示例中给出的值是默认值。 隐藏,复制Code

    // header on each page
    HeaderOnEachPage = true;
    
    // minimum row height
    MinRowHeight = 0.0;

    表信息一次处理一行。每行都由单元格组成。每列一个单元格。单元格信息的显示由PdfTableStyle类控制。大约有20个样式属性。要获得完整的列表,请查看源代码或帮助文件。其中一些样式是特定于要显示的信息类型的。这里有个例子 隐藏,复制Code

    // 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列。 隐藏,复制Code

    // 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。 互动功能的例子。 隐藏,复制Code

    // 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.cs和TableExample.cs。有关PdfTable、PdfTableCell、PdfTableStyle和PdfTableBorder类的详细文档,请查看PdfFileWriter。chm帮助文件。 2.13。播放视频文件 PdfFileWriter支持在PDF文档中嵌入视频文件。在OtherExample.cs的第7页给出了播放视频文件的完整例子。添加视频文件需要使用三个类。首先,您需要将视频文件嵌入到PDF文档中。 其次,您需要定义如何播放视频。PdfDisplayMedia类有许多控制视频显示的方法。请参考类的源代码和文档帮助文件。例如:RepeatCount或ScaleMedia。如果你想在浮动窗口中播放视频,你必须使用SetMediaWindow方法。 第三,您需要在PDF页面上定义用户必须单击才能激活视频的区域。如果您想在注释区域可见时激活视频,请在pageisvisible时使用activateaction。 隐藏,复制Code

    // 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);

    浮动窗口视频显示 隐藏,复制Code

    // 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
    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文档中嵌入声音文件。播放声音文件的完整例子在OtherExample.cs的第7页。嵌入声音文件本质上与视频文件相同。唯一明显的区别是没有什么可以展示的。 隐藏,复制Code

    // 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文档中嵌入数据文件。完整的嵌入文件的例子在OtherExample.cs的第7页给出。用户可以保存文件或显示文件。 隐藏,复制Code

    // 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将新页面追加到页面列表的末尾。如果要将页面从当前位置移动到新位置,请使用以下方法。 隐藏,复制Code

    // Source and destination index are zero based.
    // Source must be 0 to PageCount - 1.
    // Destination must be 0 to PageCount.
    // If destination index is PageCount, the page will be the last page
    // PageCount is a property of PdfDocument.
    Document.MovePage(Int32 SourceIndex, Int32 DestinationIndex);

    2.17。PDF文档输出 PdfFileWriter创建PDF文档。主类PdfDocument构造函数为保存文档提供了两种选择。第一种选择是将PDF文件保存到磁盘文件中。在本例中,您为构造器提供了一个文件名。在文件创建结束时,调用PdfDocument.CreateFile。此方法将PDF写入文件并关闭文件。 隐藏,复制Code

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

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

    // 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阅读器在文档属性的Description选项卡中显示。这些信息包括:标题、作者、主题、关键字、创建的日期和时间、修改的日期和时间、生成文件的应用程序、PDF生成器。在申请中包含文件信息的做法如下: 隐藏,复制Code

    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对象时,将向字典中添加四个附加字段。您可以在您的代码中覆盖所有它们。 隐藏,复制Code

    // 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 Chart类生成一个图像。PdfContents的DrawChart方法将执行提交。或者,您可以调用PdfChart的CommitToPdfFile方法。 隐藏,复制Code

    // 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演示基础WPF 绘制WPF图形有四个步骤。 步骤1:创建DrawWPFPath对象。输入参数是路径和Y轴引发反应。步骤2:可选地通过调用七个SetBrush方法中的一个或调用UseCurrentBrush方法来添加一个画笔。步骤3:可选地通过调用两个SetPen方法中的一个或调用UseCurrentPen方法来添加一支钢笔。步骤4:调用pdfcontent . drawwpfpath绘制图形对象。 如果System.Windows。媒体引用不可用(例如,你的应用程序是Windows窗体),你需要添加PresentationCore和WindowsBase组件到你的应用程序。 在OtherExample.cs Example8e和Example8f中给出了WPF图形类绘图的编程示例。 如果没有笔刷和钢笔定义绘制图形作为剪辑路径。 下面您将看到如何在WPF应用程序和其他应用程序中使用DrawWPFPath类的更多细节。 DrawWPFPath构造函数有两个参数:路径和Y轴方向。路径可以是字符串,也可以是System.Windows.Media.PathGeometry。文本字符串是用路径标记语法定义的。路径几何类在PathGeometry类中描述。当为WPF环境定义路径时,Y轴方向是向下的。在PDF环境下,Y轴已启动。 请注意,世界上任何地方的程序员都使用除句点之外的数字十进制分隔符。表示路径的文本字符串输入的构造必须与路径标记语法中的定义完全相同。带分数的十进制数字必须使用周期,无论世界区域。如果在x和y值之间使用可选分隔符,则必须是逗号。如果字符串是由另一个应用程序生成的,请确保通过以下方式调用PathGeometry.ToString(系统. globalize . cultureinfo .不变文化)。换句话说,就是微软的PathGeometry。解析方法将无法读取意大利生成的文本字符串,例如,由PathGeometry生成的文本字符串。未将IFormatProvider设置为不变文化的ToString方法。 为WPF应用程序定义画笔有三种方法。所有这些方法都会同时设置画笔的不透明度。 System.Windows.Media。参见SolidColorBrush类system . windows . media。查看LinearGradientBrush类system . windows . media。查看RadialGradientBrush类 有五种方法可以为所有应用程序定义画笔。所有这些方法都会同时设置画笔的不透明度。 设置笔刷为system . draw. color。设置brush为pdfaxialshadows设置brush为pdfradialshadows设置brush为pdftilingpattern设置brush为UseCurrentBrush 如果您希望DrawWPFPath类将画笔设置为当前选中的画笔,请调用UseCurrentBrush方法。 有一种方法可以为WPF应用程序定义钢笔。使用System.Windows.Media调用SetPen方法。钢笔类(参见钢笔类)。注意,钢笔。刷子属性必须是SolidColorBrush。pen类包含绘制一条直线所需的所有信息,比如颜色和宽度。 有一个方法可以为所有应用程序定义钢笔。使用System.Drawing调用SetPen。颜色参数。颜色参数定义了alpha、红色、绿色和蓝色组件。要设置其他钢笔特征,请设置以下任意或全部属性和方法: setpenwidth dasharray dashphase linecap linejoin miterlimit 如果您希望DrawWPFPath类将钢笔设置为当前选择的钢笔,请调用UseCurrentPen方法。 在DrawWPFPath类中设置了绘制路径所需的所有信息之后,调用PdfContents。DrawWPFPath方法。DrawWPFPath类根据路径边界框、绘制矩形和对齐方式计算将输入路径转换为绘制矩形所需的转换矩阵。零点对齐(默认值)将拉伸路径以适应绘图区域。所有其他对齐值都根据参数枚举值定位绘图区域内的路径。 隐藏,复制Code

    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。不透明度值对应于一个颜色结构的alpha组件,例如1.0是255 alpha, 0.0是0 alpha。如果不透明度值为0.5,在页面上绘制的新对象将透明50%。要设置不透明度,对线条调用SetAlphaStroking方法,对形状调用SetAlphaNonStroking方法。混合是将页面上的颜色与正在绘制的新项目的颜色相结合的过程。要设置乏味模式,请调用PdfContents的SetBlendMode方法。参数是BlendMode枚举。有关详细说明,请参阅PDF规格文件的7.2.4节混合模式。例如,请参阅其他例子。cs第8页。 2.22。文档链接,并命名为目的地 文档链接允许PDF文档用户单击链接并跳转到文档的另一部分。添加文档链接分为两部分。目标被定义为一个位置标记。位置标记必须有唯一的名称、范围(LocalDest或NamedDest)和文件位置(页和位置)。NamedDest作用域既可以用于文档链接,也可以用于指定目的地,也可以同时用于两者。第二部分是链接位置。这两个部分可以以任何顺序定义。他们因名字而联系在一起。名称是区分大小写的。许多链接可以指向相同的位置标记。 命名目的地是PDF文档中的目标。它们的定义方式与文档链接相同,都使用了位置标记。必须将作用域设置为NamedDest。当PDF阅读器(如adobeacrobat)打开PDF文档时,它可以在打开文档的同时在查看窗口中显示目标。 要嵌入位置标记,请调用PdfPage的AddLocationMarker方法。注意:名称是区分大小写的。 隐藏,复制Code

    // 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方法。 隐藏,复制Code

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

    有关指定目的地的详细资料,请参阅adobepdf文件规格" PDF参考,第六版,adobeportable Document Format Version 1.7 2006年11月"。582页的表8.2。 DestFit。Fit(无参数):显示页面,将其内容放大,以便在水平和垂直方向上都能容纳整个页面。DestFit。FitH (1 arg Top):显示页面,垂直的顶部坐标位于窗口的顶部边缘,页面的内容被放大到足以容纳窗口内的整个页面宽度。DestFit。FitV(左1 arg):显示页面,水平坐标位于窗口的左边缘,页面内容被放大以适应窗口内页面的整个高度。DestFit。FitR(左、下、右、上4个参数):显示页面,将其内容放大到足以在窗口中水平和垂直地完全适应由左、下、右和上的坐标所指定的矩形。DestFit。FitB(无参数):显示页面,将其内容放大,使其在水平和垂直方向上都能完全适应边框。DestFit。FitBH (1 arg Top):显示页面,垂直坐标顶部位于窗口的上边缘,页面内容被放大到刚好适合窗口内边框的整个宽度。DestFit。FitBV(左1 arg):显示页面,水平坐标位于窗口的左边缘,页面内容被放大以适应窗口内边框的整个高度。 PDF阅读器的调用参数在Adobe打开PDF文件的参数中定义。如果PDF是在台式电脑上打开的,电话线必须是: “路径\ AcroRd32。/A "nameddest=ChapterXX"路径\Document.pdf" 如果PDF文档是由网页中的链接指向的,则目的地附加到该链接: & lt; a href = " http://example.org/Document.pdf ChapterXX”在目标description< / a> 或者:<a href="http://example.org/Document.pdf# named本=ChapterXX">Target description</a> 2.23。加密支持 PDF文件编写器库提供对AES 128和标准128 (RC4)加密的支持。详情请参阅PDF参考第六版(1.7版本)第3.5节加密。PDF文件编写器支持两种类型的加密过滤器,即AES-128和标准128。标准128是RC4加密。它被认为是不安全的。对于新项目不要使用它。它不支持对收件人列表进行编码的公钥安全性。 要加密PDF文档,请调用在PdfDocument类中定义的四种加密方法中的一种: 设置不带参数的加密。 PDF文件编写器库将使用AES-128加密对PDF文档进行加密。PDF阅读器不需要密码就可以打开文档。权限标志被设置为允许所有。 隐藏,复制Code

    Document.SetEncryption();

    用一个参数设置加密。 PDF文件编写器库将使用AES-128加密对PDF文档进行加密。参数是权限。权限标志定义如下。您可以或一起使用多个权限。PDF参考手册对权限有完整的描述。PDF阅读器不需要密码就可以打开文档。 隐藏,复制Code

    Document.SetEncryption(Permission Permissions);

    用两个参数设置加密。 PDF文件编写器库将使用AES-128加密对PDF文档进行加密。这两个参数是用户密码和权限。PDF阅读器将使用用户密码打开文档。权限将根据参数设置。 隐藏,复制Code

    Document.SetEncryption(String UserPassword, Permission Permissions);

    用四个参数设置加密。 PDF文件编写器库将使用任意一种方法对PDF文档进行加密EncryptionType。Aes128加密或EncryptionType。Standard128加密。这四个参数是用户密码、所有者密码、权限和加密类型。如果用户密码为null,则采用默认密码。如果用户密码为空,软件会生成随机数密码。标准128加密被认为是不安全的。它不应该用于新项目。 PDF阅读器(如Acrobat)可以接受用户密码或所有者密码。如果使用所有者密码来打开文档,PDF阅读器将在所有权限设置为允许操作的情况下打开它。 隐藏,复制Code

    Document.SetEncryption(String UserPassword, String OwnerPassword, Permission Permissions, EncryptionType Type);

    权限标志如下: 隐藏,复制Code

    // Full description is given in
    // PDF Reference Version 1.7 Table 3.20
    public enum Permission
    	{
    	None = 0,
    	LowQalityPrint = 4,	// bit 3
    	ModifyContents = 8,	// bit 4
    	ExtractContents = 0x10,	// bit 5
    	Annotation = 0x20,	// bit 6
    	Interactive = 0x100,	// bit 9
    	Accessibility = 0x200,	// bit 10
    	AssembleDoc = 0x400,	// bit 11
    	Print = 0x804,		// bit 12 + bit 3
    	All = 0xf3c,		// bits 3, 4, 5, 6, 9, 10, 11, 12
    	}

    2.24。便利贴或文本注释。 PDF参考文档定义了便利贴或文本注释,参见第8.4节621页。文本注释表示附加到PDF文档中某个点上的“便利贴”。关闭时,注释显示为图标;打开时,它将显示一个弹出窗口,其中包含注释的文本,其字体和大小由查看器应用程序选择。文本标注不随页面缩放和旋转;它们的行为就好像总是设置了NoZoom和NoRotate注释标志(参见608页的表8.16)。表8.23显示了特定于这种类型的注释字典条目。” 在文档中添加一个便利贴非常简单。只需添加一行代码。便签被添加到PdfPage对象中。它不是页面内容的一部分。便利贴的位置是从页面的左下角到便利贴图标的左上角的绝对页面位置。文本字符串是弹出窗口的内容。stick note参数是下面的枚举项之一。 隐藏,复制Code

    // sticky note text annotation
    Page.AddStickyNote(PageAbsPosX, PageAbsPosY,
        "My first sticky note", StickyNoteIcon.Note);

    隐藏,复制Code

    // Sticky note icon
    public enum StickyNoteIcon
        {
        // Comment (note: no icon)
        Comment,
    
        // Key
        Key,
       
        // Note (default)
        Note,
            
        // Help
        Help,
            
        // New paragraph
        NewParagraph,
            
        // Paragraph
        Paragraph,
            
        // Insert
        Insert,
        }

    2.25。层或可选内容。 PDF规范文档(第4.10节)定义了如下可选内容。可选内容(PDF 1.5)指的是PDF文档中可以被文档作者或用户选择性地查看或隐藏的部分内容。这种能力在CAD绘图、分层插图、地图和多语言文档等项目中非常有用。” adobeacrobat viewer在屏幕左侧有导航面板。其中一个是层面板。如果一个PDF文档使用层,层控制开关将显示在这个面板。用户可以显示或隐藏附加到这些层控件的项。 在PDF文档中添加图层。完整的例子在LayersExample.cs中给出。cs还提供了使用图层来控制图片和注释的例子。 创建主层控件对象。每一个文档。 隐藏,复制Code

    // create a layers control object and give it a name.
    // only one object like that is allowed.
    // The name will be displayed in the layer panel.
    PdfLayers Layers = new PdfLayers(Document, "PDF layers group");

    设置列表模式选项。默认值是所有页面 隐藏,复制Code

    // List mode
    Layers.ListMode = ListMode.AllPages; // default
    
    // or
    Layers.ListMode = ListMode.VisiblePages;

    创建一个或多个层对象。每一个对应于层面板上的一个复选框。每个控件都可以控制一个或多个显示项。 隐藏,复制Code

    // create one or more layer objects
    PdfLayer LayerName = new PdfLayer(Layers, "Layer name");

    许多层可以组合成单选按钮组。一组单选按钮可以全部关闭,也可以只打开一层。 隐藏,复制Code

    // Optionally combine three layers into
    // one group of radio buttons
    LayerName1.RadioButton = "Group1";
    LayerName2.RadioButton = "Group1";

    设置层窗格中的层的顺序。如果不使用DisplayOrder方法,程序将列出在同一主层上指定的所有层。如果使用DisplayOrder方法,则必须包括所有层 层列表可以有具有可选名称的子组 隐藏,复制Code

    // display order
    Layers.DisplayOrder(LayerName1);
    Layers.DisplayOrder(LayerName2);
    Layers.DisplayOrder(LayerName3);
    Layers.DisplayOrderStartGroup("Sub Group");
    Layers.DisplayOrder(LayerName4);
    Layers.DisplayOrder(LayerName5);
    Layers.DisplayOrder(LayerName6);
    Layers.DisplayOrderEndGroup();

    在内容流中定义由层控制的区域 隐藏,复制Code

    // contents stream start layer marker
    Contents.LayerStart(LayerName1);
    
    // your contents methods to be
    // controlled by LayerName1
    
    // end of LayerName1 area
    Contents.LayerEnd();

    直接控制图像或注释。图像可以位于文档中的任何位置。 隐藏,复制Code

    // image or annotation control
    QREncoder QREncoder = new QREncoder();
    QREncoder.ErrorCorrection = ErrorCorrection.M;
    QREncoder.Encode("Some data");
    PdfImage QRImage = new PdfImage(Document);
    QRImage.LayerControl = LayerName1;
    QRImage.LoadImage(QREncoder);

    2.26。最初的文件显示。 初始文档显示控制文档在PDF查看器(Acrobat)显示时的外观。它控制屏幕的左窗格。 例如,打开书签窗格。 隐藏,复制Code

    Document.InitialDocDisplay = InitialDocDisplay.UseBookmarks;

    隐藏,复制Code

    // initial document display enumeration
    public enum InitialDocDisplay
    {
    // keep the left pane closed
    UseNone,
    
    // open the bookmarks pane
    UseBookmarks,
    
    // open the page thumbnails
    UseThumbs,
    
    // full screen mode
    FullScreen,
    
    // open layers
    UseLayers,
    
    // open attachments
    UseAttachments,
    }

    2.27。XMP元数据。 XMP文件或字节数组嵌入到包含在PDF对象中的元数据流中。XMP必须编码为UTF-8。PdfFileWriter包含用户给定的输入文件或输入字节数组。用户必须确保XMP输入是有效的元文件。没有压缩或加密XMP流。这允许读者通过少量编程获得元数据信息。您应该在创建PdfDocument之后不久以及在加载任何映像之前包含XMP matadata。通过这样做,元数据将位于文件的开头,并且它将被简单的文本编辑器读取。 隐藏,复制Code

    // adding metadata
    new PdfMatadata(Document, FileName);
    
    // or
    new PdfMetadata(Document, ByteArray);

    3.实例开发指南 本节介绍如何将PDF文件编写器c#类库集成到应用程序中。测试程序TestPdfFileWriter程序是对您自己的应用程序的模拟。当您按下“Article Example”按钮时,程序将执行ArticleExample.cs源文件中的代码。ab形象ove显示结果PDF文件。这个方法演示了如何创建带有一些文本和图形的页面文档。在完成这个示例之后,您应该对流程有了很好的理解。另一个示例按钮生成各种PDF文档。总之,这些示例几乎演示了这个库的所有特性。 如果选中Debug复选框,则将创建一个可以用文本编辑器查看但不能加载到PDF阅读器的PDF文件。结果文件没有被压缩,图像和字体文件被替换为文本占位符。“调试”复选框只能用于调试。 TestPdfFileWriter程序是使用Microsoft Visual c# 2012开发的。它对Windows XP、Vista、7和8进行了测试。 3.1。文档创建概述 下面的测试方法演示了在简介中描述的创建PDF文件的六个步骤。当您按下演示程序的“Article Example”按钮时,将执行该方法。下面的子节详细描述了每个步骤。 隐藏,收缩,复制Code

    // Create article's example test PDF document
    public void Test
            (
            bool Debug,
            string FileName
            )
    {
        {
        // Step 1: Create empty document
        // Arguments: page  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(null, null, Permission.All & ~Permission.Print, EncryptionType.Aes128);
    
        // 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;
    
        PdfInfo Info = PdfInfo.CreatePdfInfo(Document);
        Info.Title("Article Example");
        Info.Author("Uzi Granot");
        Info.Keywords("PDF, .NET, C#, Library, Document Creator");
        Info.Subject("PDF File Writer C# Class Library (Version 1.21.0)");
    
        // 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 graphices and text contents to the contents object
        DrawFrameAndBackgroundWaterMark();
        DrawTwoLinesOfHeading();
        DrawHappyFace();
        DrawBarcode();
        DrawPdf417Barcode();
        DrawImage();
        DrawChart();
        DrawTextBox();
        DrawBookOrderForm();
    
        // Step 6: create pdf file
        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方法创建了本例中使用的所有字体资源。要查看所有可用于任何字体的字符,请按“字体家族”按钮。选择一个系列并查看为每个字符定义的符号。要查看单个符号,请按“查看”或双击。 隐藏,复制Code

    // 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”在浅蓝色的白色背景。该模式由两行重复关键词组成。这两行被半字的长度扭曲了。 如果你想找到有趣的图案,可以在网上搜索制造地板或墙板的公司目录。 隐藏,收缩,复制Code

    // Define Tiling Pattern Resource
    private void DefineTilingPatternResource()
    {
        // create empty tiling pattern
        WaterMark = new PdfTilingPattern(Document);
    
        // the pattern will be PdfFileWriter laied 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
        double BaseLine = ArialBold.DescentPlusLeading(FontSize);
    
        // the overall pattern box (we add text height value as left and right text margin)
        double BoxWidth = TextWidth + 2 * TextHeight;
        double BoxHeight = 4 * TextHeight;
        WaterMark.SetTileBox(BoxWidth, BoxHeight);
    
        // save graphics state
        WaterMark.SaveGraphicsState();
    
        // fill the pattern box with background light blue color
        WaterMark.SetColorNonStroking(Color.FromArgb(230, 244, 255));
        WaterMark.DrawRectangle(0, 0, BoxWidth, BoxHeight, PaintOp.Fill);
    
        // set fill color for water mark text to white
        WaterMark.SetColorNonStroking(Color.White);
    
        // draw PdfFileWriter at the bottom center of the box
        WaterMark.DrawText(ArialBold, FontSize, BoxWidth / 2, BaseLine, TextJustify.Center, Mark);
    
        // adjust base line upward by half height
        BaseLine += BoxHeight / 2;
    
        // draw the right half of PdfFileWriter shifted left by half width
        WaterMark.DrawText(ArialBold, FontSize, 0.0, BaseLine, TextJustify.Center, Mark);
    
        // draw the left half of PdfFileWriter shifted right by half width
        WaterMark.DrawText(ArialBold, FontSize, BoxWidth, BaseLine, TextJustify.Center, Mark);
    
        // restore graphics state
        WaterMark.RestoreGraphicsState();
        return;
    }

    3.4。画框架与背景图案 DrawFrameAndBackgroundWaterMark方法在示例区域周围绘制带有背景水印图案的框架。模式资源在前面的小节中定义。 隐藏,收缩,复制Code

    // Draw frame around example area
    private void DrawFrameAndBackgroundWaterMark()
    {
        // save graphics state
        Contents.SaveGraphicsState();
    
        // Draw frame around the page
        // Set line width to 0.02"
        Contents.SetLineWidth(0.02);
    
        // set frame color dark blue
        Contents.SetColorStroking(Color.DarkBlue);
    
        // use water mark tiling pattern to fill the frame
        Contents.SetPatternNonStroking(WaterMark);
    
        // rectangle position: x=1.0", y=1.0", width=6.5", height=9.0"
        Contents.DrawRectangle(1.0, 1.0, 6.5, 9.0, PaintOp.CloseFillStroke);
    
        // restore graphics sate
        Contents.RestoreGraphicsState();
    
        // draw article name under the frame
        // Note: the \u00a4 is character 164 that was substituted during Font resource definition
        // this character is a solid circle it is normally Unicode 9679 or \u25cf in the Arial family
        Contents.DrawText(ArialNormal, 9.0, 1.1, 0.85, "PdfFileWriter \u25cf PDF File Writer C# Class Library \u25cf Author: Uzi Granot");
    
        // draw web link to the article
        Contents.DrawWebLink(Page, ArialNormal, 9.0, 7.4, 0.85, TextJustify.Right,
        DrawStyle.Underline, Color.Blue, "Click to view article", ArticleLink);
    
        return;
    }

    3.5。画两条标题线 DrawTwoLinesOfHeading方法在页面中心绘制两条标题线。第一行是用轮廓特效绘制文本。 隐藏,复制Code

    // Draw heading
    private void DrawTwoLinesOfHeading()
    {
        // page heading
        // Arguments: Font: ArialBold, size: 36 points, Position: X = 4.25", Y = 9.5"
        // Text Justify: Center (text center will be at X position)
        // Stoking color: R=128, G=0, B=255 (text outline)
        // Nonstroking color: R=255, G=0, B=128 (text body)
        Contents.DrawText(Comic, 40.0, 4.25, 9.25, TextJustify.Center, 0.02, Color.FromArgb(128, 0, 255), Color.FromArgb(255, 0, 128), "PDF FILE WRITER");
    
        // save graphics state
        Contents.SaveGraphicsState();
    
        // change nonstroking (fill) color to purple
        Contents.SetColorNonStroking(Color.Purple);
    
        // Draw second line of heading text
        // arguments: Handwriting font, Font size 30 point, Position X=4.25", Y=9.0"
        // Text Justify: Center (text center will be at X position)
        Contents.DrawText(Comic, 30.0, 4.25, 8.75, TextJustify.Center, "Example");
    
        // restore graphics sate (non stroking color will be restored to default)
        Contents.RestoreGraphicsState();
        return;
    }

    3.6。画笑脸 DrawHappyFace方法是一个从一条直线和贝赛尔曲线绘制椭圆和构造路径的示例。 隐藏,收缩,复制Code

    // Draw Happy Face
    private void DrawHappyFace()
    {
        // save graphics state
        Contents.SaveGraphicsState();
    
        // translate coordinate origin to the center of the happy face
        Contents.Translate(4.25, 7.5);
    
        // change nonstroking (fill) color to yellow
        Contents.SetColorNonStroking(Color.Yellow);
    
        // draw happy face yellow oval
        Contents.DrawOval(-1.5, -1.0, 3.0, 2.0, PaintOp.Fill);
    
        // set line width to 0.2" this is the black circle around the eye
        Contents.SetLineWidth(0.2);
    
        // eye color is white with black outline circle
        Contents.SetColorNonStroking(Color.White);
        Contents.SetColorStroking(Color.Black);
    
        // draw eyes
        Contents.DrawOval(-0.75, 0.0, 0.5, 0.5, PaintOp.CloseFillStroke);
        Contents.DrawOval(0.25, 0.0, 0.5, 0.5, PaintOp.CloseFillStroke);
    
        // mouth color is black
        Contents.SetColorNonStroking(Color.Black);
    
        // draw mouth by creating a path made of one line and one Bezier curve 
        Contents.MoveTo(-0.6, -0.4);
        Contents.LineTo(0.6, -0.4);
        Contents.DrawBezier(0.0, -0.8, 0, -0.8, -0.6, -0.4);
    
        // fill the path with black color
        Contents.SetPaintOp(PaintOp.Fill);
    
        // restore graphics sate
        Contents.RestoreGraphicsState();
        return;
    }

    3.7。画条形码 绘制条码方法是绘制两个条形码EAN-13和Code-128的示例 隐藏,收缩,复制Code

    // Draw Barcode
    private void DrawBarcode()
    {
        // save graphics state
        Contents.SaveGraphicsState();
    
        // draw EAN13 barcode
        BarcodeEAN13 Barcode1 = new BarcodeEAN13("1234567890128");
        Contents.DrawBarcode(1.3, 7.05, 0.012, 0.75, Barcode1, ArialNormal, 8.0);
    
        // create QRCode barcode
        QREncoder QREncoder = new QREncoder();
    
        // set error correction code
        QREncoder.ErrorCorrection = ErrorCorrection.M;
    
        // set module size in pixels
        QREncoder.ModuleSize = 1;
    
        // set quiet zone in pixels
        QREncoder.QuietZone = 4;
    
        // encode your text or byte array
        QREncoder.Encode(ArticleLink);
    
        // convert QRCode to black and white image
        PdfImage BarcodeImage = new PdfImage(Document);
        BarcodeImage.LoadImage(QREncoder);
    
        // draw image (height is the same as width for QRCode)
        Contents.DrawImage(BarcodeImage, 6.0, 6.8, 1.2);
    
        // define a web link area coinsiding with the qr code
        Page.AddWebLink(6.0, 6.8, 7.2, 8.0, ArticleLink);
    
        // restore graphics sate
        Contents.RestoreGraphicsState();
        return;
    }

    3.8。画PDF417条码 隐藏,收缩,复制Code

    // Draw Barcode
    private void DrawPdf417Barcode()
    {
        // save graphics state
        Contents.SaveGraphicsState();
    
        // create PDF417 barcode
        Pdf417Encoder Pdf417 = new Pdf417Encoder();
        Pdf417.DefaultDataColumns = 3;
        Pdf417.Encode(ArticleLink);
        Pdf417.WidthToHeightRatio(2.5);
    
        // convert Pdf417 to black and white image
        PdfImage BarcodeImage = new PdfImage(Document);
        BarcodeImage.LoadImage(Pdf417);
    
        // draw image
        Contents.DrawImage(BarcodeImage, 1.1, 5.2, 2.5);
    
        // define a web link area coinsiding with the qr code
        double Height = 2.5 * Pdf417.ImageHeight / Pdf417.ImageWidth;
        Page.AddWebLink(1.1, 5.2, 1.1 + 2.5, 5.2 + Height, ArticleLink);
    
        // restore graphics sate
        Contents.RestoreGraphicsState();
        return;
    }

    3.9。绘制图像和剪辑它 DrawImage方法是绘制图像的示例。PdfFileWriter支持存储在位图类和元文件类支持的所有图像文件中的绘图图像。ImageFormat类定义了所有图像类型。JPEG图像文件类型是PDF文件的原生图像格式。如果使用JPEG文件调用PdfImage构造函数,则程序将文件原样复制到PDF文件中。如果使用任何其他类型的图像文件调用PdfImage构造函数,该程序将其转换为JPEG文件。为了保持PDF文件的大小尽可能小,请确保您的图像文件的分辨率不是过高。 PdfImage类加载图像并计算在用户坐标中适合给定图像大小并保持原始宽高比的最大大小。在绘制图像之前,我们创建一个椭圆形剪切路径剪辑图像。 隐藏,收缩,复制Code

    // Draw image and clip it
    private void DrawImage()
    {
        // define local image resources
        // resolution 96 pixels per inch, image quality 50%
        PdfImage Image1 = new PdfImage(Document);
        Image1.Resolution = 96.0;
        Image1.ImageQuality = 50;
        Image1.LoadImage("TestImage.jpg");
    
        // save graphics state
        Contents.SaveGraphicsState();
    
        // translate coordinate origin to the center of the picture
        Contents.Translate(3.75, 5.0);
    
        // adjust image size and preserve aspect ratio
        PdfRectangle NewSize = Image1.ImageSizePosition(1.75, 1.5, ContentAlignment.MiddleCenter);
    
        // clipping path
        Contents.DrawOval(NewSize.Left, NewSize.Bottom, NewSize.Width, NewSize.Height, PaintOp.ClipPathEor);
    
        // draw image
        Contents.DrawImage(Image1, NewSize.Left, NewSize.Bottom, NewSize.Width, NewSize.Height);
    
        // restore graphics state
        Contents.RestoreGraphicsState();
        return;
    }

    3.10。画饼图 DrawChart方法是定义图表并将其绘制到PDF文档的示例。 隐藏,收缩,复制Code

    // Draw chart
    private void DrawChart()
    {
        // save graphics state
        Contents.SaveGraphicsState();
    
        // create chart
        Chart PieChart = PdfChart.CreateChart(Document, 1.8, 1.5, 300.0);
    
        // create PdfChart object with Chart object
        PdfChart PiePdfChart = new PdfChart(Document, PieChart);
        PiePdfChart.SaveAs = SaveImageAs.IndexedImage;
    
        // make sure we have good quality image
        PieChart.AntiAliasing = AntiAliasingStyles.None; //.All;
    
        // set colors
        PieChart.BackColor = Color.FromArgb(220, 220, 255);
        PieChart.Palette = ChartColorPalette.BrightPastel;
    
        // default font
        Font DefaultFont = PiePdfChart.CreateFont("Verdana", FontStyle.Regular, 0.05, FontSizeUnit.UserUnit);
        Font TitleFont = PiePdfChart.CreateFont("Verdana", FontStyle.Bold, 0.07, FontSizeUnit.UserUnit);
    
        // title (font size is 0.25 inches)
        Title Title1 = new Title("Pie Chart Example", Docking.Top, TitleFont, Color.Purple);
        PieChart.Titles.Add(Title1);
    
        // legend
        Legend Legend1 = new Legend();
        PieChart.Legends.Add(Legend1);
        Legend1.BackColor = Color.FromArgb(230, 230, 255);
        Legend1.Docking = Docking.Bottom;
        Legend1.Font = DefaultFont;
    
        // chart area
        ChartArea ChartArea1 = new ChartArea();
        PieChart.ChartAreas.Add(ChartArea1);
    
        // chart area background color
        ChartArea1.BackColor = Color.FromArgb(255, 200, 255);
    
        // series 1
        Series Series1 = new Series();
        PieChart.Series.Add(Series1);
        Series1.ChartType = SeriesChartType.Pie;
        Series1.Font = DefaultFont;
        Series1.IsValueShownAsLabel = true;
        Series1.LabelFormat = "{0} %";
    
        // series values
        Series1.Points.Add(22.0);
        Series1.Points[0].LegendText = "Apple";
        Series1.Points.Add(27.0);
        Series1.Points[1].LegendText = "Banana";
        Series1.Points.Add(33.0);
        Series1.Points[2].LegendText = "Orange";
        Series1.Points.Add(18.0);
        Series1.Points[3].LegendText = "Grape";
    
        Contents.DrawChart(PiePdfChart, 5.6, 5.0);
    
        // restore graphics state
        Contents.RestoreGraphicsState();
        return;
    }

    3.11。画出文本框 DrawTextBox方法是使用TextBox类的一个例子。TextBox类将文本格式化为适合列的格式。文本可以使用字体样式和大小的真实性来绘制。 隐藏,收缩,复制Code

    // Draw example of a text box
    private void DrawTextBox()
    {
        // save graphics state
        Contents.SaveGraphicsState();
    
        // translate origin to PosX=1.1" and PosY=1.1" this is the bottom left corner of the text box example
        Contents.Translate(1.1, 1.1);
    
        // Define constants
        // Box width 3.25"
        // Box height is 3.65"
        // Normal font size is 9.0 points.
        const double Width = 3.15;
        const double Height = 3.65;
        const double FontSize = 9.0;
    
        // Create text box object width 3.25"
        // First line indent of 0.25"
        TextBox Box = new TextBox(Width, 0.25);
    
        // add text to the text box
        Box.AddText(ArialNormal, FontSize,
        "This area is an example of displaying text that is too long to fit within a fixed width " +
        "area. The text is displayed justified to right edge. You define a text box with the required " +
        "width and first line indent. You add text to this box. The box will divide the text into " +
        "lines. Each line is made of segments of text. For each segment, you define font, font " +
        "size, drawing style and color. After loading all the text, the program will draw the formatted text.\n");
        Box.AddText(TimesNormal, FontSize + 1.0, "Example of multiple fonts: Times New Roman, ");
        Box.AddText(Comic, FontSize, "Comic Sans MS, ");
        Box.AddText(ArialNormal, FontSize, "Example of regular, ");
        Box.AddText(ArialBold, FontSize, "bold, ");
        Box.AddText(ArialItalic, FontSize, "italic, ");
        Box.AddText(ArialBoldItalic, FontSize, "bold plus italic. ");
        Box.AddText(ArialNormal, FontSize - 2.0, "Arial size 7, ");
        Box.AddText(ArialNormal, FontSize - 1.0, "size 8, ");
        Box.AddText(ArialNormal, FontSize, "size 9, ");
        Box.AddText(ArialNormal, FontSize + 1.0, "size 10. ");
        Box.AddText(ArialNormal, FontSize, DrawStyle.Underline, "Underline, ");
        Box.AddText(ArialNormal, FontSize, DrawStyle.Strikeout, "Strikeout. ");
        Box.AddText(ArialNormal, FontSize, "Subscript H");
        Box.AddText(ArialNormal, FontSize, DrawStyle.Subscript, "2");
        Box.AddText(ArialNormal, FontSize, "O. Superscript A");
        Box.AddText(ArialNormal, FontSize, DrawStyle.Superscript, "2");
        Box.AddText(ArialNormal, FontSize, "+B");
        Box.AddText(ArialNormal, FontSize, DrawStyle.Superscript, "2");
        Box.AddText(ArialNormal, FontSize, "=C");
        Box.AddText(ArialNormal, FontSize, DrawStyle.Superscript, "2");
        Box.AddText(ArialNormal, FontSize, "\n");
        Box.AddText(Comic, FontSize, Color.Red, "Some color, ");
        Box.AddText(Comic, FontSize, Color.Green, "green, ");
        Box.AddText(Comic, FontSize, Color.Blue, "blue, ");
        Box.AddText(Comic, FontSize, Color.Orange, "orange, ");
        Box.AddText(Comic, FontSize, DrawStyle.Underline, Color.Purple, "and purple.\n");
        Box.AddText(ArialNormal, FontSize, "Support for non-Latin letters: ");
        Box.AddText(ArialNormal, FontSize, Contents.ReverseString("עברית"));
        Box.AddText(ArialNormal, FontSize, "АБВГДЕ");
        Box.AddText(ArialNormal, FontSize, "αβγδεζ");
    
        Box.AddText(ArialNormal, FontSize, "\n");
    
        // Draw the text box
        // Text left edge is at zero (note: origin was translated to 1.1") 
        // The top text base line is at Height less first line ascent.
        // Text drawing is limited to vertical coordinate of zero.
        // First line to be drawn is line zero.
        // After each line add extra 0.015".
        // After each paragraph add extra 0.05"
        // Stretch all lines to make smooth right edge at box width of 3.15"
        // After all lines are drawn, PosY will be set to the next text line after the box's last paragraph
        double PosY = Height;
        Contents.DrawText(0.0, ref PosY, 0.0, 0, 0.015, 0.05, TextBoxJustify.FitToWidth, Box);
    
        // Create text box object width 3.25"
        // No first line indent
        Box = new TextBox(Width);
    
        // Add text as before.
        // No extra line spacing.
        // No right edge adjustment
        Box.AddText(ArialNormal, FontSize,
        "In the examples above this area the text box was set for first line indent of " +
        "0.25 inches. This paragraph has zero first line indent and no right justify.");
        Contents.DrawText(0.0, ref PosY, 0.0, 0, 0.01, 0.05, TextBoxJustify.Left, Box);
    
        // Create text box object width 2.75
        // First line hanging indent of 0.5"
        Box = new TextBox(Width - 0.5, -0.5);
    
        // Add text
        Box.AddText(ArialNormal, FontSize,
        "This paragraph is set to first line hanging indent of 0.5 inches. " +
        "The left margin of this paragraph is 0.5 inches.");
    
        // Draw the text
        // left edge at 0.5"
        Contents.DrawText(0.5, ref PosY, 0.0, 0, 0.01, 0.05, TextBoxJustify.Left, Box);
    
        // restore graphics state
        Contents.RestoreGraphicsState();
        return;
    }

    3.12。抽签书订购单 DrawBookOrderForm方法是订单输入表单或发票的示例。它是数据表支持的一个例子。它演示了PdfTable、PdfTableCell和PdfTableStyle类的使用。 隐藏,收缩,复制Code

    // Draw example of order form
    private void DrawBookOrderForm()
    {
        // Define constants to make the code readable
        const double Left = 4.35;
        const double Top = 4.65;
        const double Bottom = 1.1;
        const double Right = 7.4;
        const double FontSize = 9.0;
        const double MarginHor = 0.04;
        const double MarginVer = 0.04;
        const double FrameWidth = 0.015;
        const double GridWidth = 0.01;
    
        // column widths
        double ColWidthPrice = ArialNormal.TextWidth(FontSize, "9999.99") + 2.0 * MarginHor;
        double ColWidthQty = ArialNormal.TextWidth(FontSize, "Qty") + 2.0 * MarginHor;
        double ColWidthDesc = Right - Left - FrameWidth - 3 * GridWidth - 2 * ColWidthPrice - ColWidthQty;
    
        // define table
        PdfTable Table = new PdfTable(Page, Contents, ArialNormal, FontSize);
        Table.TableArea = new PdfRectangle(Left, Bottom, Right, Top);
        Table.SetColumnWidth(new double[] { ColWidthDesc, ColWidthPrice, ColWidthQty, ColWidthPrice });
    
        // define borders
        Table.Borders.SetAllBorders(FrameWidth, GridWidth);
    
        // margin
        PdfRectangle Margin = new PdfRectangle(MarginHor, MarginVer);
    
        // default header style
        Table.DefaultHeaderStyle.Margin = Margin;
        Table.DefaultHeaderStyle.BackgroundColor = Color.FromArgb(255, 196, 255);
        Table.DefaultHeaderStyle.Alignment = ContentAlignment.MiddleRight;
    
        // private header style for description
        Table.Header[0].Style = Table.HeaderStyle;
        Table.Header[0].Style.Alignment = ContentAlignment.MiddleLeft;
    
        // table heading
        Table.Header[0].Value = "Description";
        Table.Header[1].Value = "Price";
        Table.Header[2].Value = "Qty";
        Table.Header[3].Value = "Total";
    
        // default style
        Table.DefaultCellStyle.Margin = Margin;
    
        // description column style
        Table.Cell[0].Style = Table.CellStyle;
        Table.Cell[0].Style.MultiLineText = true;
    
        // qty column style
        Table.Cell[2].Style = Table.CellStyle;
        Table.Cell[2].Style.Alignment = ContentAlignment.BottomRight;
    
        Table.DefaultCellStyle.Format = "#,##0.00";
        Table.DefaultCellStyle.Alignment = ContentAlignment.BottomRight;
    
        Contents.DrawText(ArialBold, FontSize, 0.5 * (Left + Right), Top + MarginVer + Table.DefaultCellStyle.FontDescent,
        TextJustify.Center, DrawStyle.Normal, Color.Purple, "Example of PdfTable support");
    
        // reset order total
        double Total = 0;
    
        // loop for all items in the order
        // Order class is a atabase simulation for this example
        foreach(Order Book in Order.OrderList)
            {
            Table.Cell[0].Value = Book.Title + ". By: " + Book.Authors;
            Table.Cell[1].Value = Book.Price;
            Table.Cell[2].Value = Book.Qty;
            Table.Cell[3].Value = Book.Total;
            Table.DrawRow();
    
            // accumulate total
            Total += Book.Total;
            }
        Table.Close();
    
        // save graphics state
        Contents.SaveGraphicsState();
    
        // form line width 0.01"
        Contents.SetLineWidth(FrameWidth);
        Contents.SetLineCap(PdfLineCap.Square);
    
        // draw total before tax
        double[] ColumnPosition = Table.ColumnPosition;
        double TotalDesc = ColumnPosition[3] - MarginHor;
        double TotalValue = ColumnPosition[4] - MarginHor;
        double PosY = Table.RowTopPosition - 2.0 * MarginVer - Table.DefaultCellStyle.FontAscent;
        Contents.DrawText(ArialNormal, FontSize, TotalDesc, PosY, TextJustify.Right, "Total before tax");
        Contents.DrawText(ArialNormal, FontSize, TotalValue, PosY, TextJustify.Right, Total.ToString("#.00"));
    
        // draw tax (Ontario Canada HST)
        PosY -= Table.DefaultCellStyle.FontLineSpacing;
        Contents.DrawText(ArialNormal, FontSize, TotalDesc, PosY, TextJustify.Right, "Tax (13%)");
        double Tax = Math.Round(0.13 * Total, 2, MidpointRounding.AwayFromZero);
        Contents.DrawText(ArialNormal, FontSize, TotalValue, PosY, TextJustify.Right, Tax.ToString("#.00"));
    
        // draw total line
        PosY -= Table.DefaultCellStyle.FontDescent + 0.5 * MarginVer;
        Contents.DrawLine(ColumnPosition[3], PosY, ColumnPosition[4], PosY);
    
        // draw final total
        PosY -= Table.DefaultCellStyle.FontAscent + 0.5 * MarginVer;
        Contents.DrawText(ArialNormal, FontSize, TotalDesc, PosY, TextJustify.Right, "Total payable");
        Total += Tax;
        Contents.DrawText(ArialNormal, FontSize, TotalValue, PosY, TextJustify.Right, Total.ToString("#.00"));
    
        PosY -= Table.DefaultCellStyle.FontDescent + MarginVer;
        Contents.DrawLine(ColumnPosition[0], Table.RowTopPosition, ColumnPosition[0], PosY);
        Contents.DrawLine(ColumnPosition[0], PosY, ColumnPosition[4], PosY);
        Contents.DrawLine(ColumnPosition[4], Table.RowTopPosition, ColumnPosition[4], PosY);
    
        // restore graphics state
        Contents.RestoreGraphicsState();
        return;
    }

    4. 安装 将PdfFileWriter集成到应用程序中需要执行以下步骤。在您的开发区域安装附加的pdffilewritl .dll文件。启动visualc#程序并打开应用程序。转到“解决方案资源管理器”,右键单击“引用”并选择“添加引用”。选择Browse选项卡并将文件系统导航到pdffilewritl .dll的位置。当您的应用程序被发布时,必须包含pdffilewritl .dll。 源代码文档可以在帮助文件pdffilewritl .chm中找到。该文件是produced沙塔。结果看起来像Microsoft文档页面。 如果您想访问PdfFileWriter项目的源代码,请在您的开发区域安装PdfFileWriter项目。PdfFileWriter.dll将位于PdfFileWriter\bin\释放目录中。 将以下语句添加到使用此库的所有源模块。 隐藏,复制Code

    using PdfFileWriter;

    如果您打算使用图表,您需要添加对:System.Windows.Forms.Visualization的引用。在每个源模块中使用图表需要添加 隐藏,复制Code

    using System.Windows.Forms.DataVisualization.Charting;

    5. 参考文献 adobepdf文件规范文件可从Adobe网站下载:" PDF参考第六版,adobeportable document Format Version 1.7 2006年11月"。有关OpenType字体规范的信息可以在Microsoft Typography - OpenType规范中找到。一个匹配PDF Deflate压缩类的解压类的源代码可以在“PDF文件分析器与c#解析类”文章中获得。 6. 历史 2013/04/01: Version 1.0原始版本。2013/04/09:Version 1.1支持除句点外的十进制分隔符。2013/07/21: 1.2版本原始版本仅支持jpeg文件格式的图像资源。1.2版本支持位图类可接受的所有图像文件。看到ImageFormat类。该程序测试:Bmp, Gif,图标,Jpeg, Png和Tiff。见上文第2.3节和第3.8节。2014/02/07: 1.3版本修复PdfContents bug。(PointD P1, PointD P3)2014/03/01:版本1.4改进了对字符替换的支持。改进了对图像包含的支持。一些修复与PdfXObject相关。2014/05/05: 1.5版条码支持,不使用字体。包括四种条码:Code-128、Code-39、UPC-A和EAN-13。见第2.5节和第3.7节。创建文件后,CreateFile方法将PdfDocument重置为初始状态。(2) PdfFont对象正确释放非托管代码资源。2014/08/25: 1.7版本支持文档加密、网页链接和二维码。2014/09/12:1.8版本支持书签。2014/10/06:版本1.9支持制图,PrintDocument和图像元文件。使用除句点之外的十进制分隔符来解析区域中的数字字段。2014/12/02:版本1.10.0支持数据表。添加源代码文档。增加每个文档的最大图片数量。2015/01/12:版本1.11.0支持视频,声音和附件文件。增加对交错2 / 5条码的支持。2015/04/13:版本1.12.0支持重新排序页面和增强数据表边框线支持。2015/05/05: 1.13.0版本PDF文档输出到流。PDF表格插入分页符。图像质量的提高。支持标准128 (RC4)加密。2015/06/08: 1.14.0版本支持PDF表格内的长文本块或文本框。2015/06/17: 1.15.0版本文档信息词典。PdfImage重写。额外的图像保存选项。2015/06/18: 1.15.1版本从解决方案资源管理器中删除不使用的资源。2015/07/27: 1.16.0版本Unicode支持。提交页面的方法。1.16.1 2015/08/07:版本。修正了小(<0.0001)实数转换为字符串的问题。1.16.2 2015/09/01:版本。修正了未定义的字符。所选字体不支持所使用的字符。1.16.3 2015/09/22:版本。PdfTable构造函数使用当前页面大小计算默认的表区域矩形。当PdfTable开始一个新页面时,页面类型和方向取自前一个页面。2015/09/30:版本1.16.4一致使用IDisposable接口来释放非托管资源。2016/01/26: 1.17.0 WPF图形,透明度,颜色混合,椭圆弧线和二次贝塞尔曲线。2016/02/29: 1.17.1版本PdfTable在第一列标题为文本框时将正确显示标题。2016/03/22:版本1.17.2 PdfInfo PDF文档属性将正常显示。2016/04/14:版本1.17.3修正了在将十进制分隔符定义为非句点(逗号)的区域中使用非整数字体大小的问题。2016/05/24: 1.18.0版本命名目的地和PdfFont资源的创建。2016/06/02: 1.18.1版本重新应用1.17.3修复。2016/06/13: 1.19.0版本文档链接。对指定目的地的更改。交互式特性支持文本框和PdfTable。2016/07/27: 1.19.1版本修正:AddLocationMarker修正了十进制分隔符而不是句点的区域。2017/08/31: 1.19.2版本修复:调试工作目录不作为项目的一部分保存。BuildLocaTable方法。长格式缓冲区指针初始化。修复PdfTableCell添加值类型的DBNull。2018/07/15: 1.20.0版本修改二维码支持,每个模块增加像素数。2019/02/06: 1.21.0版本对PDF417条码的支持。2019/02/13:版本1.21.1修复PDF417条码quiet区。2019/02/18: 1.22.0版对便签的支持。2019/05/26: 1.23.0版本支持层和更改QRCode和Pdf417条形码。2019/06/06: 1.24.0版本支持图像和注释的图层控制。2019/06/20: 1.24.1版本支持米作为测量单位。版本1.25.0支持字体集合(主要是CJK字体)和非ASCII字体名称。2019/07/28:版本1.26.0支持XMP元数据和QR码ECI赋值号。 本文转载于:http://www.diyabc.com/frontweb/news269.html

  • 相关阅读:
    Java学习-060-Springboot
    PySe-013-指定安装源安装模块 + 修改安装源
    Linux-016-Centos Shell 遍历文本信息,通过流水号批量获取日志信息并保存结果
    Linux-015-Centos mysql 创建用户、数据库、授权、建表、数据插入
    Linux-014-Centos 开放端口 3306
    Linux-013-Centos mysql 5.6.50 修改字符集为 utf8
    Linux-012-Centos mysql 5.6.50 忘记密码,重置密码
    Linux-011-Centos 使用 yum 安装 mysql 5.6.50
    Linux-010-Centos 使用 yum 安装 pip
    Linux-009-Centos 安装 YUM
  • 原文地址:https://www.cnblogs.com/Dincat/p/13437338.html
Copyright © 2011-2022 走看看