Page Setting

Page Setting (5)

In PDF, you can change the page size to make the document meet different needs. For example, a smaller page size is required when creating handouts or compact versions of documents, while a larger page size could be useful for designing posters or graphics-intensive materials. In some cases, you may also need to get the page dimensions (width and height) to determine if the document is resized optimally. In this article, you will learn how to change or get PDF page size programmatically in Python using Spire.PDF for Python.

Install Spire.PDF for Python

This scenario requires Spire.PDF for Python and plum-dispatch v1.7.4. They can be easily installed in your VS Code through the following pip command.

pip install Spire.PDF

If you are unsure how to install, please refer to this tutorial: How to Install Spire.PDF for Python in VS Code

Change PDF Page Size to a Standard Paper Size with Python

The way to change the page size of a PDF file is to create a new PDF file and add pages of the desired size to it, then create templates based on the pages in the original PDF file and draw the templates onto the pages in the new PDF file. This process will preserve text, images, and other elements present in the original PDF file.

Spire.PDF for Python supports a variety of standard paper size, such as letter, legal, A0, A1, A2, A3, A4, B0, B1, B2, B3, B4 and so on. The following are the steps to change the page size of a PDF file to a standard paper size:

  • Initialize a PdfDocument instance and load the original PDF file using PdfDocument.LoadFromFile() method.
  • Initialize another PdfDocument instance to create a new PDF file.
  • Loop through the pages in the original PDF.
  • Add pages of the desired size to the new PDF file using PdfDocument.Pages.Add() method.
  • Initialize a PdfTextLayout instance and set the text layout as one page through PdfTextLayout.Layout property.
  • Create templates based on the pages in the original PDF using PdfPageBase.CreateTemplate() method.
  • Draw the templates onto the pages in the new PDF file with the specified text layout using PdfTemplate.Draw() method.
  • Save the result file using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

inputFile = "Sample1.pdf"
outputFile = "ChangePageSizeToA3.pdf"

# Create a PdfDocument instance
originalPdf = PdfDocument()

# Load the original PDF document
originalPdf.LoadFromFile(inputFile)

# Create a new PDF document
newPdf = PdfDocument()

# Loop through the pages in the original PDF
for i in range(originalPdf.Pages.Count):
    page = originalPdf.Pages.get_Item(i)

    # Add pages of size A3 to the new PDF
    newPage = newPdf.Pages.Add(PdfPageSize.A3(), PdfMargins(0.0))

    # Create a PdfTextLayout instance
    layout = PdfTextLayout()

    # Set text layout as one page (if not set the content will not scale to fit page size)
    layout.Layout = PdfLayoutType.OnePage

    # Create templates based on the pages in the original PDF
    template = page.CreateTemplate()

    # Draw the templates onto the pages in the new PDF
    template.Draw(newPage, PointF.Empty(), layout)

# Save the result document
newPdf.SaveToFile(outputFile)
newPdf.Close()

Python: Change or Get PDF Page Size

Change PDF Page Size to a Custom Paper Size with Python

Spire.PDF for Python uses point (1/72 of an inch) as the unit of measure. If you need to change the page size of a PDF to a custom paper size in other units of measure like inches or millimeters, you can use the PdfUnitConvertor class to convert them to points.

The following are steps to change the page size of a PDF file to a custom paper size in inches:

  • Initialize a PdfDocument instance and load the original PDF file using PdfDocument.LoadFromFile() method.
  • Initialize another PdfDocument instance to create a new PDF file.
  • Initialize a PdfUnitConvertor instance, then convert the custom size in inches to points using PdfUnitConvertor.ConvertUnits() method.
  • Initialize a SizeF instance from the custom size.
  • Loop through the pages in the original PDF.
  • Add pages of the custom size to the new PDF file using PdfDocument.Pages.Add() method.
  • Initialize a PdfTextLayout instance and set the text layout as one page through PdfTextLayout.Layout property.
  • Create templates based on the pages in the original PDF using PdfPageBase.CreateTemplate() method.
  • Draw the templates onto the pages in the new PDF file with the specified text layout using PdfTemplate.Draw() method.
  • Save the result file using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

inputFile = "Sample1.pdf"
outputFile = "CustomizePdfPageSize.pdf"

