Making PDF Forms Non-Editable in Java

When a PDF form is made non-editable, its interactive capability is removed, so the field data appears as regular text and cannot be edited. This is very useful when we want to archive or distribute PDF documents containing forms. In this article, I will demonstrate how to make PDF forms non-editable in Java using Free Spire.PDF for Java.

Add Dependencies

If you are using maven, you can install the jar of Free Spire.PDF for Java into your project by adding the following code to your project’s pom.xml file.

<repositories>    
    <repository>    
        <id>com.e-iceblue</id>    
        <name>e-iceblue</name>    
        <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>    
    </repository>    
</repositories>    
<dependencies>    
    <dependency>    
        <groupId> e-iceblue </groupId>    
        <artifactId>spire.pdf.free</artifactId>    
        <version>5.1.0</version>    
    </dependency>    
</dependencies>

If you are not using maven, you can download Free Spire.PDF for Java from this website, unzip the package and then import the Spire.Pdf.jar under the lib folder into your project as a dependency.

Making PDF Forms Non-Editable in Java

There are two ways to make PDF forms non-editable, they are: flatten the forms and make the forms read only.

Example 1. Flatten PDF Forms in Java

The following are the steps to flatten all the forms in a PDF document:

  • Load a PDF document by initializing an instance of PdfDocument class and passing the file path to the class’s constructor as a parameter.
  • Flatten all the forms in the document using PdfDocument.getForm().isFlatten(true) method.
  • Save the result document using PdfDocument.saveToFile() method.

Code example:

import com.spire.pdf.PdfDocument;

public class FlattenForms {
    public static void main(String[] args){
        //Load a PDF document
        PdfDocument doc = new PdfDocument("FormFields.pdf");

        //Flatten all the form fields in the document 
        doc.getForm().isFlatten(true);

        //Save the result document
        doc.saveToFile("Flatten.pdf");
    }
}

The input PDF:

The input PDF document with forms

The result PDF:

Flatten PDF forms using Java

If you only want to flatten a specific form, you can use the following code:

import com.spire.pdf.PdfDocument;
import com.spire.pdf.fields.PdfField;
import com.spire.pdf.widget.PdfFormWidget;

public class FlattenSpecificForm {
    public static void main(String[] args){
        //Load a PDF document
        PdfDocument doc = new PdfDocument("FormFields.pdf");

        //Access the first form
        PdfFormWidget formWidget = (PdfFormWidget)doc.getForm();
        PdfField form = (PdfField) formWidget.getFieldsWidget().getList().get(0);
        //Flatten the first form
        form.setFlatten(true);

        //Save the result document
        doc.saveToFile("FlattenSpecificForm.pdf");
    }
}

Example 2. Make PDF forms Read Only in Java

The following are the steps to make all the forms in a PDF document as read only:

  • Load a PDF document by initializing an instance of PdfDocument class and passing the file path to the class’s constructor as a parameter.
  • Make all the forms in the document as read only using PdfDocument.getForm().setReadOnly(true) method.
  • Save the result document using PdfDocument.saveToFile() method.

Code example:

import com.spire.pdf.PdfDocument;

public class MakeFormsReadOnly {
    public static void main(String[] args){
        //Load a PDF document
        PdfDocument doc = new PdfDocument("FormFields.pdf");

        //Make all forms in the document as read only
        doc.getForm().setReadOnly(true);

        //Save the result document
        doc.saveToFile("ReadOnly.pdf");
    }
}

The result PDF:

Make PDF forms read only using Java

If you only want to make a specific form read only, you can use the following code:

import com.spire.pdf.PdfDocument;
import com.spire.pdf.fields.PdfField;
import com.spire.pdf.widget.PdfFormWidget;

public class MakeSpecificFormReadOnly {
    public static void main(String[] args){
        //Load a PDF document
        PdfDocument doc = new PdfDocument("FormFields.pdf");

        //Access the first form
        PdfFormWidget formWidget = (PdfFormWidget)doc.getForm();
        PdfField form = (PdfField) formWidget.getFieldsWidget().getList().get(0);

        //Make the first form read only
        form.setReadOnly(true);

        //Save the result document
        doc.saveToFile("MakeSpecificFormReadOnly.pdf");
    }
}

C#/VB.NET: Read or Delete Hyperlinks in Excel

