Page Setting (22)
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.
- Increase the Margins of a PDF Document in C#, VB.NET
- Decrease the Margins of a PDF Document in C#, VB.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); } } }
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); } } }
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.
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:
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()); } } }
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:
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:
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()); } } }
Horizontally and Vertically Split a PDF Page into multiple Pages in C#
2019-01-23 06:36:03 Written by support iceblueSpire.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:
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:
Vertically split:
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:
Full Code:
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"); } } }
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(); } } }
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.
- Add Left-Aligned Page Numbers in the Footer in C#
- Add Center-Aligned Page Numbers in the Footer in C#
- Add Right-Aligned Page Numbers in the Footer in C#
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.
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(); } } }
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(); } } }
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(); } } }
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.
Set page transitions for existing PDF document in C#/VB.NET
2016-06-15 03:46:12 Written by support icebluePage transitions give visual sparkle by creating a "PowerPoint-like" effect when switching between pages. Page transitions are useful when you create a slideshow in PDF format. This article will introduce how to add page transition effects to an existing PDF document using Spire.PDF.
Code Snippet:
Step 1: Initialize an object of PdfDocument class and load the sample PDF which you want to add transition effects to.
PdfDocument doc = new PdfDocument(); doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf");
Step 2: Create a new PDF document, add sections to it based on the page count of source file and transfer every individual page to a section. Spire.PDF provides PageSettings property in PdfSection class for setting transition effects, that's reason why we should add pages to sections within a new PDF document.
PdfDocument newDoc = new PdfDocument(); for (int i = 0; i < doc.Pages.Count; i++) { PdfSection secetion = newDoc.Sections.Add(); PdfPageBase page = doc.Pages[i]; PdfTemplate template = page.CreateTemplate(); PdfNewPage newpage = secetion.Pages.Add(); newpage.Canvas.DrawTemplate(template, new PointF(0 - doc.PageSettings.Margins.Left, 0- doc.PageSettings.Margins.Top)); }
Step 3: As demonstrated above, we know that each section in the new document contains a page. Then we could set transition effect for each page through PageSettings.Transition.
PdfSection secetion1 = newDoc.Sections[0]; secetion1.PageSettings.Transition.Style = PdfTransitionStyle.Cover; secetion1.PageSettings.Transition.Duration = 3; secetion1.PageSettings.Transition.PageDuration = 2; PdfSection secetion2 = newDoc.Sections[1]; secetion2.PageSettings.Transition.Style = PdfTransitionStyle.Glitter; secetion2.PageSettings.Transition.Duration = 3; secetion2.PageSettings.Transition.PageDuration = 2; PdfSection secetion3 = newDoc.Sections[2]; secetion3.PageSettings.Transition.Style = PdfTransitionStyle.Fade; secetion3.PageSettings.Transition.Duration = 3; secetion3.PageSettings.Transition.PageDuration = 2;
Step 4: Save and launch the file.
newDoc.SaveToFile("Transition.pdf", FileFormat.PDF); System.Diagnostics.Process.Start("Transition.pdf");
Output:
Full Code:
using Spire.Pdf; using Spire.Pdf.Graphics; using System.Drawing; namespace SetPageTransitions { class Program { static void Main(string[] args) { PdfDocument doc = new PdfDocument(); doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf"); PdfDocument newDoc = new PdfDocument(); for (int i = 0; i < doc.Pages.Count; i++) { PdfSection secetion = newDoc.Sections.Add(); PdfPageBase page = doc.Pages[i]; PdfTemplate template = page.CreateTemplate(); PdfNewPage newpage = secetion.Pages.Add(); newpage.Canvas.DrawTemplate(template, new PointF(0 - doc.PageSettings.Margins.Left, 0 - doc.PageSettings.Margins.Top)); } PdfSection secetion1 = newDoc.Sections[0]; secetion1.PageSettings.Transition.Style = PdfTransitionStyle.Cover; secetion1.PageSettings.Transition.Duration = 3; secetion1.PageSettings.Transition.PageDuration = 2; PdfSection secetion2 = newDoc.Sections[1]; secetion2.PageSettings.Transition.Style = PdfTransitionStyle.Glitter; secetion2.PageSettings.Transition.Duration = 3; secetion2.PageSettings.Transition.PageDuration = 2; PdfSection secetion3 = newDoc.Sections[2]; secetion3.PageSettings.Transition.Style = PdfTransitionStyle.Fade; secetion3.PageSettings.Transition.Duration = 3; secetion3.PageSettings.Transition.PageDuration = 2; newDoc.SaveToFile("Transition.pdf", FileFormat.PDF); System.Diagnostics.Process.Start("Transition.pdf"); } } }
Imports Spire.Pdf Imports Spire.Pdf.Graphics Imports System.Drawing Namespace SetPageTransitions Class Program Private Shared Sub Main(args As String()) Dim doc As New PdfDocument() doc.LoadFromFile("C:\Users\Administrator\Desktop\sample.pdf") Dim newDoc As New PdfDocument() For i As Integer = 0 To doc.Pages.Count - 1 Dim secetion As PdfSection = newDoc.Sections.Add() Dim page As PdfPageBase = doc.Pages(i) Dim template As PdfTemplate = page.CreateTemplate() Dim newpage As PdfNewPage = secetion.Pages.Add() newpage.Canvas.DrawTemplate(template, New PointF(0 - doc.PageSettings.Margins.Left, 0 - doc.PageSettings.Margins.Top)) Next Dim secetion1 As PdfSection = newDoc.Sections(0) secetion1.PageSettings.Transition.Style = PdfTransitionStyle.Cover secetion1.PageSettings.Transition.Duration = 3 secetion1.PageSettings.Transition.PageDuration = 2 Dim secetion2 As PdfSection = newDoc.Sections(1) secetion2.PageSettings.Transition.Style = PdfTransitionStyle.Glitter secetion2.PageSettings.Transition.Duration = 3 secetion2.PageSettings.Transition.PageDuration = 2 Dim secetion3 As PdfSection = newDoc.Sections(2) secetion3.PageSettings.Transition.Style = PdfTransitionStyle.Fade secetion3.PageSettings.Transition.Duration = 3 secetion3.PageSettings.Transition.PageDuration = 2 newDoc.SaveToFile("Transition.pdf", FileFormat.PDF) System.Diagnostics.Process.Start("Transition.pdf") End Sub End Class End Namespace
Enlarge PDF Margins without Changing Page Size in C#/VB.NET
2015-11-27 03:17:21 Written by support icebluePDF margins are white spaces between body contents and page edge. Unlike Word, margins in PDF document are not easy to be modified as Adobe does not provide any functionality for users to manipulate margins freely. However, you can change the page scaling (enlarge/compress content) or crop page to get fitted margins. In this article, you will learn how to enlarge PDF margins by compressing content.
Step 1: Create a PdfDocument object to load the original PDF document.
PdfDocument origDoc = new PdfDocument(); origDoc.LoadFromFile("sample.pdf");
Step 2: Create another PdfDocument object.
PdfDocument destDoc = new PdfDocument();
Step 3: Set the increments that you want to add to the margins in the existing PDF document.
float top = 50; float bottom = 50; float left = 50; float right = 50;
Step 4: Transfer the compressed content from the original document to the new PDF document.
foreach (PdfPageBase page in origDoc.Pages) { PdfPageBase newPage = destDoc.Pages.Add(page.Size, new PdfMargins(0)); newPage.Canvas.ScaleTransform((page.ActualSize.Width - left - right) / page.ActualSize.Width, (page.ActualSize.Height - top - bottom) / page.ActualSize.Height); newPage.Canvas.DrawTemplate(page.CreateTemplate(), new PointF(left, top)); }
Step 5: Save to file.
destDoc.SaveToFile("result.pdf", FileFormat.PDF);
Original PDF:
Result:
Full Code:
using Spire.Pdf; using Spire.Pdf.Graphics; using System.Drawing; namespace ChangeMargins { class Program { static void Main(string[] args) { PdfDocument origDoc = new PdfDocument(); origDoc.LoadFromFile("sample.pdf"); PdfDocument destDoc = new PdfDocument(); float top = 50; float bottom = 50; float left = 50; float right = 50; foreach (PdfPageBase page in origDoc.Pages) { PdfPageBase newPage = destDoc.Pages.Add(page.Size, new PdfMargins(0)); newPage.Canvas.ScaleTransform((page.ActualSize.Width - left - right) / page.ActualSize.Width, (page.ActualSize.Height - top - bottom) / page.ActualSize.Height); newPage.Canvas.DrawTemplate(page.CreateTemplate(), new PointF(left, top)); } destDoc.SaveToFile("result.pdf", FileFormat.PDF); } } }
Imports Spire.Pdf Imports Spire.Pdf.Graphics Imports System.Drawing Namespace ChangeMargins Class Program Private Shared Sub Main(args As String()) Dim origDoc As New PdfDocument() origDoc.LoadFromFile("sample.pdf") Dim destDoc As New PdfDocument() Dim top As Single = 50 Dim bottom As Single = 50 Dim left As Single = 50 Dim right As Single = 50 For Each page As PdfPageBase In origDoc.Pages Dim newPage As PdfPageBase = destDoc.Pages.Add(page.Size, New PdfMargins(0)) newPage.Canvas.ScaleTransform((page.ActualSize.Width - left - right) / page.ActualSize.Width, (page.ActualSize.Height - top - bottom) / page.ActualSize.Height) newPage.Canvas.DrawTemplate(page.CreateTemplate(), New PointF(left, top)) Next destDoc.SaveToFile("result.pdf", FileFormat.PDF) End Sub End Class End Namespace
In some cases, you might need to rotate PDF pages. For example, when you receive a PDF document that contains disoriented pages, you may wish to rotate the pages so you can read the document easier. In this article, you will learn how to rotate pages in PDF 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
Rotate a Specific Page in PDF using C# and VB.NET
Rotation is based on 90-degree increments. You can rotate a PDF page by 0/90/180/270 degrees. The following are the steps to rotate a PDF page:
- Create an instance of PdfDocument class.
- Load a PDF document using PdfDocument.LoadFromFile() method.
- Get the desired page by its index (zero-based) through PdfDocument.Pages[pageIndex] property.
- Get the original rotation angle of the page through PdfPageBase.Rotation property.
- Increase the original rotation angle by desired degrees.
- Apply the new rotation angle to the page through PdfPageBase.Rotation property.
- Save the result document using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using Spire.Pdf; namespace RotatePdfPage { class Program { static void Main(string[] args) { //Create a PdfDocument instance PdfDocument pdf = new PdfDocument(); //Load a PDF document pdf.LoadFromFile("Sample.pdf"); //Get the first page PdfPageBase page = pdf.Pages[0]; //Get the original rotation angle of the page int rotation = (int)page.Rotation; //Rotate the page 180 degrees clockwise based on the original rotation angle rotation += (int)PdfPageRotateAngle.RotateAngle180; page.Rotation = (PdfPageRotateAngle)rotation; //Save the result document pdf.SaveToFile("Rotate.pdf"); } } }
Rotate All Pages in PDF using C# and VB.NET
The following are the steps to rotate all pages in a PDF document:
- Create an instance of PdfDocument class.
- Load a PDF document using PdfDocument.LoadFromFile() method.
- Loop through each page in the document.
- Get the original rotation angle of the page through PdfPageBase.Rotation property.
- Increase the original rotation angle by desired degrees.
- Apply the new rotation angle to the page through PdfPageBase.Rotation property.
- Save the result document using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using Spire.Pdf; namespace RotateAllPdfPages { class Program { static void Main(string[] args) { //Create a PdfDocument instance PdfDocument pdf = new PdfDocument(); //Load a PDF document pdf.LoadFromFile("Sample.pdf"); foreach (PdfPageBase page in pdf.Pages) { //Get the original rotation angle of the page int rotation = (int)page.Rotation; //Rotate the page 180 degrees clockwise based on the original rotation angle rotation += (int)PdfPageRotateAngle.RotateAngle180; page.Rotation = (PdfPageRotateAngle)rotation; } //Save the result document pdf.SaveToFile("RotateAll.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.