C# itextsharp print pdf

When it comes to printing, I am afraid that many people are familiar with it. Both developers and non-computer professionals will be exposed to printing. There are many places where printing is used in project development. In .NET projects, there are many ways to choose printing, such as original IE web page printing, crystal report, JS plug-in printing, export document printing, and the itextSharp component mentioned today to realize PDF printing and so on.

There are many components to implement PDF printing in .NET, such as PDFsharp, Report.NET, sharpPDF, itextSharp, etc. Today, I will briefly introduce the itextSharp component.

1. Overview of itextSharp components:

1.iText is a PDF library that allows you to create, resize, inspect and maintain files in Portable Document Format (PDF):

(1). Generate files and reports based on data from XML files or databases.

(2). Create maps and books, taking advantage of the numerous interactive features available in PDF.

(3). Add bookmarks, page numbers, watermarks and other functions to existing PDF files.

(4). Split or join pages from existing PDF files; fill out interactive forms.

(5). Serve dynamically generate or manipulate PDF documents to Web browsers.

iText is used by Java, .NET, Android and GAE developers to enhance applications with PDF functionality. iTextSharp is a .NET port.

2. Some features of itextSharp:

(1). PDF generation.

(2).PDF operation (stamping watermark, merge/split PDF files,…).

(3). Fill out the PDF form.

(4).XML function.

(5). Digital signature.

The above is a brief introduction to some features of the itextSharp component. If you need more in-depth information about the itextSharp component, you can view the API documentation and itextSharp product introduction in detail. https://sourceforge.net/projects/itextsharp/.

2. Core classes and methods of itextSharp components:

When it comes to printing, the first thing we need to consider in our projects is what we need to print. In the brain, there should be a concept of document first. In the process of our programming, the word “document” is everywhere. This can be a broad concept or a narrow concept. The broad “document” refers to a container for storing some elements; the narrow “document” refers to the actual file type.

Looking specifically at the broad concept of printed “documents”, documents contain elements, nodes, and so on. When organizing printing, we need to create documents, write information such as elements and nodes, and finally combine them into the content we need to print. The itextSharp component can insert paragraphs, tables, pictures and other information, which can easily complete the functions we need to complete.

Paragraph: text in the report; Image: picture in the report; PdfPTable: table; PdfPCell: cell.

1. Document class Open () method: open the document object.

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();
  }
}

As you can see from the above code, when we open the document, we will set the document size, document margins and other information.

2. Paragraph class Add () method: add elements to the paragraph.

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<Chunk> chunks = this. Chunks;
    if (chunks. Count > 0)
    {
      Chunk chunk = chunks[chunks.Count - 1];
      base.Add(new Chunk("\
", 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<Chunk> Chunks { get; }
  int Type { get; }
}

The above add() method is to add elements to the paragraph. We can see that the parameter is an interface “IElement”. Let’s take a look at this interface next. The main element of the interface is a block. We see that when adding elements to a paragraph, you can add List, Image, Paragraph, Chunk.

3.Image.GetInstance() Gets an image instance.

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) & amp; & amp; (num2 == 0x49)) & amp; & amp; (num3 == 70))
  {
    GifImage image = new GifImage(imgb);
    return image. GetImage(1);
  }
  if ((num == 0xff) & amp; & amp; (num2 == 0xd8))
  {
    return new Jpeg(imgb);
  }
  if (((num == 0) & amp; & amp; (num2 == 0)) & amp; & amp; ((num3 == 0) & amp; & amp; (num4 == 12)))
  {
    return new Jpeg2000(imgb);
  }
  if (((num == 0xff) & amp; & amp; (num2 == 0x4f)) & amp; & amp; ((num3 == 0xff) & amp; & amp; (num4 == 0x51)))
  {
    return new Jpeg2000(imgb);
  }
  if (((num == PngImage.PNGID[0]) & amp; & amp; (num2 == PngImage.PNGID[1])) & amp; & amp; ((num3 == PngImage.PNGID[2]) & amp; & amp; (num4 == PngImage.PNGID[3])))
  {
    return PngImage. GetImage(imgb);
  }
  if ((num == 0xd7) & amp; & amp; (num2 == 0xcd))
  {
    return new ImgWMF(imgb);
  }
  if ((num == 0x42) & amp; & amp; (num2 == 0x4d))
  {
    return BmpImage. GetImage(imgb);
  }
  if ((((num == 0x4d) & amp; & amp; (num2 == 0x4d)) & amp; & amp; ((num3 == 0) & amp; & amp; (num4 == 0x2a))) || (((num == 0x49) & amp; & amp; (num2 == 0x49)) & amp; & amp; ((num3 == 0x2a) & amp; & amp; (num4 == 0))))
  {
    RandomAccessFileOrArrays = 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"));
}