If you are parsing an Excel file that contains multiple hyperlinks, you may need to read or extract the actual URL addresses from those hyperlinks. This article will demonstrate how to read hyperlinks as well as delete hyperlinks in Excel in C# and VB.NET using Free Spire.XLS for .NET.

Add DLL References

At first, you need to add the DLL files of Free Spire.XLS for .NET to your project as a reference. The DLL files of Free Spire.XLS for .NET can be either downloaded from the official website or installed via NuGet by executing the following command in Package Manager Console:

PM> Install-Package FreeSpire.XLS

Read Hyperlinks in Excel in C# and VB.NET

The following steps show how to get the hyperlinks in an Excel worksheet and then read the actual URL addresses from the hyperlinks:

  • Initialize an instance of Workbook class.
  • Load the Excel file using Workbook.LoadFromFile() method.
  • Get the desired worksheet by its index (zero-based) through Workbook.Worksheets[sheetIndex] property.
  • Get the hyperlinks collection from the worksheet through Worksheet.Hyperlinks property.
  • Loop through the hyperlinks in the collection.
  • Within the loop, get the cell where the hyperlink is located at through Hyperlink.Range property. Then get the URL address that the hyperlink refers to through Hyperlink.Address property. Next, write the address into a specific cell within the worksheet through Worksheet.Range[rowIndex, columnIndex].Text property. (Note the row and column indexes here are 1-based)
  • Save the result file using Workbook.SaveToFile() method.

C#

using Spire.Xls;
using Spire.Xls.Collections;

namespace ReadExcelHyperlinks
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook workbook = new Workbook();
            //Load an Excel file
            workbook.LoadFromFile("Hyperlinks.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Get the hyperlinks collection from the worksheet
            HyperLinksCollection hyperlinks = sheet.HyperLinks;

            //Loop through the hyperlinks in the collection
            foreach (HyperLink url in hyperlinks)
            {
                //Get the cell where the hyperlink is located at 
                CellRange range = url.Range;
                //Get the address that the hyperlink refers to
                string address = url.Address;
                //Write the address into a specific cell
                sheet.Range[range.Row, 4].Text = address;
            }

            //Save the result file
            workbook.SaveToFile("ExtractHyperlinks.xlsx", ExcelVersion.Version2016);
        }
    }
}

VB.NET

Imports Spire.Xls
Imports Spire.Xls.Collections

Namespace ReadExcelHyperlinks
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Workbook instance
            Dim workbook As Workbook = New Workbook()
            'Load an Excel file
            workbook.LoadFromFile("Hyperlinks.xlsx")

            'Get the first worksheet
            Dim sheet As Worksheet = workbook.Worksheets(0)

            'Get the hyperlinks collection from the worksheet
            Dim hyperlinks As HyperLinksCollection = sheet.HyperLinks

            'Loop through the hyperlinks in the collection
            For Each url As HyperLink In hyperlinks
                'Get the cell where the hyperlink is located at 
                Dim range As CellRange = url.Range
                'Get the address that the hyperlink refers to
                Dim address As String = url.Address
                'Write the address into a specific cell
                sheet.Range(range.Row, 4).Text = address
            Next

            'Save the result file
            workbook.SaveToFile("ExtractHyperlinks.xlsx", ExcelVersion.Version2016)
        End Sub
    End Class
End Namespace

The result file:

Extract the URL addresses from Hyperlinks in Excel using C# or VB.NET

Delete Hyperlinks from Excel in C# and VB.NET

You can delete a specific hyperlink or all of the hyperlinks from an Excel worksheet. The following steps show how to delete all the hyperlinks:

  • Initialize an instance of Workbook class.
  • Load the Excel file using Workbook.LoadFromFile() method.
  • Get the desired worksheet by its index (zero-based) through Workbook.Worksheets[sheetIndex] property.
  • Get the hyperlinks collection from the worksheet through Worksheet.Hyperlinks property.
  • Loop through from the last hyperlink to the first hyperlink in the collection. Then remove the hyperlink using Hyperlink.RemoveAt(hyperlinkIndex) method.
  • Save the result file using Workbook.SaveToFile() method.

C#

using Spire.Xls;
using Spire.Xls.Collections;

