Page Setting

Page Setting (24)

C#: Copy Pages in PDF

2024-10-10 01:03:29 Written by support iceblue

Copying PDF pages facilitates better organization of information. By copying pages that contain important sections and then compiling them into a new document, you can bring together relevant content from different sources to create a cohesive resource that is easy to navigate. In this article, you will learn how to copy pages in PDF in C# using Spire.PDF for .NET.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Copy Pages within the Same PDF in C#

To duplicate PDF pages, you can first create template based on a specified page in PDF, and then draw the template on a newly added page through the PdfPageBase.Canvas.DrawTemplate() method. The following are the detailed steps.

  • Create a PdfDocument instance.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Get a specified page using PdfDocument.Pages[] property.
  • Get the size of the page using PdfPageBase.Size property.
  • Create a template based on the page using PdfPageBase.CreateTemplate() method.
  • Add a new page of the same size at the end using PdfDocument.Pages.Add(SizeF size, PdfMargins margins) method. Or you can insert a new page of the same size at a specified location using PdfDocument.Pages.Insert(int index, SizeF size, PdfMargins margins) method.
  • Draw template on the newly added page using PdfPageBase.Canvas.DrawTemplate(PdfTemplate template, PointF location) method.
  • Save the result file using PdfDocument.SaveToFile() method.
  • C#
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace DuplicatePage
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument instance
            PdfDocument pdf = new PdfDocument();

            //Load a PDF file
            pdf.LoadFromFile("Butterflies.pdf");

            //Get the first page
            PdfPageBase page = pdf.Pages[0];

            //Get the size of the page
            SizeF size = page.Size;

            //Create a template based on the page
            PdfTemplate template = page.CreateTemplate();

            //Add a new page the same size as the first page
            page = pdf.Pages.Add(size, new PdfMargins(0));
            //Insert a new page at the specified location
            //page = pdf.Pages.Insert(1, size, new PdfMargins(0));

            //Draw the template on the newly added page
            page.Canvas.DrawTemplate(template, new PointF(0, 0));

            //Save the PDF file
            pdf.SaveToFile("CopyPDFPages.pdf");
        }
    }
}

C#: Copy Pages in PDF

Copy Pages from One PDF to Another in C#

Spire.PDF for .NET also allows you to load two PDF files, create templates based on the pages in one PDF file, and then draw them onto the pages in another PDF file. The following are the detailed steps.

  • Create a PdfDocument instance.
  • Load two PDF files using PdfDocument.LoadFromFile() method.
  • Get a specified page in the first PDF using PdfDocument.Pages[] property.
  • Get the size of the page using PdfPageBase.Size property.
  • Create a template based on the page using PdfPageBase.CreateTemplate() method.
  • Insert a new page of the same size at a specified location in the second PDF using PdfDocument.Pages.Insert(int index, SizeF size, PdfMargins margins) method. Or you can add a new page of the same size at the end of the second PDF using PdfDocument.Pages.Add(SizeF size, PdfMargins margins) method.
  • Draw template on the newly added page using PdfPageBase.Canvas.DrawTemplate(PdfTemplate template, PointF location) method.
  • Save the result file using PdfDocument.SaveToFile() method.
  • C#
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace CopyPageToAnother
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load the first PDF file
            PdfDocument pdf1 = new PdfDocument();
            pdf1.LoadFromFile("Butterflies.pdf");

            //Load the second PDF file
            PdfDocument pdf2 = new PdfDocument();
            pdf2.LoadFromFile("SamplePDF.pdf");

            //Get the first page in the first PDF file
            PdfPageBase page = pdf1.Pages[0];

            //Get the size of the page
            SizeF size = page.Size;

            //Create a template based on the page
            PdfTemplate template = page.CreateTemplate();

            //Insert a new page at a specified location in the second PDF file
            PdfPageBase newPage = pdf2.Pages.Insert(0, size, new PdfMargins(0));

            //Add a new page at the end of the second PDF file
            //PdfPageBase newPage = pdf2.Pages.Add(size, new PdfMargins(0));

            //Draw the template on the newly added page
            newPage.Canvas.DrawTemplate(template, new PointF(0, 0));

            //Save the result file
            pdf2.SaveToFile("CopyPagesToAnotherPDF.pdf");
        }
    }
}

C#: Copy Pages in PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

C#: Crop Pages in PDF

2024-09-18 01:10:05 Written by support iceblue

PDF page cropping is particularly useful in scenarios where the original document has excessive margins or borders that are not necessary for the intended use. By cropping pages, you can preserve the designated area for specific use, making the document more efficient for sharing, printing, or digital presentations. In this article, you will learn how to crop pages in PDF in C# using Spire.PDF for .NET.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Crop a PDF Page in C#

Spire.PDF for .NET allows you specify a rectangular area, and then use the PdfPageBase.CropBox property to crop page to the specified area. The following are the detailed steps.

  • Create a PdfDocument instance.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Get a specified page using PdfDocument.Pages[] property.
  • Crop the page to the specified area using PdfPageBase.CropBox property.
  • Save the result file using PdfDocument.SaveToFile() method.
  • C#
