如何开源.NETPDF打印组件itextSharp-创新互联

如何开源.NETPDF打印组件itextSharp,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

禹会ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联公司的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:028-86922220(备注:SSL证书合作)期待与您的合作!

提到打印,恐怕对于很多人都不会陌生,无论是开发者,还是非计算机专业的人员都会接触到打印。对于项目开发中使用到打印的地方会非常多,在.NET项目中,选择打印的方式比较多,例如原始的IE网页打印、水晶报表、JS插件实现打印、导出文档打印,以及今天提到的使用itextSharp组件实现PDF打印等等。

 在.NET中实现PDF打印的组件比较多,例如PDFsharp、Report.NET、sharpPDF、itextSharp等等,今天主要简单的介绍itextSharp组件。

一.itextSharp组件概述:

1.iText的是PDF库,它允许你创建,调整,检查和维护的可移植文档格式文件(PDF):

        (1).基于从XML文件或数据库中的数据生成文件和报告。

        (2).创建地图和书籍,利用众多的互动在PDF可用的功能。

        (3).添加书签,页码,水印等功能,以现有的PDF文件。

        (4).从现有PDF文件拆分或连接页面;填写交互式表单。

        (5).即成动态生成或操纵PDF文档到Web浏览器。

 iText所使用的的Java,.NET,Android和GAE开发人员加强与PDF功能的应用程序。iTextSharp的是.NET端口。

 2.itextSharp的一些特征:

       (1).PDF生成。

       (2).PDF操作(冲压水印,合并/拆分PDF文件,...)。

       (3).PDF表单填写。

       (4).XML功能。

       (5).数字签名。

以上是对itextSharp组件的一些特性的简单介绍,如果需要更加深入的了解itextSharp组件的相关信息,可以细致的查看API文档和itextSharp产品介绍。/tupian/20230522/>public virtual void Open() {   if (!this.close)   {     this.open = true;   }   foreach (IDocListener listener in this.listeners)   {     listener.SetPageSize(this.pageSize);     listener.SetMargins(this.marginLeft, this.marginRight, this.marginTop, this.marginBottom);     listener.Open();   } }

以上的代码可以看到,我们在打开文档的时候,会设置文档大小,文档页边距等信息。

2.Paragraph类Add()方法:向段落添加元素。

public override bool Add(IElement o)
{
  if (o is List)
  {
    List element = (List) o;
    element.IndentationLeft += this.indentationLeft;
    element.IndentationRight = this.indentationRight;
    base.Add(element);
    return true;
  }
  if (o is Image)
  {
    base.AddSpecial((Image) o);
    return true;
  }
  if (o is Paragraph)
  {
    base.Add(o);
    IList chunks = this.Chunks;
    if (chunks.Count > 0)
    {
      Chunk chunk = chunks[chunks.Count - 1];
      base.Add(new Chunk("\n", chunk.Font));
    }
    else
    {
      base.Add(Chunk.NEWLINE);
    }
    return true;
  }
  base.Add(o);
  return true;
}
public interface IElement
{
  // Methods
  bool IsContent();
  bool IsNestable();
  bool Process(IElementListener listener);
  string ToString();

  // Properties
  IList Chunks { get; }
  int Type { get; }
}

以上的add()方法是向段落添加元素,我们可以看到参数是个接口“IElement”,我们接下来看一下这个接口,接口主要元素是块。我们看到在向段落添加元素时,可以添加List,Image,Paragraph,Chunk。

   3.Image.GetInstance()获取图片实例。