# Create a PdfDocument instance
originalPdf = PdfDocument()

# Load the original PDF document
originalPdf.LoadFromFile(inputFile)

# Create a new PDF document
newPdf = PdfDocument()

# Create a PdfUnitConvertor instance
unitCvtr = PdfUnitConvertor()

# Convert the custom size in inches to points
width = unitCvtr.ConvertUnits(12.0, PdfGraphicsUnit.Inch, PdfGraphicsUnit.Point)
height = unitCvtr.ConvertUnits(15.5, PdfGraphicsUnit.Inch, PdfGraphicsUnit.Point)

#Create a new SizeF instance from the custom size, then it will be used as the page size of the new PDF
size = SizeF(width, height)

# Loop through the pages in the original PDF
for i in range(originalPdf.Pages.Count):
    page = originalPdf.Pages.get_Item(i)

    # Add pages of the custom size (12.0*15.5 inches) to the new PDF
    newPage = newPdf.Pages.Add(size, PdfMargins(0.0))

    # Create a PdfTextLayout instance
    layout = PdfTextLayout()

    # Set text layout as one page (if not set the content will not scale to fit page size)
    layout.Layout = PdfLayoutType.OnePage

    # Create templates based on the pages in the original PDF
    template = page.CreateTemplate()

    # Draw the templates onto the pages in the new PDF
    template.Draw(newPage, PointF.Empty(), layout)

# Save the result document
newPdf.SaveToFile(outputFile)
newPdf.Close()

Python: Change or Get PDF Page Size

Get PDF Page Size with Python

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

The following are the steps to get the PDF page size:

  • Initialize a PdfDocument instance.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Get a specified page using PdfDocument.Pages[] property.
  • Get the width and height of the PDF page using PdfPageBase.Size.Width and PdfPageBase.Size.Height properties.
  • Initialize a PdfUnitConvertor instance, and then convert the size units from points to other units of measure using PdfUnitConvertor.ConvertUnits() method.
  • Add the size information to a StringBuilder instance, and then save the result to a TXT file.
  • Python
from spire.pdf.common import *
from spire.pdf import *

def AppendAllText(fname: str, text: List[str]):
    fp = open(fname, "w")
    for s in text:
        fp.write(s + "\n")
    fp.close()

inputFile = "Sample1.pdf"
outputFile = "GetPageSize.txt"

# Create a PdfDocument instance
pdf = PdfDocument()

# Load a sample PDF from disk
pdf.LoadFromFile(inputFile)

# Get the first page of the file
page = pdf.Pages[0]

# Get the width and height of page based on "point"
pointWidth = page.Size.Width
pointHeight = page.Size.Height

# Create PdfUnitConvertor to convert the unit
unitCvtr = PdfUnitConvertor()

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

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

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

# Add the size information to a StringBuilder instance
content = []
content.append("The page size of the file in points is (width: " +
               str(pointWidth) + "pt, height: " + str(pointHeight) + "pt).")
content.append("The page size of the file in pixels is (width: " +
               str(pixelWidth) + "pixel, height: " + str(pixelHeight) + "pixel).")
content.append("The page size of the file in inches is (width: " +
               str(inchWidth) + "inch, height: " + str(inchHeight) + "inch).")
content.append("The page size of the file in centimeters is (width: " +
               str(centimeterWidth) + "cm, height: " + str(centimeterHeight) + "cm.)")

# Save to a txt file
AppendAllText(outputFile, content)
pdf.Close()

Python: Change or Get PDF Page Size

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.

To get the number of pages in a PDF file, you can open the file in a PDF viewer such as Adobe, which has a built-in page count feature. However, when there is a batch of PDF files, opening each file to check how many pages it contains is a time-consuming task. In this article, you will learn how to quicky count the number of pages in a PDF file through programming using Spire.PDF for Python.

Install Spire.PDF for Python

This scenario requires Spire.PDF for Python and plum-dispatch v1.7.4. They can be easily installed in your VS Code through the following pip command.

pip install Spire.PDF

If you are unsure how to install, please refer to this tutorial: How to Install Spire.PDF for Python in VS Code

Count the Number of Pages in a PDF File in Python