using System.Drawing;
using Spire.Pdf;

namespace CropPDFPage
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument pdf = new PdfDocument();

            //Load a PDF file from disk
            pdf.LoadFromFile("Sample1.pdf");

            //Get the first page
            PdfPageBase page = pdf.Pages[0];

            //Crop the page by the specified area
            page.CropBox = new RectangleF(0, 300, 600, 260);

            //Save the result file
            pdf.SaveToFile("CropPDF.pdf");
            pdf.Close();
        }
    }
}

C#: Crop Pages in PDF

Crop a PDF Page and Export as an Image in C#

To accomplish this task, you can use the PdfDocument.SaveAsImage(int pageIndex, PdfImageType type) method to convert a cropped PDF page to an image. The following are the detailed steps.

  • Create a PdfDocument instance.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Get a specified page using PdfDocument.Pages[] property.
  • Crop the page to the specified area using PdfPageBase.CropBox property.
  • Convert the copped page to an image using PdfDocument.SaveAsImage() method.
  • Save the image as a PNG, JPG or BMP file using Image.Save(string filename, ImageFormat format) method.
  • C#
using System.Drawing;
using System.Drawing.Imaging;
using Spire.Pdf;
using Spire.Pdf.Graphics;

namespace CropPDFPageToImage
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument pdf = new PdfDocument();

            //Load a PDF file from disk
            pdf.LoadFromFile("Sample1.pdf");

            //Get the first page
            PdfPageBase page = pdf.Pages[0];

            //Crop the page by the specified area
            page.CropBox = new RectangleF(0, 300, 600, 260);

            //Convert the page to an image
            Image image = pdf.SaveAsImage(0, PdfImageType.Bitmap);

            //Save the image as a PNG file
            image.Save("CropPDFSaveAsImage.png", ImageFormat.Png);

            //Save the image as a JPG file
            //image.Save("ToJPG.jpg", ImageFormat.Jpeg);

            //Save the image as a BMP file
            //image.Save("ToBMP.bmp", ImageFormat.Bmp);
        }
    }
}

C#: Crop Pages in PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

In some cases, checking the size, orientation, and rotation of PDF pages can be part of the quality control process. For example, before publishing or distributing a document, you might need to verify this information to ensure that all pages in the document are correctly presented. In this article, you will learn how to get PDF page size, orientation and rotation angle in C# using Spire.PDF for .NET.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF 

Get PDF Page Size in C#

Spire.PDF for .NET offers the PdfPageBase.Size.Width and PdfPageBase.Size.Height properties to get the width and height of a PDF page in points. If you want to convert the default unit of measure to other units, you can use the PdfUnitConvertor class. The following are the detailed steps.

  • Create a PdfDocument instance.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Get a specified page using PdfDocument.Pages[] property.
  • Get the width and height of the PDF page using PdfPageBase.Size.Width and PdfPageBase.Size.Height properties.
  • Create a PdfUnitConvertor instance, and then convert the size units from points to other units of measure using PdfUnitConvertor.ConvertUnits() method.
  • Add the page size information to a StringBuilder instance, and then save the result to a TXT file.
  • C#
using System.Text;
using Spire.Pdf;
using Spire.Pdf.Graphics;

namespace GetPDFPageSize
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument pdf = new PdfDocument();

            //Load a PDF file from disk
            pdf.LoadFromFile("SamplePDF.pdf");

            //Get the first page 
            PdfPageBase page = pdf.Pages[0];

            //Get the width and height of the page in "point"
            float pointWidth = page.Size.Width;
            float pointHeight = page.Size.Height;

            //Create PdfUnitConvertor to convert the unit
            PdfUnitConvertor unitCvtr = new PdfUnitConvertor();

            //Convert size units from points to pixels
            float pixelWidth = unitCvtr.ConvertUnits(pointWidth, PdfGraphicsUnit.Point, PdfGraphicsUnit.Pixel);
            float pixelHeight = unitCvtr.ConvertUnits(pointHeight, PdfGraphicsUnit.Point, PdfGraphicsUnit.Pixel);

            //Convert size units from points to inches
            float inchWidth = unitCvtr.ConvertUnits(pointWidth, PdfGraphicsUnit.Point, PdfGraphicsUnit.Inch);
            float inchHeight = unitCvtr.ConvertUnits(pointHeight, PdfGraphicsUnit.Point, PdfGraphicsUnit.Inch);

            //Convert size units from points to centimeters
            float centimeterWidth = unitCvtr.ConvertUnits(pointWidth, PdfGraphicsUnit.Point, PdfGraphicsUnit.Centimeter);
            float centimeterHeight = unitCvtr.ConvertUnits(pointHeight, PdfGraphicsUnit.Point, PdfGraphicsUnit.Centimeter);

            //Create a StringBuilder instance 
            StringBuilder content = new StringBuilder();

            //Add the page size information to the StringBuilder instance 
            content.AppendLine("The page size of the file in points is (width: " + pointWidth + "pt, height: " + pointHeight + "pt).");
            content.AppendLine("The page size of the file in pixels is (width: " + pixelWidth + "pixel, height: " + pixelHeight + "pixel).");
            content.AppendLine("The page size of the file in inches is (width: " + inchWidth + "inch, height: " + inchHeight + "inch).");
            content.AppendLine("The page size of the file in centimeters is (width: " + centimeterWidth + "cm, height: " + centimeterHeight + "cm).");

            //Save to a txt file
            File.WriteAllText("GetPageSize.txt", content.ToString());
        }
    }
}

