Page Setting (24)
In some circumstance where we need to create a copy of the existing pages in our PDF document instead of copying the entire file, in particular, if we have to create hundreds copies of a certain page, it can be tedious to copy the page one after another. This article demonstrates a solution for how to duplicate a page in a PDF document and create multiple copies at a time using Spire.PDF.
In this example, I prepare a sample PDF file that only contains one page and eventually I’ll create ten copies of this page in the same document. Main method would be as follows:
Code Snippet:
Step 1: Create a new PDF document and load the sample file.
PdfDocument pdf = new PdfDocument("Sample.pdf");
Step 2: Get the first page from PDF, get the size of the page. Create a new instance of Pdf Template object based on the content and appearance of the first page.
PdfPageBase page = pdf.Pages[0]; SizeF size = page.Size; PdfTemplate template = page.CreateTemplate();
Step 3: Create a new PDF page with the method Pages.Add() based on the size of the first page, draw the template on the new page at the specified location. Use a for loops to get more copies of this page.
for (int i = 0; i < 10; i++) { page = pdf.Pages.Add(size, new PdfMargins(0)); page.Canvas.DrawTemplate(template, new PointF(0, 0)); }
Step 4: Save the file.
pdf.SaveToFile("Result.pdf");
Output:
Ten copies of the first page have been created in the sample PDF document.
Full Code:
using Spire.Pdf; using Spire.Pdf.Graphics; using System.Drawing; namespace DuplicatePage { class Program { static void Main(string[] args) { PdfDocument pdf = new PdfDocument("Sample.pdf"); PdfPageBase page = pdf.Pages[0]; SizeF size = page.Size; PdfTemplate template = page.CreateTemplate(); for (int i = 0; i < 10; i++) { page = pdf.Pages.Add(size, new PdfMargins(0)); page.Canvas.DrawTemplate(template, new PointF(0, 0)); } pdf.SaveToFile("Result.pdf"); } } }
Imports Spire.Pdf Imports Spire.Pdf.Graphics Imports System.Drawing Namespace DuplicatePage Class Program Private Shared Sub Main(args As String()) Dim pdf As New PdfDocument("Sample.pdf") Dim page As PdfPageBase = pdf.Pages(0) Dim size As SizeF = page.Size Dim template As PdfTemplate = page.CreateTemplate() For i As Integer = 0 To 9 page = pdf.Pages.Add(size, New PdfMargins(0)) page.Canvas.DrawTemplate(template, New PointF(0, 0)) Next pdf.SaveToFile("Result.pdf") End Sub End Class End Namespace
As a powerful PDF component, Spire.PDF supports to work with page setting for PDF well, such as set PDF properties, view preference, and set background color etc. This article will focus on show you how to add image as page background to an existing PDF file in C#.
Make sure Spire.PDF for .NET has been installed correctly and then add Spire.Pdf.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Pdf\Bin\NET4.0\ Spire.Pdf.dll".
Firstly, check the original PDF file without background image.
The following code snippet shows you how to add image as background for PDF in C#.
Step 1: Create a PDF document and load from file.
PdfDocument doc = new PdfDocument(); doc.LoadFromFile("sample.pdf");
Step 2: Get the first page in PDF file
PdfPageBase page = doc.Pages[0];
Step 3: Load the image from file and set it as background image.
Image backgroundImage = Image.FromFile("background.png"); page.BackgroundImage = backgroundImage;
Step 4: Save the document to file and launch it.
doc.SaveToFile("result.pdf"); System.Diagnostics.Process.Start("result.pdf");
Effective Screenshot:
Full Codes:
using Spire.Pdf; using System.Drawing; namespace Addimagebackground { class Program { static void Main(string[] args) { PdfDocument doc = new PdfDocument(); doc.LoadFromFile("sample.pdf"); PdfPageBase page = doc.Pages[0]; Image backgroundImage = Image.FromFile("background.png"); page.BackgroundImage = backgroundImage; doc.SaveToFile("result.pdf"); System.Diagnostics.Process.Start("result.pdf"); } } }
Spire.PDF has a function of adding, removing the blank pages in C#. We have already shown you how to remove the blank page in a PDF file. This article will show you how to insert an empty page in a PDF file in C#. By using the Spire.PDF, we can add the blank page to any place in the PDF file you want, such as at the first, the middle of the PDF file or at the end of the PDF file. It is very easy and you only need three lines of code to accomplish this task.
Make sure Spire.PDF for .NET has been installed correctly and then add Spire.Pdf.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Pdf\Bin\NET4.0\Spire.Pdf.dll".
The following code snippet shows you how to insert an empty page in a PDF file. We will show you how to add the empty page at the end of the file and as the second page of the file.
//create a PDF document and load file PdfDocument doc = new PdfDocument(); doc.LoadFromFile("sample.pdf"); //insert blank page at the end of the PDF file doc.Pages.Add(); //insert blank page as the second page doc.Pages.Insert(1); //Save the document to file doc.SaveToFile("result.pdf");
Check the effective screenshots as below:
Add the blank page at the end of the PDF file:
Add the blank page as the second page of the PDF file:
Full codes:
using Spire.Pdf; using System; namespace InsertPage { class Program { static void Main(string[] args) { //create PdfDocument instance and load file PdfDocument doc = new PdfDocument(); doc.LoadFromFile("sample.pdf"); //insert blank page as last page doc.Pages.Add(); doc.SaveToFile("result.pdf"); doc.Close(); System.Diagnostics.Process.Start("result.pdf"); //create PdfDocument instance and load file PdfDocument doc2 = new PdfDocument(); doc2.LoadFromFile("sample.pdf"); //insert blank page as second page doc2.Pages.Insert(1); doc2.SaveToFile("result2.pdf"); doc2.Close(); System.Diagnostics.Process.Start("result2.pdf"); } } }
Counting the number of pages in a PDF file is essential for various purposes, such as determining document length, organizing content, and evaluating printing requirements. Apart from knowing page count information using PDF viewers, you can also automate the task through programming. In this article, you will learn how to use C# to get the number of pages in a PDF file 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 the Number of Pages in a PDF File in C#
Spire.PDF for .NET offers the PdfDocument.Pages.Count property to quickly count the number of pages in a PDF file without opening it. The following are the detailed steps.
- Create a PdfDocument object.
- Load a sample PDF file using PdfDocument.LoadFromFile() method.
- Count the number of pages in the PDF file using PdfDocument.Pages.Count property.
- Output the result and close the PDF.
- C#
using Spire.Pdf; namespace GetNumberOfPages { class Program { static void Main(string[] args) { //Create a PdfDocument object PdfDocument pdf = new PdfDocument(); //Load a sample PDF file pdf.LoadFromFile("Contract.pdf"); //Count the number of pages in the PDF int PageNumber = pdf.Pages.Count; Console.WriteLine("The PDF file has {0} pages", PageNumber); //Close the 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.
Page transitions display a decorative effect such as a dissolve or wipe when you’re turning pages in a document that is exported to PDF format. Page transitions are especially useful when you create a slideshow in PDF format. And Spire.PDF, a powerful .NET component specially designed for developers enables you to apply page transitions to PDF file.
A solution is introduced here to show how to apply page transitions to PDF using Spire.PDF. Spire.PDF provides you a class called PdfSection. PdfSection has a property called PageSettings. And PageSettings has a property called Transition. You can use this property to apply page transitions.
Step 1: Create a new section.
PdfSection section = doc.Sections.Add(); section.PageSettings.Size = PdfPageSize.A4;
Step 2: Create a new PdfPageTransition instance.
section.PageSettings.Transition = new PdfPageTransition();
Step 3: Set the style of page transition.
section.PageSettings.Transition.Style = PdfTransitionStyle.Fade;
You can assign any value that is defined in PdfTransitionStyle to Style.
Step 4: Set the duration of transition effect in seconds.
section.PageSettings.Transition.Duration = 3;
Step 5: Set the page's display duration.
section.PageSettings.Transition.PageDuration = 2;
Step 6: Add more sections and apply more page transitions.
section = doc.Sections.Add(); section.PageSettings.Size = PdfPageSize.A4; section.PageSettings.Transition = new PdfPageTransition(); section.PageSettings.Transition.Style = PdfTransitionStyle.Box; section.PageSettings.Transition.Motion = PdfTransitionMotion.Outward; section.PageSettings.Transition.Duration = 3; section.PageSettings.Transition.PageDuration = 2;
You can combine the type of PdfPageTransition with the property Direction and the property Dimension of PdfPageTransition to create new and flexible page transition. For example, in this step, the Style of page transition is PdfTransitionStyle.Box and the Motion of page transition is PdfTransitionMotion.Outward.
At last, save the file.
doc.SaveToFile("result.pdf");
To see page transitions in the PDF, open the PDF file in Full Screen.
Here comes to the full code:
using Spire.Pdf; using Spire.Pdf.Graphics; using System.Drawing; namespace PageTransitions { class Program { static void Main(string[] args) { PdfDocument doc = new PdfDocument(); PdfSection section = doc.Sections.Add(); section.PageSettings.Size = PdfPageSize.A4; section.PageSettings.Transition = new PdfPageTransition(); section.PageSettings.Transition.Style = PdfTransitionStyle.Fade; section.PageSettings.Transition.Duration = 3; section.PageSettings.Transition.PageDuration = 2; PdfNewPage page = section.Pages.Add(); page.BackgroundColor = Color.Blue; page.Canvas.DrawString("This is Page One.", new PdfFont(PdfFontFamily.Helvetica, 20f), new PdfSolidBrush(Color.Black), 10, 10); page = section.Pages.Add(); page.BackgroundColor = Color.Green; page.Canvas.DrawString("This is Page Two.", new PdfFont(PdfFontFamily.Helvetica, 20f), new PdfSolidBrush(Color.Black), 10, 10); section = doc.Sections.Add(); section.PageSettings.Size = PdfPageSize.A4; section.PageSettings.Transition = new PdfPageTransition(); section.PageSettings.Transition.Style = PdfTransitionStyle.Box; section.PageSettings.Transition.Motion = PdfTransitionMotion.Outward; section.PageSettings.Transition.Duration = 3; section.PageSettings.Transition.PageDuration = 2; page = section.Pages.Add(); page.BackgroundColor = Color.Orange; page.Canvas.DrawString("This is Page Three.", new PdfFont(PdfFontFamily.Helvetica, 20f), new PdfSolidBrush(Color.Black), 10, 10); page = section.Pages.Add(); page.BackgroundColor = Color.Brown; page.Canvas.DrawString("This is Page Four.", new PdfFont(PdfFontFamily.Helvetica, 20f), new PdfSolidBrush(Color.Black), 10, 10); section = doc.Sections.Add(); section.PageSettings.Size = PdfPageSize.A4; section.PageSettings.Transition = new PdfPageTransition(); section.PageSettings.Transition.Duration = 3; section.PageSettings.Transition.Style = PdfTransitionStyle.Dissolve; section.PageSettings.Transition.PageDuration = 2; page = section.Pages.Add(); page.BackgroundColor = Color.Orange; page.Canvas.DrawString("This is Page Five.", new PdfFont(PdfFontFamily.Helvetica, 20f), new PdfSolidBrush(Color.Black), 10, 10); page = section.Pages.Add(); page.BackgroundColor = Color.Navy; page.Canvas.DrawString("This is Page Six.", new PdfFont(PdfFontFamily.Helvetica, 20f), new PdfSolidBrush(Color.Black), 10, 10); doc.SaveToFile("result.pdf"); doc.Close(); } } }
A PDF document can contain multiple pages with different text content, images, or other objects. Occasionally, users may need to delete certain pages with incorrectly drawn objects or pages that are irrelevant to the topic of the document. This article will demonstrate how to programmatically delete/remove pages from 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
Delete/Remove Pages from PDF
- Create a PdfDocument object.
- Load a sample PDF document using PdfDocument.LoadFromFile() method.
- Get the pages in the PDF document using PdfDocument.Pages property.
- Delete a specified page by index using PdfPageCollection.RemoveAt(int index)method.
- Save the document to another file using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using Spire.Pdf; namespace RemovePage { class Program { static void Main(string[] args) { //Create a PdfDocument object PdfDocument document = new PdfDocument(); //Load a sample PDF document document.LoadFromFile(@"E:\Files\input.pdf"); //Remove the second page document.Pages.RemoveAt(1); //Save the result document document.SaveToFile("RemovePDFPage.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 booklet is pretty helpful when people print a huge PDF document. It enjoys special popularity among book, newspaper and magazine editors. This section will introduce a very simple way to create PDF booklet via a .NET PDF component in C#, VB.NET.
Spire.PDF for .NET is a .NET PDF library which can manipulate PDF documents without Adobe Acrobat or any third party library. Using this PDF component, you can quickly create PDF booklet in your .NET applications. After setting the PDF page width and height by a class Spire.Pdf.PdfPageSize, you can create your PDF booklet through implementing PdfDocument.CreateBooklet(string fileName, float width, float height, bool doubleSide) directly. Below picture shows the effect of this task:
Here you can quickly download Spire.PDF for .NET and install it on your system. After adding Spire.Pdf reference, please see the detail code of PDF booklet below.
Draw PDF Barcode in C#, VB.NET
using System.Drawing; using Spire.Pdf; namespace PDF_Booklet { class Program { static void Main(string[] args) { //Load a PDF file PdfDocument doc = new PdfDocument(); String srcPdf = @"..\read PDF.pdf"; //Create PDF booklet float width = PdfPageSize.A4.Width * 2; float height = PdfPageSize.A4.Height; doc.CreateBooklet(srcPdf, width, height, true); //Save pdf file. doc.SaveToFile("Booklet.pdf"); doc.Close(); //Launching the Pdf file. System.Diagnostics.Process.Start("Booklet.pdf"); } } }
Imports System.Drawing Imports Spire.Pdf Namespace PDF_Booklet Class Program Private Shared Sub Main(args As String()) 'Load a PDF file Dim doc As New PdfDocument() Dim srcPdf As [String] = "..\read PDF.pdf" 'Create PDF booklet Dim width As Single = PdfPageSize.A4.Width * 2 Dim height As Single = PdfPageSize.A4.Height doc.CreateBooklet(srcPdf, width, height, True) 'Save pdf file. doc.SaveToFile("Booklet.pdf") doc.Close() 'Launching the Pdf file. System.Diagnostics.Process.Start("Booklet.pdf") End Sub End Class End Namespace
Spire.PDF for .NET is a PDF component that enables you to create, read, edit and manipulate PDF files in C#, VB.NET
C#/VB.NET: Set Viewer Preferences and Zoom Factors for PDFs
2023-07-20 07:18:00 Written by support iceblueOptimizing the viewer preferences and zoom factors is crucial for improving the viewing experience of PDF documents. By using the appropriate viewer preferences and zoom factors, you can make your PDF documents more user-friendly, viewable and suitable for different devices and platforms. In this article, we will demonstrate how to set viewer preferences and zoom factors for PDF documents 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
Set Viewer Preferences for PDF in C# and VB.NET
Viewer preferences are settings that can be applied to a PDF document to control how it is displayed when it is opened in a PDF viewer. These preferences can affect various aspects of the viewing experience, such as the initial view, page layout, and navigation tabs.
To set the viewer preference for a PDF document using Spire.PDF for .NET, you can follow these steps:
- Initialize an instance of PdfDocument class.
- Load a PDF document using PdfDocument.LoadFromFile() method.
- Get the PdfViewerPreferences object.
- Set viewer preference for the document using the properties provided by the PdfViewerPreferences class.
- Save the result document using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using Spire.Pdf; namespace SetViewerPreference { internal class Program { static void Main(string[] args) { //Initialize an instance of PdfDocument class PdfDocument pdf = new PdfDocument(); //Load a PDF document pdf.LoadFromFile(@"Example.pdf"); //Get the PdfViewerPreferences object PdfViewerPreferences viewerPreferences = pdf.ViewerPreferences; //Set viewer preference viewerPreferences.FitWindow = false; viewerPreferences.HideMenubar = true; viewerPreferences.HideToolbar = true; viewerPreferences.CenterWindow= true; viewerPreferences.DisplayTitle = false; viewerPreferences.PageLayout = PdfPageLayout.SinglePage; viewerPreferences.PageMode = PdfPageMode.UseNone; //Save the result document pdf.SaveToFile("SetViewerPreference.pdf"); pdf.Close(); } } }
Set Zoom Factors for PDF in C# and VB.NET
The zoom factor determines the zoom level of the PDF document when it is opened. By default, most PDF viewers set the zoom factor to "Fit Page," which scales the document to fit the width of the viewer window. However, you can also set a specific zoom factor, such as 60%, 150% or 200%, depending on your needs.
To set the zoom factor for a PDF document using Spire.PDF for .NET, you can follow these steps:
- Initialize an instance of PdfDocument class.
- Load a PDF document using PdfDocument.LoadFromFile() method.
- Get a specific page using PdfDocument.Pages[int index] property.
- Initialize an instance of the PdfDestination class.
- Set the destination mode, location and zoom factor using PdfDestination.Mode and PdfDestination.Location and PdfDestination.Zoom properties.
- Initialize an instance of the PdfGoToAction class and pass the PdfDestination instance to the constructor of the class as a parameter.
- Set the action to be executed when the document is opened using PdfDocument.AfterOpenAction property.
- Save the result document using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using Spire.Pdf; using Spire.Pdf.Actions; using Spire.Pdf.General; using System.Drawing; namespace SetZoomFactor { internal class Program { static void Main(string[] args) { //Initialize an instance of the PdfDocument class PdfDocument pdf = new PdfDocument(); //Load a PDF document pdf.LoadFromFile(@"Example.pdf"); //Get the first page PdfPageBase page = pdf.Pages[0]; //Initialize an instance of the PdfDestination class PdfDestination dest = new PdfDestination(page); //Set the destination mode dest.Mode = PdfDestinationMode.Location; //Set the destination location dest.Location = new PointF(40f, 40f); //Set the zoom factor dest.Zoom = 1.5f; //Initialize an instance of the PdfGoToAction class PdfGoToAction gotoAction = new PdfGoToAction(dest); //Set the action to be executed when the document is opened pdf.AfterOpenAction = gotoAction; //Save the result document pdf.SaveToFile("SetZoomFactor.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.
PDF pagination not only enables users to add page numbers in PDF file but also can divide PDF document into sections so that some additional information such as PDF file cover, introduction or reference can be added. So PDF pagination provides great convenience for managing large files or organizing books. This section will show you a solution to paginate PDF pages via a .NET PDF component in C#, VB.NET.
Spire.PDF for .NET, a PDF component for managing PDF files, enables you to paginate PDF pages quickly with C#, VB.NET. Before expounding the main code, I want to show the screenshot of the output PDF file as below:
Here you can download Spire.PDF for .NET and install it on your system. After adding Spire.Pdf dll, let us start to paginate PDF file together.
In the whole solution, there are three main steps to paginate PDF file. One is to draw page number; another is to draw content; the last one is to draw PDF cover so that you can add additional information. Let us see them one by one.
Paginate PDF - Draw PDF Page Number
When drawing page number, page label is also set in below method. By calling this method: DrawString(string s, PdfFontBase font, PdfBrush brush, float x, float y, PdfStringFormat format). You can not only set page label font, color, position and format. Please see detail code below:
foreach (PdfPageBase page in section.Pages) { page.Canvas.SetTransparency(0.5f); PdfBrush brush = PdfBrushes.Black; PdfPen pen = new PdfPen(brush, 0.75f); PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 9f, FontStyle.Italic), true); PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Right); format.MeasureTrailingSpaces = true; float space = font.Height * 0.75f; float x = margin.Left; float width = page.Canvas.ClientSize.Width - margin.Left - margin.Right; float y = page.Canvas.ClientSize.Height - margin.Bottom + space; page.Canvas.DrawLine(pen, x, y, x + width, y); y = y + 1; String numberLabel = String.Format("{0} of {1}", startNumber++, pageCount); page.Canvas.DrawString(numberLabel, font, brush, x + width, y, format); page.Canvas.SetTransparency(1); }
For Each page As PdfPageBase In section.Pages page.Canvas.SetTransparency(0.5!) Dim brush As PdfBrush = PdfBrushes.Black Dim pen As PdfPen = New PdfPen(brush, 0.75!) Dim font As PdfTrueTypeFont = New PdfTrueTypeFont(New Font("Arial", 9!, FontStyle.Italic), true) Dim format As PdfStringFormat = New PdfStringFormat(PdfTextAlignment.Right) format.MeasureTrailingSpaces = true Dim space As Single = (font.Height * 0.75!) Dim x As Single = margin.Left Dim width As Single = (page.Canvas.ClientSize.Width _ - (margin.Left - margin.Right)) Dim y As Single = ((page.Canvas.ClientSize.Height - margin.Bottom) _ + space) page.Canvas.DrawLine(pen, x, y, (x + width), y) y = (y + 1) Dim numberLabel As String = String.Format("{0} of {1}", startNumber++, pageCount) page.Canvas.DrawString(numberLabel, font, brush, (x + width), y, format) page.Canvas.SetTransparency(1) Next
Paginate PDF - Draw PDF Content
PDF content depends on your own like, so here I avoid coding them in detail.
Paginate PDF - Draw PDF Cover
Cover page is always the best place for adding additional information about this PDF file. In below method, I ignore adding reference content and document title, you can add cover image a class PdfImage in the PDF cover page. Please see code below:
//cover PdfBrush brush3 = PdfBrushes.Black; PdfBrush brush4 = new PdfSolidBrush(new PdfRGBColor(0xf9, 0xf9, 0xf9)); PdfImage image = PdfImage.FromFile(@"..\potala palace1.jpg"); String text = paginate_PDF.Properties.Resources.ImageDescription; float r = image.PhysicalDimension.Height / image.Height; PdfPen pen = new PdfPen(brush1, r); SizeF size = font1.MeasureString(text, image.PhysicalDimension.Width - 2); PdfTemplate template = new PdfTemplate(image.PhysicalDimension.Width + 4 * r + 4, image.PhysicalDimension.Height + 4 * r + 7 + size.Height); template.Graphics.DrawRectangle(pen, brush4, 0, 0, template.Width, template.Height);
'cover Dim brush3 As PdfBrush = PdfBrushes.Black Dim brush4 As PdfBrush = New PdfSolidBrush(New PdfRGBColor(249, 249, 249)) Dim image As PdfImage = PdfImage.FromFile("..\potala palace1.jpg") Dim text As String = paginate_PDF.Properties.Resources.ImageDescription Dim r As Single = (image.PhysicalDimension.Height / image.Height) Dim pen As PdfPen = New PdfPen(brush1, r) Dim size As SizeF = font1.MeasureString(text, (image.PhysicalDimension.Width - 2)) Dim template As PdfTemplate = New PdfTemplate((image.PhysicalDimension.Width _ + ((4 * r) _ + 4)), (image.PhysicalDimension.Height _ + ((4 * r) + (7 + size.Height)))) template.Graphics.DrawRectangle(pen, brush4, 0, 0, template.Width, template.Height)
Spire.PDF for .NET is a professional PDF component to generate, edit, read, and manipulate PDF documents in your .NET applications with C#, VB.NET.
C#/VB.NET: Add Background Color or Background Image to PDF
2023-07-17 06:14:00 Written by support iceblueIn a PDF document, the background refers to the overall visual appearance behind the content of the pages. The background can be a simple solid color or an image of your choice. Adding backgrounds to PDFs can help you add visual interest to your documents and also enhance readability. In this article, you will learn how to programmatically set the background color or image for PDF 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
Add Background Color to PDF Documents in C# and VB.NET
The PdfPageBase.BackgroundColor property offered by Spire.PDF for .NET allows you to set a solid color as the PDF background. The following are the detailed steps.
- Create a PdfDocument instance.
- Load a sample PDF file using PdfDocument.LoadFromFile() method.
- Loop through all the PDF pages and add a background color to each page using PdfPageBase.BackgroundColor property.
- Set the opacity of the background using PdfPageBase.BackgroudOpacity property.
- Save the result document using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using Spire.Pdf; using System.Drawing; namespace PDFBackgroundColor { class Program { static void Main(string[] args) { //Create a PdfDocument instance PdfDocument pdf = new PdfDocument(); //Load a sample PDF file from disk pdf.LoadFromFile("input.pdf"); //Loop through the pages in the PDF file foreach (PdfPageBase page in pdf.Pages) { //Set the background color for each page page.BackgroundColor = Color.Yellow; //Set the opacity of the background page.BackgroudOpacity = 0.1f; } //Save the result PDF file pdf.SaveToFile("BackgroundColor.pdf"); pdf.Close(); } } }
Add Background Images to PDF Documents C# and VB.NET
If you want to add an image as a background to match the document theme, you can use the PdfPageBase.BackgroundImage property. The following are the detailed steps.
- Create a PdfDocument instance.
- Load a sample PDF file using PdfDocument.LoadFromFile() method.
- Loop through all the PDF pages and add a background picture to each page using PdfPageBase.BackgroundImage property.
- Set the opacity of the background using PdfPageBase.BackgroudOpacity property.
- Save the result document using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using Spire.Pdf; using System.Drawing; namespace PDFBackgroundImage { class Program { static void Main(string[] args) { //Create a PdfDocument instance PdfDocument pdf = new PdfDocument(); //Load a sample PDF file from disk pdf.LoadFromFile("input.pdf"); //Load an image Image background = Image.FromFile("background.png"); //Loop through the pages in the PDF file foreach (PdfPageBase page in pdf.Pages) { //Set the loaded image as the background image for each page page.BackgroundImage = background; //Set the opacity of the background page.BackgroudOpacity = 0.2f; } //Save the result PDF file pdf.SaveToFile("BackgroundImage.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.