Spire.PDF for Python 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 document using PdfDocument.LoadFromFile() method.
  • Count the number of pages in the PDF document using PdfDocument.Pages.Count property.
  • Write the result to a TXT file or print it out directly.
  • Python
from spire.pdf.common import *
from spire.pdf import *

def AppendText(fname: str, text: str):
    fp = open(fname, "w")
    fp.write(text + "\n")
    fp.close()

# Specify the input and output files
inputFile = "contract.pdf"
outputFile = "GetNumberOfPages.txt"

# Create a PdfDocument object
pdf = PdfDocument()

# Load a PDF document from disk
pdf.LoadFromFile(inputFile)

# Count the number of pages in the document
count = pdf.Pages.Count
# Print the result
print("Total Pages:", count)

# Write the result to a TXT file
AppendText(
    outputFile, "The number of pages in the pdf document is: " + str(count))
pdf.Close()

Python: Count the Number of Pages in a PDF File

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.

Pages are the most fundamental components of a PDF document. If you want to add new information or supplemental material to an existing PDF, it is necessary to add new pages. Conversely, if there are some pages that contain incorrect or irrelevant content, you can remove them to create a more professional document. In this article, you will learn how to programmatically add or delete pages in PDF using Spire.PDF for Python.

Install Spire.PDF for Python

This scenario requires Spire.PDF for Python and plum-dispatch v1.7.4. They can be easily installed in your VS Code through the following pip command.

pip install Spire.PDF

If you are unsure how to install, please refer to this tutorial: How to Install Spire.PDF for Python in VS Code

Add Empty Pages to a PDF Document in Python

With Spire.PDF for Python, you can easily add a blank page to a specific position or to the end of the document using PdfDocument.Pages.Insert() or PdfDocument.Pages.Add(SizeF, PdfMargins) methods. The following are the detailed steps.

  • Create a PdfDocument object.
  • Load a sample PDF document using PdfDocument.LoadFromFile() method.
  • Create a new blank page and insert it into a specific position of the document using PdfDocument.Pages.Insert() method.
  • Create another new blank page with the specified size and margins, and then append it to the end of the document using PdfDocument.Pages.Add(SizeF, PdfMargins) method.
  • Save the result document using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
pdf = PdfDocument()

# Load a PDF document
pdf.LoadFromFile("Test.pdf")

# Insert a blank page to the document as the second page
pdf.Pages.Insert(1)

# Add an empty page to the end of the document
pdf.Pages.Add(PdfPageSize.A4(), PdfMargins(0.0, 0.0))

# Save the result document
pdf.SaveToFile("AddPage.pdf")
pdf.Close()

Python: Add or Delete Pages in PDF

Delete an Existing Page in a PDF Document in Python

To remove a specified page from a PDF, you can use the PdfDocument.Pages.RemoveAt() method. The following are the detailed steps.

  • Create a PdfDocument object.
  • Load a sample PDF document using PdfDocument.LoadFromFile() method.
  • Remove a specified page from the document using PdfDocument.Pages.RemoveAt() method.
  • Save the result document using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
pdf = PdfDocument()

# Load a PDF document
pdf.LoadFromFile("Test.pdf")

# Delete the second page of the document
pdf.Pages.RemoveAt(1)

# Save the result document
pdf.SaveToFile("DeletePage.pdf")
pdf.Close()

Python: Add or Delete Pages in PDF

Apply for a Temporary License

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

Applying a background color or image to a PDF can be an effective way to enhance its visual appeal, create a professional look, or reinforce branding elements. By adding a background, you can customize the overall appearance of your PDF document and make it more engaging for readers. Whether you want to use a solid color or incorporate a captivating image, this feature allows you to personalize your PDFs and make them stand out. In this article, you will learn how to set a background color or image for a PDF document in Python using Spire.PDF for Python.

Install Spire.PDF for Python

This scenario requires Spire.PDF for Python and plum-dispatch v1.7.4. They can be easily installed in your VS Code through the following pip command.

pip install Spire.PDF

If you are unsure how to install, please refer to this tutorial: How to Install Spire.PDF for Python in VS Code

Set a Background Color for PDF in Python