C#: Get Page Size, Orientation and Rotation of PDF

Detect PDF Page Orientation in C#

To detect the orientation of a PDF page, you can compare the width and height of the page. If the page width is greater than the height, then the page orientation is landscape, otherwise it is portrait. The following are the detailed steps.

  • Create a PdfDocument instance.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Get a specified page using PdfDocument.Pages[] property.
  • Get the width and height of the PDF page using PdfPageBase.Size.Width and PdfPageBase.Size.Height properties.
  • Compare the values of page width and height to detect the page orientation.
  • Output the result using Console.WriteLine() method.
  • C#
using Spire.Pdf;

namespace GetPDFPageOrientation
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument pdf = new PdfDocument();

            //Load a PDF file from disk
            pdf.LoadFromFile("SamplePDF.pdf");

            //Get the first page 
            PdfPageBase page = pdf.Pages[0];

            //Get the width and height of the page
            float width = page.Size.Width;
            float height = page.Size.Height;

            //Compare the values of page width and height 
            if (width > height)
            {
                Console.WriteLine("The page orientation is Landscape.");
            }

            else
            {
                Console.WriteLine("The page orientation is Portrait.");
            }
        }
    }
}

C#: Get Page Size, Orientation and Rotation of PDF

Detect PDF Page Rotation Angle in C#

The rotation angle of a PDF page can be obtained through the PdfPageBase.Rotation property. The following are the detailed steps.

  • Create a PdfDocument instance.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Get a specified page using PdfDocument.Pages[] property.
  • Get the rotation angle of the page using PdfPageBase.Rotation property, and then convert it to text string.
  • Output the result using Console.WriteLine() method.
  • C#
using Spire.Pdf;

namespace GetPDFPageRotationAngle
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument pdf = new PdfDocument();

            //Load a PDF file from disk
            pdf.LoadFromFile("E:\\PythonPDF\\Sample.pdf");

            //Get the first page 
            PdfPageBase page = pdf.Pages[0];

            //Get the rotation angle of the current page
            PdfPageRotateAngle rotationAngle = page.Rotation;
            string rotation = rotationAngle.ToString();

            //Output the page rotation angle information
            Console.WriteLine("The rotation angle of the current page is: " + rotation);
        }
    }
}

C#: Get Page Size, Orientation and Rotation of PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

PDF margins are blank areas between content and page edges. In most cases, we set moderate or narrow margins in order to create a compact appearance. However, if we wish to place a company logo or other relevant information in the margins, we need to make the margins a bit wider. In this article, you will learn how to increase or decrease the margins of an existing PDF document in C# and VB.NET using Spire.PDF for .NET.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Increase the Margins of a PDF Document in C#, VB.NET

The way to enlarge the margins of a PDF document is to create a new PDF that has a larger page size, and then draw the source page on the large page at the appropriate location. The following are the steps to increase the margins of a PDF document using Spire.PDF for .NET.

  • Load the original PDF document while initialing the PdfDocument object.
  • Create another PdfDocument object, which is used to create a new PDF document that has a larger page size.
  • Set the increasing values of the margins.
  • Calculate the page size of the new PDF document.
  • Loop through the pages in the original document, and create a template based on a specific page using PdfPageBase.CreateTemplate() method.
  • Add a page to the new PDF document using PdfDocument.Pages.Add() method.
  • Draw the template on the page at the coordinate (0, 0) using PdfTemplate.Draw() method.
  • Save the new PDF document to file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace IncreaseMargins
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load the original PDF document
            PdfDocument originalPdf = new PdfDocument("C:\\Users\\Administrator\\Desktop\\sample.pdf");

            //Get the first page
            PdfPageBase firstPage = originalPdf.Pages[0];

            //Create a new PdfDocument object
            PdfDocument newPdf = new PdfDocument();

            //Set increasing value of the margins
            PdfMargins margins = newPdf.PageSettings.Margins;
            margins.Top = 40;
            margins.Bottom=40;
            margins.Left=40;
            margins.Right= 40;

            //Calculate the new page size
            SizeF sizeF = new SizeF(firstPage.Size.Width + margins.Left + margins.Right, firstPage.Size.Height + margins.Top + margins.Bottom);

            //Loop through the pages in the original document
            for (int i = 0; i < originalPdf.Pages.Count; i++)
            {
                //Create a template based on a spcific page
                PdfTemplate pdfTemplate = originalPdf.Pages[i].CreateTemplate();

                //Add a page to the new PDF
                PdfPageBase page = newPdf.Pages.Add(sizeF);

                //Draw template on the page
                pdfTemplate.Draw(page, 0, 0);
            }

            //Save the new document
            newPdf.SaveToFile("IncreaseMargins.pdf", FileFormat.PDF);
        }
    }
}