namespace DeleteExcelHyperlinks
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook workbook = new Workbook();
            //Load an Excel file
            workbook.LoadFromFile("Hyperlinks.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Get the hyperlinks collection in the worksheet
            HyperLinksCollection hyperlinks = sheet.HyperLinks;

            //Loop through from the last hyperlink to the first hyperlink in the collection
            for (int i = hyperlinks.Count - 1; i >= 0; i--)
            {
                //Remove the hyperlink
                hyperlinks.RemoveAt(i);
            }

            //Save the result file
            workbook.SaveToFile("DeleteHyperlinks.xlsx", ExcelVersion.Version2016);
        }
    }
}

VB.NET

Imports Spire.Xls
Imports Spire.Xls.Collections

Namespace DeleteExcelHyperlinks
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Workbook instance
            Dim workbook As Workbook = New Workbook()
            'Load an Excel file
            workbook.LoadFromFile("Hyperlinks.xlsx")

            'Get the first worksheet
            Dim sheet As Worksheet = workbook.Worksheets(0)

            'Get the hyperlinks collection from the worksheet
            Dim hyperlinks As HyperLinksCollection = sheet.HyperLinks

            'Loop through from the last hyperlink to the first hyperlink in the collection
            For i = hyperlinks.Count - 1 To 0 Step -1
                'Remove the hyperlink
                hyperlinks.RemoveAt(i)
            Next

            'Save the result file
            workbook.SaveToFile("DeleteHyperlinks.xlsx", ExcelVersion.Version2016)
        End Sub
    End Class
End Namespace

The result file:

Delete hyperlinks from Excel using C# or VB.NET

See Also

C#/VB.NET: Add Hyperlinks to Excel

C#/VB.NET: Create, Use and Delete Named Ranges in Excel

In Excel, we can give names to individual cells or range of cells. Then we can refer to the cells using their names instead of cell references. This is very helpful when working with formulas as it makes the formulas much easier to understand and maintain. For example, in the following image, cells A2 and B2 are named Sales and Expenses respectively. In cell C2, you can see the formula is “=Sales-Expenses” which is more self-explanatory than “=A2-B2”.

This article will explain how to create named ranges and use them in formulas as well as delete named ranges from Excel in C# and VB.NET using Free Spire.XLS for .NET.

Installation

You can download the DLL file of the API from this website or install it via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console and then execute the following command:

Install-Package FreeSpire.XLS

Create and Use Named Ranges in Excel using C# and VB.NET

You can create named ranges at workbook scope or worksheet scope. The following steps show how to create a named range at workbook scope and worksheet scope:

  • Create an instance of Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get the desired worksheet by its index (zero-based) through Workbook.Worksheets[sheetIndex] property.
  • Create a named range at workbook scope using Worksheet.Names.Add() method and specify the range it refers to through INamedRange.RefersToRange property.
  • Create a named range at worksheet scope using Workbook.NameRanges.Add() method and specify the range it refers to through INamedRange.RefersToRange property.
  • Create a formula to use the named ranges through Worksheet.Range[rangeName].Formula property.
  • Save the result file using Workbook.SaveToFile() method.

C#

using Spire.Xls;
using Spire.Xls.Core;

namespace AddNamedRanges
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook workbook = new Workbook();
            //Load an Excel file
            workbook.LoadFromFile(@"Input.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Create a named range at workbook scope
            INamedRange NamedRange1 = workbook.NameRanges.Add("Salary");
            NamedRange1.RefersToRange = sheet.Range["B2"];

            //Create a named range at worksheet scope
            INamedRange NamedRange2 = sheet.Names.Add("Bonus");
            NamedRange2.RefersToRange = sheet.Range["C2"];

            //Add text to the cell "D1"
            sheet.Range["D1"].Text = "Total";

            //Use the named ranges in a formula
            sheet.Range["D2"].Formula = "=SUM(Salary, Bonus)";

            //Save the result file
            workbook.SaveToFile("CreateNamedRanges.xlsx", ExcelVersion.Version2013);
        }
    }
}

VB.NET

 

Imports Spire.Xls
Imports Spire.Xls.Core