Spire.PDF for Python offers the PdfPageBase.BackgroundColor property to get or set the background color of a certain page. To add a solid color to the background of each page in the document, follow the steps below.

  • Create a PdfDocument object.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Traverse through the pages in the document, and get a specific page through PdfDocument.Pages[index] property.
  • Apply a solid color to the background through PdfPageBase.BackgroundColor property.
  • Save the document to a different PDF file using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
doc = PdfDocument()

# Load a PDF file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.pdf")

# Loop through the pages in the document
for i in range(doc.Pages.Count):
    
    # Get a particular page
    page = doc.Pages[i]

    # Set background color 
    page.BackgroundColor = Color.get_LightYellow()

# Save the document to a different file
doc.SaveToFile("output/SetBackgroundColor.pdf")

Python: Set a Background Color or Image for PDF

Set a Background Image for PDF in Python

Likewise, an image can be applied to the background of a specific page via PdfPageBase.BackgroundImage property. The steps to set an image background for the entire document are as follows.

  • Create a PdfDocument object.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Traverse through the pages in the document, and get a specific page through PdfDocument.Pages[index] property.
  • Apply an image to the background through PdfPageBase.BackgroundImage property.
  • Save the document to a different PDF file using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
doc = PdfDocument()

# Load a PDF file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.pdf")

# Loop through the pages in the document
for i in range(doc.Pages.Count):
    
    # Get a particular page
    page = doc.Pages[i]

    # Set background image 
    page.BackgroundImage = Stream("C:\\Users\\Administrator\\Desktop\\img.jpg")

# Save the document to a different file
doc.SaveToFile("output/SetBackgroundImage.pdf")

Python: Set a Background Color or Image for 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.

Python: Rotate PDF Pages

2023-09-19 00:59:07 Written by support iceblue

If you receive or download a PDF file and find that some of the pages are displayed in the wrong orientation (e.g., sideways or upside down), rotating the PDF file allows you to correct the page orientation for easier reading and viewing. This article will demonstrate how to programmatically rotate PDF pages using Spire.PDF for Python.

Install Spire.PDF for Python

This scenario requires Spire.PDF for Python and plum-dispatch v1.7.4. They can be easily installed in your VS Code through the following pip command.

pip install Spire.PDF

If you are unsure how to install, please refer to this tutorial: How to Install Spire.PDF for Python in VS Code

Rotate a Specific Page in PDF in Python

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 a PdfDocument object.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Get a specified page using PdfDocument.Pages[pageIndex] property.
  • Get the original rotation angle of the page using PdfPageBase.Rotation.value property.
  • Increase the original rotation angle by desired degrees.
  • Apply the new rotation angle to the page using PdfPageBase.Rotation property
  • Save the result document using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
pdf = PdfDocument()

# Load a PDF document
pdf.LoadFromFile("Sample.pdf")

# Get the first page 
page = pdf.Pages[0]

# Get the original rotation angle of the page
rotation = int(page.Rotation.value)

# Rotate the page 180 degrees clockwise based on the original rotation angle
rotation += int(PdfPageRotateAngle.RotateAngle180.value)
page.Rotation = PdfPageRotateAngle(rotation)

# Save the result document
pdf.SaveToFile("RotatePDFPage.pdf")
pdf.Close()

Python: Rotate PDF Pages

Rotate All Pages in PDF in Python

Spire.PDF for Python also allows you to loop through each page in a PDF file and then rotate them all. The following are the detailed steps.

  • Create a PdfDocument object.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Loop through each page in the document.
  • Get the original rotation angle of the page using PdfPageBase.Rotation.value property.
  • Increase the original rotation angle by desired degrees.
  • Apply the new rotation angle to the page using PdfPageBase.Rotation property.
  • Save the result document using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
pdf = PdfDocument()

# Load a PDF document
pdf.LoadFromFile("Input.pdf")

# Loop through each page in the document
for i in range(pdf.Pages.Count):
    page = pdf.Pages.get_Item(i)

    # Get the original rotation angle of the page
    rotation = int(page.Rotation.value)

    # Rotate the page 180 degrees clockwise based on the original rotation angle
    rotation += int(PdfPageRotateAngle.RotateAngle180.value)
    page.Rotation = PdfPageRotateAngle(rotation)

# Save the result document
pdf.SaveToFile("RotatePDF.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.