C#/VB.NET: Adjust the Margins of a PDF Document

Decrease the Margins of a PDF Document in C#, VB.NET

The way to decrease the margins of a PDF is to create a new PDF that has a smaller page size, and then draw the source page on the small page at a specified coordinate. The following are the steps to decrease the margins of a PDF document using Spire.PDF for .NET.

  • Load the original PDF document while initialing the PdfDocument object.
  • Create another PdfDocument object, which is used to create a new PDF document that has a smaller page size.
  • Set the decreasing values of the margins.
  • Calculate the page size of the new PDF document.
  • Loop through the pages in the original document, and create a template based on a specific page using PdfPageBase.CreateTemplate() method.
  • Add a page to the new PDF document using PdfDocument.Pages.Add() method.
  • Draw the template on the page at a specified coordinate using PdfTemplate.Draw() method.
  • Save the new PDF document to file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace DecreaseMargins
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load the original PDF document
            PdfDocument originalPdf = new PdfDocument("C:\\Users\\Administrator\\Desktop\\sample.pdf");

            //Get the first page
            PdfPageBase firstPage = originalPdf.Pages[0]; 

            //Create a new PdfDocument object
            PdfDocument newPdf = new PdfDocument();

            //Set decreasing value
            float left = -20;
            float right = -20;
            float top = -20;
            float bottom = -20;

            //Calculate the new page size
            SizeF sizeF = new SizeF(firstPage.Size.Width + left + right, firstPage.Size.Height + top + bottom);

            //Loop through the pages in the original document
            for (int i = 0; i < originalPdf.Pages.Count; i++)
            {
                //Create a template based on a specific page
                PdfTemplate pdfTemplate = originalPdf.Pages[i].CreateTemplate();

                //Add a page to the new PDF
                PdfPageBase page = newPdf.Pages.Add(sizeF, new PdfMargins(0));

                //Draw template on the page
                pdfTemplate.Draw(page, left, top);
            }

            //Save the new document
            newPdf.SaveToFile("DecreaseMargins.pdf", FileFormat.PDF);
        }
    }
}

C#/VB.NET: Adjust the Margins of a PDF Document

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Get PDF page size in C#

2019-10-24 07:46:32 Written by support iceblue

With Spire.PDF for .NET, developers can set page size for PDF in C#. This article will demonstrates how to get the PDF page size using Spire.PDF.

Detail steps:

Step 1: Create a PdfDocument instance and load the sample.pdf file.

PdfDocument doc = new PdfDocument();
doc.LoadFromFile("Sample.pdf");

Step 2: Get the width and height of the first page in the PDF file.

PdfPageBase page = doc.Pages[0];
float pointWidth = page.Size.Width;
float pointHeight = page.Size.Height;

Step 3: Convert the size with other measurement unit, such as in Inch, Centimeter, Unit or Pixel.

//Create PdfUnitConvertor to convert the unit
PdfUnitConvertor unitCvtr = new PdfUnitConvertor();

//Convert the size with "pixel"
float pixelWidth = unitCvtr.ConvertUnits(pointWidth, PdfGraphicsUnit.Point, PdfGraphicsUnit.Pixel);
float pixelHeight = unitCvtr.ConvertUnits(pointHeight, PdfGraphicsUnit.Point, PdfGraphicsUnit.Pixel);

//Convert the size with "inch"
float inchWidth = unitCvtr.ConvertUnits(pointWidth, PdfGraphicsUnit.Point, PdfGraphicsUnit.Inch);
float inchHeight = unitCvtr.ConvertUnits(pointHeight, PdfGraphicsUnit.Point, PdfGraphicsUnit.Inch);

//Convert the size with "centimeter"
float centimeterWidth = unitCvtr.ConvertUnits(pointWidth, PdfGraphicsUnit.Point, PdfGraphicsUnit.Centimeter);
float centimeterHeight = unitCvtr.ConvertUnits(pointHeight, PdfGraphicsUnit.Point, PdfGraphicsUnit.Centimeter);

Step 4: Save to a .txt file.

//Create StringBuilder to save 
StringBuilder content = new StringBuilder();
//Add pointSize string to StringBuilder
content.AppendLine("The page size of the file is (width: " + pointWidth + "pt, height: " + pointHeight + "pt).");
content.AppendLine("The page size of the file is (width: " + pixelWidth + "pixel, height: " + pixelHeight + "pixel).");
content.AppendLine("The page size of the file is (width: " + inchWidth + "inch, height: " + inchHeight + "inch).");
content.AppendLine("The page size of the file is (width: " + centimeterWidth + "cm, height: " + centimeterHeight + "cm.)");

String output = "GetPageSize_out.txt";
//Save them to a txt file
File.WriteAllText(output, content.ToString());