public static Image GetInstance(Image image)
{
  if (image == null)
  {
    return null;
  }
  return (Image) image.GetType().GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(Image) }, null).Invoke(new object[] { image });
}

 
public static Image GetInstance(byte[] imgb)
{
  int num = imgb[0];
  int num2 = imgb[1];
  int num3 = imgb[2];
  int num4 = imgb[3];
  if (((num == 0x47) && (num2 == 0x49)) && (num3 == 70))
  {
    GifImage image = new GifImage(imgb);
    return image.GetImage(1);
  }
  if ((num == 0xff) && (num2 == 0xd8))
  {
    return new Jpeg(imgb);
  }
  if (((num == 0) && (num2 == 0)) && ((num3 == 0) && (num4 == 12)))
  {
    return new Jpeg2000(imgb);
  }
  if (((num == 0xff) && (num2 == 0x4f)) && ((num3 == 0xff) && (num4 == 0x51)))
  {
    return new Jpeg2000(imgb);
  }
  if (((num == PngImage.PNGID[0]) && (num2 == PngImage.PNGID[1])) && ((num3 == PngImage.PNGID[2]) && (num4 == PngImage.PNGID[3])))
  {
    return PngImage.GetImage(imgb);
  }
  if ((num == 0xd7) && (num2 == 0xcd))
  {
    return new ImgWMF(imgb);
  }
  if ((num == 0x42) && (num2 == 0x4d))
  {
    return BmpImage.GetImage(imgb);
  }
  if ((((num == 0x4d) && (num2 == 0x4d)) && ((num3 == 0) && (num4 == 0x2a))) || (((num == 0x49) && (num2 == 0x49)) && ((num3 == 0x2a) && (num4 == 0))))
  {
    RandomAccessFileOrArray s = null;
    try
    {
      s = new RandomAccessFileOrArray(imgb);
      Image tiffImage = TiffImage.GetTiffImage(s, 1);
      if (tiffImage.OriginalData == null)
      {
        tiffImage.OriginalData = imgb;
      }
      return tiffImage;
    }
    finally
    {
      if (s != null)
      {
        s.Close();
      }
    }
  }
  throw new IOException(MessageLocalization.GetComposedMessage("the.byte.array.is.not.a.recognized.imageformat"));
}

该方法根据参数获取图片实例的方式比较多,例如:Image,PdfTemplate,PRIndirectReference,byte[],Stream,string ,Uri等等,以上给出了根据Image和byte[]获取ItextSharp的image实例。

 4.Image的ScaleAbsolute():设置图片信息。

public void ScaleAbsolute(float newWidth, float newHeight)
{
  this.plainWidth = newWidth;
  this.plainHeight = newHeight;
  float[] matrix = this.Matrix;
  this.scaledWidth = matrix[6] - matrix[4];
  this.scaledHeight = matrix[7] - matrix[5];
  this.WidthPercentage = 0f;
}

 以上代码可以看出,设置图片的信息主要包括高度、宽度、排列等信息。

 5.Anchor类的Process()方法:重写链接的处理方法。

public override bool Process(IElementListener listener)
{
  try
  {
    bool flag = (this.reference != null) && this.reference.StartsWith("#");
    bool flag2 = true;
    foreach (Chunk chunk in this.Chunks)
    {
      if (((this.name != null) && flag2) && !chunk.IsEmpty())
      {
        chunk.SetLocalDestination(this.name);
        flag2 = false;
      }
      if (flag)
      {
        chunk.SetLocalGoto(this.reference.Substring(1));
      }
      else if (this.reference != null)
      {
        chunk.SetAnchor(this.reference);
      }
      listener.Add(chunk);
    }
    return true;
  }
  catch (DocumentException)
  {
    return false;
  }
}

以上方法可以看到,该方法是在本类中被重写,用以处理链接的相关信息。

6.PageSize:设置纸张的类型

public class PageSize
{
  // Fields
  public static readonly Rectangle _11X17;
  public static readonly Rectangle A0;
  public static readonly Rectangle A1;
  public static readonly Rectangle A10;
  public static readonly Rectangle A2;
  public static readonly Rectangle A3;
  public static readonly Rectangle A4;
  public static readonly Rectangle A4_LANDSCAPE;
  public static readonly Rectangle A5;
  public static readonly Rectangle A6;
  public static readonly Rectangle A7;
  public static readonly Rectangle A8;
  public static readonly Rectangle A9;
  public static readonly Rectangle ARCH_A;
  public static readonly Rectangle ARCH_B;
  public static readonly Rectangle ARCH_C;
  public static readonly Rectangle ARCH_D;
  public static readonly Rectangle ARCH_E;
  public static readonly Rectangle B0;
  public static readonly Rectangle B1;
  public static readonly Rectangle B10;
  public static readonly Rectangle B2;
  public static readonly Rectangle B3;
  public static readonly Rectangle B4;
  public static readonly Rectangle B5;
  public static readonly Rectangle B6;
  public static readonly Rectangle B7;
  public static readonly Rectangle B8;
  public static readonly Rectangle B9;
  public static readonly Rectangle CROWN_OCTAVO;
  public static readonly Rectangle CROWN_QUARTO;
  public static readonly Rectangle DEMY_OCTAVO;
  public static readonly Rectangle DEMY_QUARTO;
  public static readonly Rectangle EXECUTIVE;
  public static readonly Rectangle FLSA;
  public static readonly Rectangle FLSE;
  public static readonly Rectangle HALFLETTER;
  public static readonly Rectangle ID_1;
  public static readonly Rectangle ID_2;
  public static readonly Rectangle ID_3;
  public static readonly Rectangle LARGE_CROWN_OCTAVO;
  public static readonly Rectangle LARGE_CROWN_QUARTO;
  public static readonly Rectangle LEDGER;
  public static readonly Rectangle LEGAL;
  public static readonly Rectangle LEGAL_LANDSCAPE;
  public static readonly Rectangle LETTER;
  public static readonly Rectangle LETTER_LANDSCAPE;
  public static readonly Rectangle NOTE;
  public static readonly Rectangle PENGUIN_LARGE_PAPERBACK;
  public static readonly Rectangle PENGUIN_SMALL_PAPERBACK;
  public static readonly Rectangle POSTCARD;
  public static readonly Rectangle ROYAL_OCTAVO;
  public static readonly Rectangle ROYAL_QUARTO;
  public static readonly Rectangle SMALL_PAPERBACK;
  public static readonly Rectangle TABLOID;