Namespace AddNamedRanges
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Workbook instance
            Dim workbook As Workbook = New Workbook()
            'Load an Excel file
            workbook.LoadFromFile("Input.xlsx")

            'Get the first worksheet
            Dim sheet As Worksheet = workbook.Worksheets(0)

            'Create a named range at workbook scope
            Dim NamedRange1 As INamedRange = workbook.NameRanges.Add("Salary")
            NamedRange1.RefersToRange = sheet.Range("B2")

            'Create a named range at worksheet scope
            Dim NamedRange2 As INamedRange = sheet.Names.Add("Bonus")
            NamedRange2.RefersToRange = sheet.Range("C2")

            'Add text to the cell "D1"
            sheet.Range("D1").Text = "Total"

            'Use the named ranges in a formula
            sheet.Range("D2").Formula = "=SUM(Salary, Bonus)"

            'Save the result file
            workbook.SaveToFile("CreateNamedRanges.xlsx", ExcelVersion.Version2013)
        End Sub
    End Class
End Namespace

The result file:

Create named ranges in Excel using C# and VB.NET

Delete Named Ranges from Excel

The following steps show how to delete the named ranges at workbook and worksheet scopes:

  • Create an instance of Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get the desired worksheet by its index (zero-based) through Workbook.Worksheets[sheetIndex] property.
  • Get the named range at workbook scope using Workbook.NameRanges.GetByName() method. Then, get the address of the range that the named range refers to. Next, delete the named range through Workbook.NameRanges.Remove() method.
  • Get the named range at worksheet scope using Worksheet.Names.GetByName() method. Then, get the address of the range that the named range refers to. Next, delete the named range through Worksheet.Names.Remove() method.
  • Change the named ranges’ name in the formula to range addresses through Worksheet.Range[rangeName].Formula property.
  • Save the result file using Workbook.SaveToFile() method.

C#

using Spire.Xls;
using Spire.Xls.Core;

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

            //Create a Workbook instance
            Workbook workbook = new Workbook();

            //Load an Excel file
            workbook.LoadFromFile(@"CreateNamedRanges.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Delete the named ranges at workbook scope            
            INamedRange namedRange1 = workbook.NameRanges.GetByName("Salary");
            string refersToRangeName1 = namedRange1.RefersToRange.RangeAddressLocal;
            workbook.NameRanges.Remove(namedRange1.Name);


            //Delete the named ranges at worksheet scope
            INamedRange namedRange2 = sheet.Names.GetByName("Bonus");
            string refersToRangeName2 = namedRange2.RefersToRange.RangeAddressLocal;;
            sheet.Names.Remove(namedRange2.Name);

            //Change the named ranges' name in the formula to range addresses
            sheet.Range["D2"].Formula = "=SUM(" + refersToRangeName1 + "," + refersToRangeName2 +")";

            //Save the result file
            workbook.SaveToFile("DeleteNamedRanges.xlsx", ExcelVersion.Version2013);
        }
    }
}

VB.NET

Imports Spire.Xls
Imports Spire.Xls.Core

Namespace DeleteNamedRanges
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())

            'Create a Workbook instance
            Dim workbook As Workbook = New Workbook()

            'Load an Excel file
            workbook.LoadFromFile("CreateNamedRanges.xlsx")

            'Get the first worksheet
            Dim sheet As Worksheet = workbook.Worksheets(0)

            'Delete the named ranges at workbook scope            
            Dim namedRange1 As INamedRange = workbook.NameRanges.GetByName("Salary")
            Dim refersToRangeName1 As String = namedRange1.RefersToRange.RangeAddressLocal
            workbook.NameRanges.Remove(namedRange1.Name)

            'Delete the named ranges at worksheet scope
            Dim namedRange2 As INamedRange = sheet.Names.GetByName("Bonus")
            Dim refersToRangeName2 As String = namedRange2.RefersToRange.RangeAddressLocal
            sheet.Names.Remove(namedRange2.Name)

            'Change the named ranges' name in the formula to range addresses
            sheet.Range("D2").Formula = "=SUM(" & refersToRangeName1 & "," & refersToRangeName2 & ")"

            'Save the result file
            workbook.SaveToFile("DeleteNamedRanges.xlsx", ExcelVersion.Version2013)
        End Sub
    End Class
End Namespace

The result file:

Delete named ranges from Excel using C# and VB.NET

C#/VB.NET: Change Page Margins of Existing PDF Documents

