How C # Adds a PDF header footer

Source: Internet
Author: User
Tags pdfpen

The header footer is an important part of a complete, refined document. In the header and footer, you can render a lot of content, such as company name, page number, worksheet name, date, picture, such as logo, tag, etc. In the following article, you'll learn how to add a header footer to a PDF. With code testing, adding a header footer can be done in two ways:

    • Add a header footer to a new page by adding a new page
    • Add header footer directly to an existing document
      The following describes specific C # code actions based on both of these scenarios
      (Example for reference)
      Using tools: Free spire.pdf for. NET 4.3 (Community Edition) 1. Create a new page to add Header Footer 1.1 Add header

      "C #"

Using spire.pdf;using spire.pdf.graphics;using system.drawing;using system;namespace AddHeader_PDF{class Program { static void Main (string[] args) {//Create a new Pdfdocument class object and add a page pdfdocument PDF = new PDF            Document (); Pdfpagebase page = PDF.            Pages.Add ();            Set margin Pdfunitconvertor UNITCVTR = new Pdfunitconvertor ();            Pdfmargins margin = new Pdfmargins (); Margin.            Top = Unitcvtr.convertunits (2.54f, Pdfgraphicsunit.centimeter, Pdfgraphicsunit.point); Margin. Bottom = margin.            Top; Margin.            left = Unitcvtr.convertunits (4.17f, Pdfgraphicsunit.centimeter, Pdfgraphicsunit.point); Margin. right = margin.            Left;            Call the AddHeader () method to add the header AddHeader (PDF, pdfpagesize.a4, margin); Save and open the document PDF.            SaveToFile ("PDF header. pdf");        System.Diagnostics.Process.Start ("PDF header. pdf"); } static void AddHeader (Pdfdocument doc, SizeF pageSize,Pdfmargins margin) {//Initialize a Pdfpagetemplateelement object for creating the header pdfpagetemplateelement Headerspac E = new Pdfpagetemplateelement (pagesize.width, margin.            TOP);            Headerspace.foreground = true; Doc.            Template.top = Headerspace;            Draws text in the header section Pdftruetypefont font = new Pdftruetypefont ("Arial Unicode MS", 10f), true);            Pdfstringformat format = new Pdfstringformat (pdftextalignment.right);            String HeaderText = "World trade ORGANIZATION, WTO \ International ORGANIZATION, regulates international trade";            float x = PdfPageSize.A4.Width;            Float y = 0;            HeaderSpace.Graphics.DrawString (HeaderText, Font, Pdfbrushes.black, x, y, format);            In the header section, draw the picture pdfimage Headerimage = Pdfimage.fromfile (@ "C:\Users\Administrator\Desktop\1.png");            float width = HEADERIMAGE.WIDTH/2;            float height = HEADERIMAGE.HEIGHT/3; headerspace.gRaphics.        DrawImage (headerimage, 0, 0, width, height); }    }}

Header Add Effect:

1.2 Adding a footer

"C #"

Using spire.pdf;using spire.pdf.graphics;using system.drawing;using system;using Spire.Pdf.AutomaticFields; Namespace addfooter_pdf{class Program {static void Main (string[] args) {//Create a new Pdfdocumen            Class T object, add a page pdfdocument doc = new pdfdocument (); Pdfpagebase page = doc.            Pages.Add ();            Set margin Pdfunitconvertor UNITCVTR = new Pdfunitconvertor ();            Pdfmargins margin = new Pdfmargins (); Margin.            Top = Unitcvtr.convertunits (2.54f, Pdfgraphicsunit.centimeter, Pdfgraphicsunit.point); Margin. Bottom = margin.            Top; Margin.            left = Unitcvtr.convertunits (4.17f, Pdfgraphicsunit.centimeter, Pdfgraphicsunit.point); Margin. right = margin.            Left;            Call the Addfooter () method to add a footer Addfooter (doc, pdfpagesize.a4, margin);            Call the Addpagenumber () method to add the page number Addpagenumber (doc, margin); Save and open document Doc.            SaveToFile ("PDF footer. pdf"); System.diagNostics.        Process.Start ("PDF footer. pdf"); } static void Addfooter (Pdfdocument doc, SizeF pageSize, pdfmargins margin) {//Initialize a Pdfpagetempl The Ateelement object that is used to create the footer pdfpagetemplateelement footerspace = new Pdfpagetemplateelement (pagesize.width, margin.            Bottom);            Footerspace.foreground = true; Doc.            Template.bottom = Footerspace;            Draws text in the footer section Pdftruetypefont font = new Pdftruetypefont ("Arial Unicode MS", 10f), true);            Pdfstringformat format = new Pdfstringformat (pdftextalignment.center);            String headerText = "Website:www.wto.org";            float x = PDFPAGESIZE.A4.WIDTH/2;            Float y = 0;        FooterSpace.Graphics.DrawString (HeaderText, Font, Pdfbrushes.black, x, y, format); } static void Addpagenumber (Pdfdocument doc, pdfmargins margin) {//Add page number to footer section foreach (Pdfpagebase page in Doc.) Pages) {pdfstringFormat format1 = new Pdfstringformat (pdftextalignment.left); int x1 = Convert.ToInt32 (page.                CANVAS.CLIENTSIZE.WIDTH/2); int y1 = Convert.ToInt32 (page. Canvas.clientsize.height-margin.                Bottom + 20);                Rectangle bounds = new Rectangle (x1, Y1, 20, 20);                Pdfpagenumberfield field = new Pdfpagenumberfield ();                Pdftruetypefont font = new Pdftruetypefont (New Font ("Arial Unicode MS", 10f), true); Field.                Font = font; Field.                StringFormat = FORMAT1; Field.                Brush = Pdfbrushes.black; Field.                Bounds = Bounds; Field. Draw (page.            Canvas); }        }    }}

Footer Add Effect:

2. Add a header footer to an existing PDF document

"C #"

Using spire.pdf;using spire.pdf.automaticfields;using spire.pdf.graphics;using system;using System.Drawing;            Namespace pdfheader{class Program {static void Main (string[] args) {//Load a test document            Pdfdocument existingpdf = new Pdfdocument ();            Existingpdf.loadfromfile ("Test.pdf");            Call the Drawheader method to add a header Drawheader (existingpdf) to an existing document;            Call the Drawfooter method to add a footer Drawfooter (existingpdf) to an existing document;            Save and open the document Existingpdf.savetofile ("Output.pdf");        System.Diagnostics.Process.Start ("Output.pdf"); }//Draw header static void Drawheader (Pdfdocument doc) {//Get page Size SizeF page in blank area above Size = doc. Pages[0].            Size;            Declares X, y two float-type variable float x = 90;            Float y = 20; for (int i = 0; i < Doc. Pages.count; i++) {//Draw a picture at the specified location on each page pdfimage headerimage = pdfimage.fromfile ("Logo.png");                float width = HEADERIMAGE.WIDTH/7;                float height = HEADERIMAGE.HEIGHT/7; Doc. Pages[i].                Canvas.drawimage (Headerimage, x, y, width, height);                Draw a horizontal line at the specified position on each page PDFpen pen = new PDFpen (Pdfbrushes.gray, 0.5f); Doc. Pages[i].            Canvas.drawline (pen, x, y + height + 2, pagesize.width-x, y + height + 2); }}//Draw footer in blank area below page static void Drawfooter (Pdfdocument doc) {//Get page size S Izef pageSize = doc. Pages[0].            Size;            Declares X, y two float-type variable float x = 90;            Float y = pagesize.height-72; for (int i = 0; i < Doc. Pages.count;                i++) {//Draw horizontal PDFpen pen = new PDFpen (Pdfbrushes.gray, 0.5f) at the specified position on each page; Doc. Pages[i].                Canvas.drawline (pen, x, Y, pagesize.width-x, y);                Draws the text at the specified position on each page y = y + 5; Pdftruetypefont font = new PdftruEtypefont (New Font ("Blackbody", 10f, FontStyle.Bold), true);                Pdfstringformat format = new Pdfstringformat (pdftextalignment.left);                String footertext = "website\n https://g20.org/"; Doc. Pages[i].                                 Canvas.drawstring (Footertext, Font, Pdfbrushes.black, x, y, format);                At the specified position on each page, the current page number and the total page pdfpagenumberfield number = new Pdfpagenumberfield ();                Pdfpagecountfield count = new Pdfpagecountfield ();                Pdfcompositefield Compositefield = new Pdfcompositefield (font, Pdfbrushes.black, "{0}/{1}", number, count);                Compositefield.stringformat = new Pdfstringformat (pdftextalignment.right, pdfverticalalignment.top); SizeF size = font.                MeasureString (Compositefield.text); Compositefield.bounds = new RectangleF (pagesize.width-x-size. Width, y, size. Width, size.                Height); Compositefield.draw (Doc. Pages[i].            Canvas); }        }    }}

Test results:

The above is the entire content of the C # Add PDF header Footer, the two cases of the example method, you can choose to use the reference.
The end of this article.
(If you need to reprint, please specify the source)

How C # Adds a PDF header footer

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.