Output:

Get PDF page size in C#

Full code:

using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.General;
using Spire.Pdf.Graphics;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GetPDFPageSize
{
    class Program
    {
        static void Main(string[] args)
        {

            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile("Sample.pdf");

            //Get the first page of the loaded PDF file
            PdfPageBase page = doc.Pages[0];
            //Get the width of page based on "point"
            float pointWidth = page.Size.Width;
            //Get the height of page
            float pointHeight = page.Size.Height;

            //Create PdfUnitConvertor to convert the unit
            PdfUnitConvertor unitCvtr = new PdfUnitConvertor();

            //Convert the size with "pixel"
            float pixelWidth = unitCvtr.ConvertUnits(pointWidth, PdfGraphicsUnit.Point, PdfGraphicsUnit.Pixel);
            float pixelHeight = unitCvtr.ConvertUnits(pointHeight, PdfGraphicsUnit.Point, PdfGraphicsUnit.Pixel);

            //Convert the size with "inch"
            float inchWidth = unitCvtr.ConvertUnits(pointWidth, PdfGraphicsUnit.Point, PdfGraphicsUnit.Inch);
            float inchHeight = unitCvtr.ConvertUnits(pointHeight, PdfGraphicsUnit.Point, PdfGraphicsUnit.Inch);

            //Convert the size with "centimeter"
            float centimeterWidth = unitCvtr.ConvertUnits(pointWidth, PdfGraphicsUnit.Point, PdfGraphicsUnit.Centimeter);
            float centimeterHeight = unitCvtr.ConvertUnits(pointHeight, PdfGraphicsUnit.Point, PdfGraphicsUnit.Centimeter);

            //Create StringBuilder to save 
            StringBuilder content = new StringBuilder();
            
            //Add pointSize string to StringBuilder
            content.AppendLine("The page size of the file is (width: " + pointWidth + "pt, height: " + pointHeight + "pt).");
            content.AppendLine("The page size of the file is (width: " + pixelWidth + "pixel, height: " + pixelHeight + "pixel).");
            content.AppendLine("The page size of the file is (width: " + inchWidth + "inch, height: " + inchHeight + "inch).");
            content.AppendLine("The page size of the file is (width: " + centimeterWidth + "cm, height: " + centimeterHeight + "cm.)");

            String output = "GetPageSize_out.txt";

            //Save them to a txt file
            File.WriteAllText(output, content.ToString());        

        }
    }
}

Get PDF Page Labels in C#

2019-03-26 07:12:21 Written by support iceblue

Page labels are used to identify each page visually on the screen or in print. This article demonstrates how to get the PDF page labels using Spire.PDF.

Below is the screenshot of the sample PDF document:

Get PDF Page Labels in C#

Detail steps:

Step 1: Create a PdfDocument instance and load the sample.pdf file.

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("sample.pdf");

Step 2: Get the labels of the pages in the PDF file.

StringBuilder sb = new StringBuilder();
for (int i = 0; i < pdf.Pages.Count; i++)
{
    sb.AppendLine(pdf.Pages[i].PageLabel);
}

Step 3: Save to a .txt file.

File.WriteAllText("PageLabels.txt", sb.ToString());

Output:

Get PDF Page Labels in C#

Full code:

using System.IO;
using System.Text;
using Spire.Pdf;

namespace Get_PDF_Page_Labels
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument instance
            PdfDocument pdf = new PdfDocument();
            //Load the PDF file
            pdf.LoadFromFile("sample.pdf");

            //Create a StringBuilder instance
            StringBuilder sb = new StringBuilder();
            //Get the lables of the pages in the PDF file
            for (int i = 0; i < pdf.Pages.Count; i++)
            {
                sb.AppendLine(pdf.Pages[i].PageLabel);
            }

            //Save to a .txt file
            File.WriteAllText("PageLabels.txt", sb.ToString());
        }
    }
}

Spire.PDF supports to horizontally and vertically split a PDF page into two or more pages. This article will show you how to use Spire.PDF to accomplish this function.

The sample PDF file:

Horizontally and Vertically Split a PDF Page into multiple Pages in C#

Detail steps:

Step 1: Load the sample PDF file and get the first page.

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("New Zealand.pdf");

PdfPageBase page = pdf.Pages[0];

Step 2: Create a new PDF file and remove page margins.

PdfDocument newPdf = new PdfDocument();
newPdf.PageSettings.Margins.All = 0;

Step 3: Set page width and height in order to horizontally or vertically split the first page into 2 pages.

//Horizontally Split
newPdf.PageSettings.Width = page.Size.Width;
newPdf.PageSettings.Height = page.Size.Height / 2;
//Vertically split
//newPdf.PageSettings.Width = page.Size.Width / 2;
//newPdf.PageSettings.Height = page.Size.Height;

Step 5: Add a new page to the new PDF file.

PdfPageBase newPage = newPdf.Pages.Add();

Step 6: Create layout format.

PdfTextLayout format = new PdfTextLayout();
format.Break = PdfLayoutBreakType.FitPage;
format.Layout = PdfLayoutType.Paginate;