  // Methods
  static PageSize();
  public PageSize();
  public static Rectangle GetRectangle(string name);
}

以上的类中,我们可以看到我们可以设置需要打印的纸张类型,根据实际情况可以选择。在最下面我们看到了两种方法,一个是PageSize()设置纸张大小,一个是GetRectangle()绘制矩形。

以上是对itextSharp组件的一些类和方法的简单介绍,对于表格,单元格等等类的介绍就不再继续,有兴趣的可以自己查看源代码信息。

三.itextSharp组件实例:

上面介绍了itextSharp组件的背景、特性,以及组件的核心类和方法,在这里给出一个简单的itextSharp组件操作的实例,这个实例只是一个简单的介绍。

 /// 
    /// 字体
    /// 
    private Font _font;

    /// 
    /// 文档大小
    /// 
    private Rectangle _rect;

    /// 
    /// 文档对象
    /// 
    private readonly Document _document;

    /// 
    /// 基础字体
    /// 
    private BaseFont _basefont;

    /// 
    /// 构造函数
    /// 
    public PDFOperation()
    {
      _rect = PageSize.A4;
      _document = new Document(_rect);
    }

    /// 
    /// 构造函数
    /// 
    /// 页面大小(如"A4")
    public PDFOperation(string type)
    {
      if (string.IsNullOrEmpty(type))
      {
        throw new ArgumentNullException(type);
      }
      SetPageSize(type);
      _document = new Document(_rect);
    }

    /// 
    /// 构造函数
    /// 
    /// 页面大小(如"A4")
    /// 内容距左边框距离
    /// 内容距右边框距离
    /// 内容距上边框距离
    /// 内容距下边框距离
    public PDFOperation(string type, float marginLeft, float marginRight, float marginTop, float marginBottom)
    {
      if (string.IsNullOrEmpty(type))
      {
        throw new ArgumentNullException(type);
      }
      SetPageSize(type);
      _document = new Document(_rect, marginLeft, marginRight, marginTop, marginBottom);
    }


    /// 
    /// 设置字体
    /// 
    public void SetBaseFont(string path)
    {
      if (string.IsNullOrEmpty(path))
      {
        throw new ArgumentNullException(path);
      }
      _basefont = BaseFont.CreateFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
    }

    /// 
    /// 设置字体
    /// 
    /// 字体大小
    public void SetFont(float size)
    {
      _font = new Font(_basefont, size);
    }

    /// 
    /// 设置页面大小
    /// 
    /// 页面大小(如"A4")
    public void SetPageSize(string type)
    {
      if (string.IsNullOrEmpty(type))
      {
        throw new ArgumentNullException(type);
      }
      switch (type.Trim())
      {
        //枚举需要的文档纸张大小
        case "A3":
          _rect = PageSize.A3;
          break;
        case "A4":
          _rect = PageSize.A4;
          break;
        case "A8":
          _rect = PageSize.A8;
          break;
      }
    }

    /// 
    /// 实例化文档
    /// 
    /// 文档相关信息(如路径,打开方式等)
    public void GetInstance(Stream os)
    {
      if (os == null)
      {
        throw new ArgumentNullException("os");
      }
      PdfWriter.GetInstance(_document, os);
    }

    /// 
    /// 打开文档对象
    /// 
    /// 文档相关信息(如路径,打开方式等)
    public void Open(Stream os)
    {
      if (os == null)
      {
        throw new ArgumentNullException("os");
      }
      GetInstance(os);
      _document.Open();
    }

    /// 
    /// 关闭打开的文档
    /// 
    public void Close()
    {
      _document.Close();
    }

    /// 
    /// 添加段落
    /// 
    /// 内容
    /// 字体大小
    public void AddParagraph(string content, float fontsize)
    {
      SetFont(fontsize);
      var pra = new Paragraph(content, _font);
      _document.Add(pra);
    }

    /// 
    /// 添加段落
    /// 
    /// 内容
    /// 字体大小
    /// 对齐方式(1为居中,0为居左,2为居右)
    /// 段后空行数(0为默认值)
    /// 段前空行数(0为默认值)
    /// 行间距(0为默认值)
    public void AddParagraph(string content, float fontsize, int alignment, float spacingAfter, float spacingBefore, float multipliedLeading)
    {
      SetFont(fontsize);
      var pra = new Paragraph(content, _font)
      {
        Alignment = alignment
      };
      if (spacingAfter != 0)
      {
        pra.SpacingAfter = spacingAfter;
      }
      if (spacingBefore != 0)
      {
        pra.SpacingBefore = spacingBefore;
      }
      if (multipliedLeading != 0)
      {
        pra.MultipliedLeading = multipliedLeading;
      }
      _document.Add(pra);
    }

    /// 
    /// 添加图片
    /// 
    /// 图片路径
    /// 对齐方式(1为居中,0为居左,2为居右)
    /// 图片宽(0为默认值,如果宽度大于页宽将按比率缩放)
    /// 图片高
    public void AddImage(string path, int alignment, float newWidth, float newHeight)
    {
      if (string.IsNullOrEmpty(path))
      {
        throw new ArgumentNullException(path);
      }
      var img = Image.GetInstance(path);
      img.Alignment = alignment;
      // ReSharper disable once CompareOfFloatsByEqualityOperator
      if (newWidth != 0)
      {
        img.ScaleAbsolute(newWidth, newHeight);
      }
      else
      {
        if (img.Width > PageSize.A4.Width)
        {
          img.ScaleAbsolute(_rect.Width, img.Width * img.Height / _rect.Height);
        }
      }
      _document.Add(img);
    }

    /// 
    /// 添加链接
    /// 
    /// 链接文字
    /// 字体大小
    /// 链接地址
    public void AddAnchorReference(string content, float fontSize, string reference)
    {
      if (string.IsNullOrEmpty(content))
      {
        throw new ArgumentNullException(content);
      }
      SetFont(fontSize);
      var auc = new Anchor(content, _font)
      {
        Reference = reference
      };
      _document.Add(auc);
    }

    /// 
    /// 添加链接点
    /// 
    /// 链接文字
    /// 字体大小
    /// 链接点名
    public void AddAnchorName(string content, float fontSize, string name)
    {
      if (string.IsNullOrEmpty(content))
      {
        throw new ArgumentNullException(content);
      }
      SetFont(fontSize);
      var auc = new Anchor(content, _font)
      {
        Name = name
      };
      _document.Add(auc);
    }

以上的实例比较的简单,主要是用作简单介绍组件的用法。如果需要将组件设计的更加通用,我们可以将组件的相关类和方法重写,并且可以开发一套cs或者bs程序,实现组件的图形化操作,图形化操作生成文件模板。文件模板可以将相关信息序列化(json或者二进制),在项目中直接加载模型,并将数据绑定在模板中,实现pdf打印的动态配置。

这个程序的开发难度一般,如果有兴趣的可以自行开发一套工具,可以更好的实现我们的项目pdf打印功能。

上面介绍了itextSharp组件的相关信息,在这个系列的组件介绍中,对于组件的介绍都是比较的简单,旨在向大家介绍这个组件,在实际的开发中,我们可以根据实际情况自行选择相应的组件,组件没有绝对的好坏,只有合适的场景。

关于如何开源.NETPDF打印组件itextSharp问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注创新互联行业资讯频道了解更多相关知识。


网页标题:如何开源.NETPDF打印组件itextSharp-创新互联
网页URL:http://myzitong.com/article/cchoph.html