There are many ways to obtain image instances according to parameters in this method, for example: Image, PdfTemplate, PRIndirectReference, byte[], Stream, string, Uri, etc. The above gives the image instance of ItextSharp obtained according to Image and byte[].

4. ScaleAbsolute() of Image: Set image information.

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;
}

As can be seen from the above code, the information for setting the image mainly includes information such as height, width, and arrangement.

5. Process () method of the Anchor class: rewrite the processing method of the link.

public override bool Process(IElementListener listener)
{
  try
  {
    bool flag = (this.reference != null) & amp; & amp; this.reference.StartsWith("#");
    bool flag2 = true;
    foreach (Chunk chunk in this.Chunks)
    {
      if (((this.name != null) & amp; & amp; flag2) & amp; & amp; !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;
  }
}

As you can see from the above method, this method is rewritten in this class to process the related information of the link.

6.PageSize: Set the type of paper.

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

In the above class, we can see that we can set the type of paper to be printed, which can be selected according to the actual situation. At the bottom we see two methods, one is PageSize() to set the paper size, and the other is GetRectangle() to draw a rectangle.

The above is a brief introduction to some classes and methods of the itextSharp component. The introduction to tables, cells, etc. will not continue. Those who are interested can view the source code information by themselves.

3.itextSharp component instance:

The background, characteristics, and core classes and methods of the itextSharp component are introduced above. Here is a simple example of the operation of the itextSharp component. This example is just a brief introduction.

/// <summary>
    /// font
    /// </summary>
    private Font _font;


    /// <summary>
    /// document size
    /// </summary>
    private Rectangle_rect;


    /// <summary>
    /// document object
    /// </summary>
    private readonly Document _document;


    /// <summary>
    /// Basic font
    /// </summary>
    private BaseFont _basefont;


    /// <summary>
    /// Constructor
    /// </summary>
    public PDFOperation()
    {
      _rect = PageSize.A4;
      _document = new Document(_rect);
    }


    /// <summary>
    /// Constructor
    /// </summary>
    /// <param name="type">page size (such as "A4")</param>
    public PDFOperation(string type)
    {
      if (string. IsNullOrEmpty(type))
      {
        throw new ArgumentNullException(type);
      }
      SetPageSize(type);
      _document = new Document(_rect);
    }


    /// <summary>
    /// Constructor
    /// </summary>
    /// <param name="type">page size (such as "A4")</param>
    /// <param name="marginLeft">The distance between the content and the left border</param>
    /// <param name="marginRight">The distance between the content and the right border</param>
    /// <param name="marginTop">The distance between the content and the top border</param>
    /// <param name="marginBottom">The distance between the content and the bottom border</param>
    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);
    }




    /// <summary>
    /// set font
    /// </summary>
    public void SetBaseFont(string path)
    {
      if (string. IsNullOrEmpty(path))
      {
        throw new ArgumentNullException(path);
      }
      _basefont = BaseFont.CreateFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
    }


    /// <summary>
    /// set font
    /// </summary>
    /// <param name="size">font size</param>
    public void SetFont(float size)
    {
      _font = new Font(_basefont, size);
    }


    /// <summary>
    /// Set page size
    /// </summary>
    /// <param name="type">page size (such as "A4")</param>
    public void SetPageSize(string type)
    {
      if (string. IsNullOrEmpty(type))
      {
        throw new ArgumentNullException(type);
      }
      switch (type. Trim())
      {
        //Enumerate the required document paper size
        case "A3":
          _rect = PageSize.A3;
          break;
        case "A4":
          _rect = PageSize.A4;
          break;
        case "A8":
          _rect = PageSize.A8;
          break;
      }
    }


    /// <summary>
    /// Instantiate the document
    /// </summary>
    /// <param name="os">Document-related information (such as path, opening method, etc.)</param>
    public void GetInstance(Stream os)
    {
      if (os == null)
      {
        throw new ArgumentNullException("os");
      }
      PdfWriter. GetInstance(_document, os);
    }


    /// <summary>
    /// Open the document object
    /// </summary>
    /// <param name="os">Document-related information (such as path, opening method, etc.)</param>
    public void Open(Stream os)
    {
      if (os == null)
      {
        throw new ArgumentNullException("os");
      }
      GetInstance(os);
      _document. Open();
    }


    /// <summary>
    /// Close the open document
    /// </summary>
    public void Close()
    {
      _document. Close();
    }


    /// <summary>
    /// Add paragraph
    /// </summary>
    /// <param name="content">Content</param>
    /// <param name="fontsize">font size</param>
    public void AddParagraph(string content, float fontsize)
    {
      SetFont(fontsize);
      var pra = new Paragraph(content, _font);
      _document. Add(pra);
    }


    /// <summary>
    /// Add paragraph
    /// </summary>
    /// <param name="content">Content</param>
    /// <param name="fontsize">font size</param>
    /// <param name="alignment">Alignment (1 is centered, 0 is left, 2 is right)</param>
    /// <param name="spacingAfter">The number of blank lines after the paragraph (0 is the default value)</param>
    /// <param name="spacingBefore">The number of blank lines before the paragraph (0 is the default value)</param>
    /// <param name="multipliedLeading">line spacing (0 is the default value)</param>
    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);
    }


    /// <summary>
    /// add pictures
    /// </summary>
    /// <param name="path">Image path</param>
    /// <param name="alignment">Alignment (1 is centered, 0 is left, 2 is right)</param>
    /// <param name="newWidth">Image width (0 is the default value, if the width is larger than the page width, it will be scaled according to the ratio)</param>
    /// <param name="newHeight">Image height</param>
    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);
    }


    /// <summary>
    /// Add a link
    /// </summary>
    /// <param name="content">Link text</param>
    /// <param name="fontSize">font size</param>
    /// <param name="reference">Link URL</param>
    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);
    }


    /// <summary>
    /// Add link point
    /// </summary>
    /// <param name="content">Link text</param>
    /// <param name="fontSize">font size</param>
    /// <param name="name">Link point name</param>
    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);
    }

The above examples are relatively simple, and are mainly used to briefly introduce the usage of components. If it is necessary to make the component design more general, we can rewrite the related classes and methods of the component, and develop a set of cs or bs program to realize the graphical operation of the component, and the graphical operation generates a file template. The file template can serialize relevant information (json or binary), load the model directly in the project, and bind the data in the template to realize the dynamic configuration of pdf printing.

The development difficulty of this program is average. If you are interested, you can develop a set of tools by yourself, which can better realize the pdf printing function of our project.

4. Summary:

The above introduces the relevant information of the itextSharp component. In this series of component introductions, the introduction of the components is relatively simple. The purpose is to introduce this component to everyone. In actual development, we can choose the corresponding components according to the actual situation. There is no absolute quality of components, only suitable scenarios.

If there are any mistakes and deficiencies in the above explanation, I hope everyone will forgive me and give us more opinions and suggestions. I also hope that you will support me a lot.

Source: This article is reproduced from: http://www.qb5200.com/article/316927.html

Copyright statement: This article is collected or provided by netizens and is for learning and communication purposes only. If there is any infringement, please tell the moderator or leave a message, and this official account will be deleted immediately.

-EOF-
Technical group: Add Xiaobian WeChat dotnet999
Official account: dotnet lecture hall