Step 7: Create template from the first Page of the sample PDF, and draw the template to the new added page with the layout format.

page.CreateTemplate().Draw(newPage, new PointF(0, 0), format);

Step 8: Save and close.

newPdf.SaveToFile("SplitPage.pdf");
newPdf.Close();
pdf.Close();  

Horizontally split:

Horizontally and Vertically Split a PDF Page into multiple Pages in C#

Vertically split:

Horizontally and Vertically Split a PDF Page into multiple Pages in C#

Full code:

using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;

namespace SplitPDFPage
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load the sample PDF
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile("New Zealand.pdf");

            //Get the first page
            PdfPageBase page = pdf.Pages[0];

            //Create a new PDF
            PdfDocument newPdf = new PdfDocument();

            //Remove page margins
            newPdf.PageSettings.Margins.All = 0;

            //Set page width and height in order to horizontally split the first page into 2 pages
            newPdf.PageSettings.Width = page.Size.Width;
            newPdf.PageSettings.Height = page.Size.Height / 2;

            //Set page width and height in order to vertically split the first page into 2 pages
            //newPdf.PageSettings.Width = page.Size.Width / 2;
            //newPdf.PageSettings.Height = page.Size.Height;

            //Add a new page to the new PDF
            PdfPageBase newPage = newPdf.Pages.Add();

            //Create layout format
            PdfTextLayout format = new PdfTextLayout();
            format.Break = PdfLayoutBreakType.FitPage;
            format.Layout = PdfLayoutType.Paginate;

            //Create template from the first Page of the sample PDF, and draw the template to the new added page with the layout format
            page.CreateTemplate().Draw(newPage, new PointF(0, 0), format);

            //Save and close
            newPdf.SaveToFile("SplitPage.pdf");
            newPdf.Close();
            pdf.Close();                                               
        }
    }
}

A tiled background usually refers to the background that is filled with one or more repetitions of a small image. In this article, you will learn how to tile an image in PDF and make a tile background for your PDFs in C# and VB.NET.

Step 1: Create a PdfDocument object and load a sample PDF document.

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("sample.pdf");

Step 2: Load an image file to PdfImage object.

PdfImage image = PdfImage.FromFile("logo.png");

Step 3: Create a PdfTilingBrush object specifying its size, set the transparency of the brush, and draw an image at the specified position of the brush.

PdfTilingBrush brush = new PdfTilingBrush(new SizeF(pdf.Pages[1].Canvas.Size.Width / 3, pdf.Pages[1].Canvas.Size.Height / 5));
brush.Graphics.SetTransparency(0.2f);
brush.Graphics.DrawImage(image,new PointF((brush.Size.Width-image.Width)/2,(brush.Size.Height-image.Height)/2));

Step 4: Draw rectangles on the PDF page using the brush.

pdf.Pages[1].Canvas.DrawRectangle(brush, new RectangleF(new PointF(0, 0), page.Canvas.Size));

Step 5: Save the file.

pdf.SaveToFile("output.pdf");

Output:

How to Add a Tiled Background Image to PDF in C#, VB.NET

Full Code:

[C#]
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;


namespace Image
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile("sample.pdf");

            PdfImage image = PdfImage.FromFile("logo.png");
            foreach (PdfPageBase page in pdf.Pages)
            {
                PdfTilingBrush brush = new PdfTilingBrush(new SizeF(page.Canvas.Size.Width / 3, page.Canvas.Size.Height / 5));
                brush.Graphics.SetTransparency(0.2f);
                brush.Graphics.DrawImage(image, new PointF((brush.Size.Width - image.Width) / 2, (brush.Size.Height - image.Height) / 2));
                page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(0, 0), page.Canvas.Size));
            }
            pdf.SaveToFile("output.pdf");
        }
    }
}
[VB.NET]
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports System.Drawing


Namespace Image
	Class Program
		Private Shared Sub Main(args As String())
			Dim pdf As New PdfDocument()
			pdf.LoadFromFile("sample.pdf")

			Dim image As PdfImage = PdfImage.FromFile("logo.png")
			For Each page As PdfPageBase In pdf.Pages
				Dim brush As New PdfTilingBrush(New SizeF(page.Canvas.Size.Width / 3, page.Canvas.Size.Height / 5))
				brush.Graphics.SetTransparency(0.2F)
				brush.Graphics.DrawImage(image, New PointF((brush.Size.Width - image.Width) / 2, (brush.Size.Height - image.Height) / 2))
				page.Canvas.DrawRectangle(brush, New RectangleF(New PointF(0, 0), page.Canvas.Size))
			Next
			pdf.SaveToFile("output.pdf")
		End Sub
	End Class
End Namespace

For PDF documents with pages out of order, rearranging the pages can avoid confusing the reader and also make the document more organized. This article will demonstrate how to programmatically rearrange the pages in an existing PDF document using Spire.PDF for .NET.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Rearrange Pages in an Existing PDF Document

  • Create a PdfDocument object.
  • Load a sample PDF document using PdfDocument.LoadFromFile() method.
  • Get the pages in the PDF document using PdfDocument.Pages property.
  • Rearrange PDF pages using PdfPageCollection.ReArrange(int[] orderArray) method.
  • Save the document to another file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;