Margins are the white spaces between the main content and the edges of a page. They are used to control where the page content begins and ends. Sometimes, you may need to adjust the margins of PDF pages to change or add more white spaces. This article will explain how to change PDF page margins programmatically in C# and VB.NET. It consists of the following sections:

  • Change PDF Page Margins without Changing Page Size
  • Change PDF Page Margins and Also Change Page Size

Installation

Spire.PDF for .NET is used here to change PDF page margins. It’s a commercial library for creating, editing, converting and printing PDF documents. A free version of Spire.PDF for .NET is also available, but it should be pointed out that it’s limited to 10 pages while loading PDF files.

You can install either of them via NuGet:

Commercial version: Install-Package Spire.PDF

Free version: Install-Package FreeSpire.PDF

Change PDF Page Margins without Changing Page Size in C# and VB.NET

The following are the steps to change page margins of an existing PDF document without changing page size:

  • Load the source PDF document using PdfDocument class.
  • Create a new PDF document using PdfDocument class. Then set the increasing or decreasing value of margins as margins of the new PDF document.
  • Loop through the pages in the source PDF document.
  • Add a page that has the same page size with the source page to the new PDF document.
  • Create a new instance of PdfTextLayout class and specify the layout type as one page by setting the PdfTextLayout.Layout property as PdfLayoutType.OnePage (if not set the content will not scale to fit page size).
  • Create a template based on the source page using PdfPageBase.CreateTemplate() method.
  • Draw the template on the page of the new PDF document with one page layout using PdfTemplate.Draw() method.
  • Save the new PDF document to file using PdfDocument.SaveToFile() method.

Note: if you change page margins but don’t adjust the page size accordingly, the page content will be scaled.

C#

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

namespace PageMargins
{
    class Program
    {
        static void Main(string[] args)
        {            
            //Load the source PDF document
            PdfDocument sourcePdf = new PdfDocument("Input.pdf");

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

            //Set increasing value of page margins as page margins of the new PDF document
             //if you want to decrease the margins, set the value as negative
            newPdf.PageSettings.Margins.Left = 40;
            newPdf.PageSettings.Margins.Right = 40;
            newPdf.PageSettings.Margins.Top = 40;
            newPdf.PageSettings.Margins.Bottom = 40;

            //Loop through the pages in the source PDF document
            foreach (PdfPageBase sourcePage in sourcePdf.Pages)
            {
                //Add a page with the same page size to the new PDF document
                PdfPageBase newPage = newPdf.Pages.Add(sourcePage.Size);

                //Set text layout as 1 page, if not set the content will not scale to fit page size
                PdfTextLayout layout = new PdfTextLayout();
                layout.Layout = PdfLayoutType.OnePage;

                //Create a template based on the source page and draw it on the page of the new PDF document
                PdfTemplate template = sourcePage.CreateTemplate();
                template.Draw(newPage, new PointF(0, 0), layout);
            }

            //Save the new PDF document to file
            newPdf.SaveToFile("ChangeMargins1.pdf");
        }
    }
}

VB.NET

Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports System.Drawing

Namespace PageMargins
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Load the source PDF document
            Dim sourcePdf As PdfDocument = New PdfDocument("Input.pdf")

            'Create a new PDF document
            Dim newPdf As PdfDocument = New PdfDocument()

            'Set increasing value of page margins as page margins of the new PDF document              
            'if you want to decrease the margins, set the value as negative
            newPdf.PageSettings.Margins.Left = 40
            newPdf.PageSettings.Margins.Right = 40
            newPdf.PageSettings.Margins.Top = 40
            newPdf.PageSettings.Margins.Bottom = 40

            'Loop through the pages in the source PDF document
            For Each sourcePage As PdfPageBase In sourcePdf.Pages
                'Add a page with the same page size to the new PDF document
                Dim newPage As PdfPageBase = newPdf.Pages.Add(sourcePage.Size)

                'Set text layout as 1 page, if not set the content will not scale to fit page size
                Dim layout As PdfTextLayout = New PdfTextLayout()
                layout.Layout = PdfLayoutType.OnePage

                'Create a template based on the source page and draw it on the page of the new PDF document
                Dim template As PdfTemplate = sourcePage.CreateTemplate()
                template.Draw(newPage, New PointF(0, 0), layout)
            Next

            'Save the new PDF document to file
            newPdf.SaveToFile("ChangeMargins1.pdf")
        End Sub
    End Class