namespace RearrangePDF
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument pdf = new PdfDocument();

            //Load a sample PDF document
            pdf.LoadFromFile("input.pdf");

            //Rearrange pages by page index
            pdf.Pages.ReArrange(new int[] { 1, 0, 2, 3 });

            //Save the document
            pdf.SaveToFile("ChangeOrder.pdf");
            pdf.Close();
        }
    }
}

C#/VB.NET: Rearrange Pages in PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Adding page numbers to a PDF document is not only practical but also aesthetically pleasing, as it provides a polished look akin to professionally published materials. Whether you're dealing with a digital copy of a novel, a report, or any other type of lengthy document, having page numbers can significantly improve its readability and utility. In this article, you will learn how to add page numbers to a PDF document in C# using Spire.PDF for .NET.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

PDF Coordinate System

When utilizing Spire.PDF for .NET to manipulate an existing PDF document, it's important to note that the coordinate system's origin is located at the top left corner of the page. The x-axis extends to the right, while the y-axis extends downward.

Typically, page numbers are positioned within the header or footer section of a document. Therefore, it is crucial to take into account the page size and margins when determining the appropriate placement for the page numbers.

C#: Add Page Numbers to a PDF Document

Add Left-Aligned Page Numbers in the Footer in C#

In the Spire.PDF for .NET library, there are two classes available: PdfPageNumberField and PdfPageCountField. These classes allow you to retrieve and display the current page number and the total page count when they are added to a page of a PDF document. If you wish to insert text such as "Page X" or "Page X of Y", you can utilize the PdfCompositeField class, which enables you to combine the desired text with one or more fields into a single field.

The following are the steps to add left-aligned page numbers in the PDF footer using C#.

  • Create a Document object.
  • Load a PDF file from a specified page.
  • Create a PdfPageNumberField object and a PdfPageCountField object.
  • Create a PdfCompositeField object to create a "Page X of Y" format.
  • Specify the location of the PdfCompositeField object using PdfCompositeField.Location property.
  • Iterate though the pages in the document, and add "Page X of Y" to the left corner of the footer section using PdfCompositeField.Draw() method.
  • Save the document to a different PDF file.
  • C#
using Spire.Pdf.AutomaticFields;
using Spire.Pdf.Graphics;
using Spire.Pdf;
using System.Drawing;
using Spire.Pdf.License;

namespace AddPageNumbersToLeftCorner
{
    class Program
    {
        static void Main(string[] args)
        {
            // Apply your license key
            LicenseProvider.SetLicenseKey("License Key");

            // Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            // Load a PDF file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf");

            // Create font, brush and pen, which determine the appearance of the page numbers to be added
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", 12, FontStyle.Regular), true);
            PdfBrush brush = PdfBrushes.Black;
            PdfPen pen = new PdfPen(brush, 1.0f);

            // Create a PdfPageNumberField object and a PdfPageCountField object
            PdfPageNumberField pageNumberField = new PdfPageNumberField();
            PdfPageCountField pageCountField = new PdfPageCountField();

            // Create a PdfCompositeField object to combine page count field and page number field in a single field
            PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField);

            // Get the page size
            SizeF pageSize = doc.Pages[0].Size;

            // Set the location of the composite field
            compositeField.Location = new PointF(72, pageSize.Height - 45);

            // Iterate through the pages in the document
            for (int i = 0; i < doc.Pages.Count; i++)
            {

                // Get a specific page
                PdfPageBase page = doc.Pages[i];

                // Draw a line at the specified position
                page.Canvas.DrawLine(pen, 72, pageSize.Height - 50, pageSize.Width - 72, pageSize.Height - 50);

                // Draw the composite field on the page
                compositeField.Draw(page.Canvas);
            }

            // Save to a different PDF file
            doc.SaveToFile("AddPageNumbersToLeftCorner.pdf");

            // Dispose resources
            doc.Dispose();
        }
    }
}

C#: Add Page Numbers to a PDF Document

Add Center-Aligned Page Numbers in the Footer in C#

In order to align the page number in the footer section to the center, it is crucial to dynamically calculate the width of the text "Page X of Y." This calculation is essential as it determines the X coordinate of the page number (PdfCompositeField). To achieve center alignment, the X coordinate is calculated by subtracting the width of the page number from the page width and dividing the result by 2, as follows: (PageWidth - PageNumberWidth)/2.

The following are the steps to add center-aligned page numbers in the PDF footer using C#.

  • Create a Document object.
  • Load a PDF file from a specified page.
  • Create a PdfPageNumberField object and a PdfPageCountField object.
  • Create a PdfCompositeField object to create a "Page X of Y" format.
  • Specify the location of the PdfCompositeField object using PdfCompositeField.Location property.
  • Iterate though the pages in the document, and add "Page X of Y" to the center of the footer section using PdfCompositeField.Draw() method.
  • Save the document to a different PDF file.
  • C#