End Namespace

The source PDF:

The source PDF document

The result PDF:

The result PDF document after changing page margins

Change PDF Page Margins and Also Change Page Size

If you don’t want the page contents to be scaled while changing page margins, you can change the page size at the same time. The following are the steps to do so:

  • Load the source PDF document using PdfDocument class.
  • Create a new PDF document using PdfDocument class. Then set the increasing or decreasing value of margins as margins of the new PDF document.
  • Loop through the pages in the source PDF document.
  • Create an instance of SizeF class which will then be used as the page size of the new PDF document. Then set its width and height through SizeF.Width and SizeF.Height properties.
  • Add a page with the specified size to the new PDF document.
  • Create a template based on the source page using PdfPageBase.CreateTemplate() method.
  • Draw the template on the page of the new PDF document using PdfTemplate.Draw() method.
  • Save the new PDF document to file using PdfDocument.SaveToFile() method.

C#

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

namespace PageMargins
{
    class Program
    {
        static void Main(string[] args)
        {          
            //Load the source PDF document
            PdfDocument sourcePdf = new PdfDocument("Input.pdf");

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

            //Set increasing value of margins as margins of the new PDF document 
            //if you want to decrease the margins, set the value as negative
            newPdf.PageSettings.Margins.Left = 40;
            newPdf.PageSettings.Margins.Right = 40;
            newPdf.PageSettings.Margins.Top = 40;
            newPdf.PageSettings.Margins.Bottom = 40;

            //Loop through the pages in the source PDF document
            foreach (PdfPageBase sourcePage in sourcePdf.Pages)
            {
                //Create a SizeF instance which will then be used as the page size of the new PDF document
                SizeF size = new SizeF();
                //Set its width and height 
                size.Width = sourcePage.Size.Width + newPdf.PageSettings.Margins.Left + newPdf.PageSettings.Margins.Right;
                size.Height = sourcePage.Size.Height + newPdf.PageSettings.Margins.Top + newPdf.PageSettings.Margins.Bottom;
                //Add a page with larger page size to the new PDF document
                PdfPageBase newPage = newPdf.Pages.Add(size);
                //Create a template based on the source page and draw it on the page of the new PDF document
                PdfTemplate template = sourcePage.CreateTemplate();
                template.Draw(newPage, new PointF(0, 0));
            }

            //Save the new PDF document to file
            newPdf.SaveToFile("ChangeMargins2.pdf");
        }
    }
}

VB.NET

Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports System.Drawing

Namespace PageMargins
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Load the source PDF document
            Dim sourcePdf As PdfDocument = New PdfDocument("Input.pdf")

            'Create a new PDF document
            Dim newPdf As PdfDocument = New PdfDocument()

            'Set increasing value of margins as margins of the new PDF document 
            'if you want to decrease the margins, set the value as negative
            newPdf.PageSettings.Margins.Left = 40
            newPdf.PageSettings.Margins.Right = 40
            newPdf.PageSettings.Margins.Top = 40
            newPdf.PageSettings.Margins.Bottom = 40

            'Loop through the pages in the source PDF document
            For Each sourcePage As PdfPageBase In sourcePdf.Pages
                'Create a SizeF instance which will then be used as the page size of the new PDF document
                Dim size As SizeF = New SizeF()
                'Set its width and height 
                size.Width = sourcePage.Size.Width + newPdf.PageSettings.Margins.Left + newPdf.PageSettings.Margins.Right
                size.Height = sourcePage.Size.Height + newPdf.PageSettings.Margins.Top + newPdf.PageSettings.Margins.Bottom
                'Add a page with larger page size to the new PDF document
                Dim newPage As PdfPageBase = newPdf.Pages.Add(size)
                'Create a template based on the source page and draw it on the page of the new PDF document
                Dim template As PdfTemplate = sourcePage.CreateTemplate()
                template.Draw(newPage, New PointF(0, 0))
            Next

            'Save the new PDF document to file
            newPdf.SaveToFile("ChangeMargins2.pdf")
        End Sub
    End Class
End Namespace

The result PDF:

The result PDF after changing page margins and page size
Design a site like this with WordPress.com
Get started