using Spire.Pdf.AutomaticFields;
using Spire.Pdf.Graphics;
using Spire.Pdf;
using System.Drawing;
using Spire.Pdf.License;

namespace AddPageNumbersToCenter
{
    class Program
    {
        static void Main(string[] args)
        {
            // Apply your license key
            LicenseProvider.SetLicenseKey("License Key");

            // Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            // Load a PDF file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf");

            // Create font, brush and pen, which determine the appearance of the page numbers to be added
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", 12, FontStyle.Regular), true);
            PdfBrush brush = PdfBrushes.Black;
            PdfPen pen = new PdfPen(brush, 1.0f);

            // Create a PdfPageNumberField object and a PdfPageCountField object
            PdfPageNumberField pageNumberField = new PdfPageNumberField();
            PdfPageCountField pageCountField = new PdfPageCountField();

            // Create a PdfCompositeField object to combine page count field and page number field in a single field
            PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField);


            // Iterate through the pages in the document
            for (int i = 0; i < doc.Pages.Count; i++)
            {

                // Get a specific page
                PdfPageBase page = doc.Pages[i];

                // Get the page size
                SizeF pageSize = doc.Pages[i].Size;

                // Draw a line at the specified position
                page.Canvas.DrawLine(pen, 72, pageSize.Height - 50, pageSize.Width - 72, pageSize.Height - 50);

                // Measure the size the "Page X of Y"
                SizeF pageNumberSize = font.MeasureString(string.Format("Page {0} of {1}", i + 1, doc.Pages.Count));

                // Set the location of the composite field
                compositeField.Location = new PointF((pageSize.Width - pageNumberSize.Width) / 2, pageSize.Height - 45);

                // Draw the composite field on the page
                compositeField.Draw(page.Canvas);

            }

            // Save to a different PDF file
            doc.SaveToFile("AddPageNumbersToCenter.pdf");

            // Dispose resources
            doc.Dispose();
        }
    }
}

C#: Add Page Numbers to a PDF Document

Add Right-Aligned Page Numbers in the Footer in C#

To position the page number in the footer section's right corner, it is essential to dynamically calculate the width of the text "Page X of Y" as well. Because the X coordinate of the page number (PdfCompositeField) is determined by subtracting the combined width of the page number and the right page margin from the page width, as follows: PageWidth - (PageNumberWidth + RightPageMargin).

Below are the steps to add right-aligned page numbers in the PDF footer in C#.

  • Create a Document object.
  • Load a PDF file from a specified page.
  • Create a PdfPageNumberField object and a PdfPageCountField object.
  • Create a PdfCompositeField object to create a "Page X of Y" format.
  • Specify the location of the PdfCompositeField object using PdfCompositeField.Location property.
  • Iterate though the pages in the document, and add "Page X of Y" to the right corner of the footer section using PdfCompositeField.Draw() method.
  • Save the document to a different PDF file.
  • C#
using Spire.Pdf.AutomaticFields;
using Spire.Pdf.Graphics;
using Spire.Pdf;
using System.Drawing;
using Spire.Pdf.License;

namespace AddPageNumbersToRigthCorner
{
    class Program
    {
        static void Main(string[] args)
        {
            // Apply your license key
            LicenseProvider.SetLicenseKey("License Key");

            // Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            // Load a PDF file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of service.pdf");

            // Create font, brush and pen, which determine the appearance of the page numbers to be added
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", 12, FontStyle.Regular), true);
            PdfBrush brush = PdfBrushes.Black;
            PdfPen pen = new PdfPen(brush, 1.0f);

            // Create a PdfPageNumberField object and a PdfPageCountField object
            PdfPageNumberField pageNumberField = new PdfPageNumberField();
            PdfPageCountField pageCountField = new PdfPageCountField();

            // Create a PdfCompositeField object to combine page count field and page number field in a single field
            PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField);


            // Iterate through the pages in the document
            for (int i = 0; i < doc.Pages.Count; i++)
            {

                // Get a specific page
                PdfPageBase page = doc.Pages[i];

                // Get the page size
                SizeF pageSize = doc.Pages[i].Size;

                // Draw a line at the specified position
                page.Canvas.DrawLine(pen, 72, pageSize.Height - 50, pageSize.Width - 72, pageSize.Height - 50);

                // Measure the size the "Page X of Y"
                SizeF pageNumberSize = font.MeasureString(string.Format("Page {0} of {1}", i + 1, doc.Pages.Count));

                // Set the location of the composite field
                compositeField.Location = new PointF(pageSize.Width - pageNumberSize.Width - 72, pageSize.Height - 45);

                // Draw the composite field on the page
                compositeField.Draw(page.Canvas);

            }

            // Save to a different PDF file
            doc.SaveToFile("AddPageNumbersToRigthCorner.pdf");

            // Dispose resources
            doc.Dispose();
        }
    }
}

C#: Add Page Numbers to a PDF Document

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Page 1 of 2
page 1