Python (359)
Hyperlinks are a useful tool for connecting and navigating between different sections of your document or external resources such as websites or files. However, there may be instances where you need to modify the hyperlinks in your Word document. For example, you may need to update the text or URL of a hyperlink to ensure accuracy, or change the appearance of a hyperlink to improve visibility. In this article, you will learn how to update or change hyperlinks in a Word document in Python using Spire.Doc for Python.
- Update a Hyperlink in a Word Document in Python
- Change the Appearance of a Hyperlink in a Word Document in Python
Install Spire.Doc for Python
This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.Doc
If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python on Windows
Update a Hyperlink in a Word Document in Python
A hyperlink is recognized as a FormField object by Spire.Doc for Python. In order to modify a specific hyperlink, we need to retrieve all hyperlinks in the document and get the desired one by its index. The display text and URL of a hyperlink can be reset by the FormField.Text property and the FormField.Code property. The following are the steps to update a hyperlink in a Word document using Spire.Doc for Python.
- Create a Document object.
- Load a Word file using Document.LoadFromFile() method.
- Loop through the elements in the document to find all hyperlinks.
- Get a specific hyperlink from the hyperlink collection.
- Update the display text of the hyperlink through FormField.FieldText property.
- Update the URL of the hyperlink through FormField.Code property.
- Save the document to a different Word file using Document.SaveToFile() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
doc = Document()
# Load a Word file
doc.LoadFromFile("C:/Users/Administrator/Desktop/input.docx")
# Find all hyperlinks in the document
hyperlinks = []
for i in range(doc.Sections.Count):
section = doc.Sections.get_Item(i)
for j in range(section.Body.ChildObjects.Count):
sec = section.Body.ChildObjects.get_Item(j)
if sec.DocumentObjectType == DocumentObjectType.Paragraph:
for k in range((sec if isinstance(sec, Paragraph) else None).ChildObjects.Count):
para = (sec if isinstance(sec, Paragraph)
else None).ChildObjects.get_Item(k)
if para.DocumentObjectType == DocumentObjectType.Field:
field = para if isinstance(para, Field) else None
if field.Type == FieldType.FieldHyperlink:
hyperlinks.append(field)
# Get a specific hyperlink
hyperlink = hyperlinks[0]
# Update the display text of the hyperlink
hyperlink.FieldText = "HYPERTEXT MARKUP LANGUAGE"
# Update the URL of the hyperlink
hyperlink.Code ="HYPERLINK \"" + "https://en.wikipedia.org/wiki/HTML" + "\""
# Save the document to a docx file
doc.SaveToFile("output/UpdateHyperlink.docx", FileFormat.Docx)
doc.Close()

Change the Appearance of a Hyperlink in a Word Document in Python
After a hyperlink is obtained, it's easy to change the appearance of it through the FormField.CharacterFormat object. Specifically, the CharacterFormat object offers the properties such as TextColor, FontName, FontSize, UnderlineStyle to change the style of the characters of a hyperlink. The following are the detailed steps.
- Create a Document object.
- Load a Word file using Document.LoadFromFile() method.
- Loop through the elements in the document to find all hyperlinks.
- Get a specific hyperlink from the hyperlink collection.
- Change the appearance of the hyperlink through the properties under FormField.CharacterFormat object.
- Save the document to a different Word file using Document.SaveToFile() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
doc = Document()
# Load a Word file
doc.LoadFromFile("C:/Users/Administrator/Desktop/input.docx")
# Find all hyperlinks in the Word document
hyperlinks = []
for i in range(doc.Sections.Count):
section = doc.Sections.get_Item(i)
for j in range(section.Body.ChildObjects.Count):
sec = section.Body.ChildObjects.get_Item(j)
if sec.DocumentObjectType == DocumentObjectType.Paragraph:
for k in range((sec if isinstance(sec, Paragraph) else None).ChildObjects.Count):
para = (sec if isinstance(sec, Paragraph)
else None).ChildObjects.get_Item(k)
if para.DocumentObjectType == DocumentObjectType.Field:
field = para if isinstance(para, Field) else None
if field.Type == FieldType.FieldHyperlink:
hyperlinks.append(field)
# Get a specific hyperlink
hyperlink = hyperlinks[0]
# Change the appearance of the hyperlink
hyperlink.CharacterFormat.UnderlineStyle = UnderlineStyle.none
hyperlink.CharacterFormat.TextColor = Color.get_Purple()
hyperlink.CharacterFormat.Bold = True
# Save the document to a docx file
doc.SaveToFile("output/ChangeAppearance.docx", FileFormat.Docx)
doc.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.
Headers and footers in Word are sections at the top and bottom margins of each page. They can contain additional information such as page numbers, document titles, dates, author names, and other identifying details. By default, the headers or footers on all pages are the same, but in certain scenarios, you can also insert different headers or footers on the first page, odd pages, or even pages. This article will demonstrate how to insert headers and footers into a Word document in Python using Spire.Doc for Python.
- Insert Headers and Footers into a Word Document
- Add Different Headers and Footers for the First Page and Other Pages
- Add Different Headers and Footers for Odd and Even Pages
Install Spire.Doc for Python
This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip commands.
pip install Spire.Doc
If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python on Windows
Insert Headers and Footers into a Word Document in Python
To insert a header or a footer into a Word document, you first need to get them through the Section.HeadersFooters.Header and Section.HeadersFooters.Footer properties, and then add paragraphs to them to insert pictures, text, page numbers, dates, or other information.
The following are steps to add headers and footers in Word:
- Create a Document object.
- Load a Word document using Document.LoadFromFile() method.
- Get a specified section using Document.Sections[] property.
- Add Header
- Get header using Section.HeadersFooters.Header property.
- Add a paragraph to the header using HeaderFooter.AddParagraph() method and set paragraph alignment.
- Add an image to the header paragraph using Paragraph.AppendPicture() method, and then set the text wrapping style and position of the image.
- Add text to the header paragraph using Paragraph.AppendText() method, and then set the font name, size, color, etc.
- Add Footer
- Get footer using Section.HeadersFooters.Footer property.
- Add a paragraph to the footer and then add text to the footer paragraph.
- Get the borders of the footer paragraph using Paragraph.Format.Borders property, and then set the top border style and space.
- Save the result document using Document.SaveToFile() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
document = Document()
# Load a Word document
document.LoadFromFile("Sample.docx")
# Get a specific section
section = document.Sections.get_Item(0)
# Get header
header = section.HeadersFooters.Header
# Add a paragraph to the header and set its alignment style
headerParagraph = header.AddParagraph()
headerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Left
# Add an image to the header paragraph and set its text wrapping style, position
headerPicture = headerParagraph.AppendPicture("Logo.png")
headerPicture.TextWrappingStyle = TextWrappingStyle.Square
headerPicture.VerticalOrigin = VerticalOrigin.Line
headerPicture.VerticalAlignment = ShapeVerticalAlignment.Center
# Add text to the header paragraph and set its font style
text = headerParagraph.AppendText("E-iceblue Co. Ltd."+ "\nYour Office Development Master")
text.CharacterFormat.FontName = "Arial"
text.CharacterFormat.FontSize = 10
text.CharacterFormat.Bold = True
text.CharacterFormat.TextColor = Color.get_Blue()
# Get footer
footer = section.HeadersFooters.Footer
# Add a paragraph to the footer paragraph and set its alignment style
footerParagraph = footer.AddParagraph()
footerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center
# Add text to the footer paragraph and set its font style
text = footerParagraph.AppendText("Copyright © 2013 e-iceblue. All Rights Reserved.")
text.CharacterFormat.FontName = "Arial"
text.CharacterFormat.FontSize = 10
# Set the border of the footer paragraph
footerParagraph.Format.Borders.Top.BorderType = BorderStyle.Single
footerParagraph.Format.Borders.Top.Space = 0.05
# Save the result file
document.SaveToFile("HeaderAndFooter.docx", FileFormat.Docx)
document.Close()

Add Different Headers and Footers for the First Page and Other Pages in Word in Python
Sometimes you may need to insert a header and footer only on the first page, or you may want the header and footer on the first page different from other pages.
Spire.Doc for Python offers the Section.PageSetup.DifferentFirstPageHeaderFooter property to enable a different first page header or footer. The following are the detailed steps to accomplish the task.
- Create a Document object.
- Load a Word document using Document.LoadFromFile() method.
- Get a specified section using Document.Sections[] property.
- Enable different headers and footers for the first page and other pages by setting the Section.PageSetup.DifferentFirstPageHeaderFooter property to True.
- Get the first page header using Section.HeadersFooters.FirstPageHeader property.
- Add a paragraph to the first page header and then add an image to the header paragraph.
- Get the first page footer using Section.HeadersFooters.FirstPageFooter property.
- Add a paragraph to the first page footer and then add text to the footer paragraph.
- Set headers and footers for other pages. (There's no need to set this if you only need the header & footer for the first page.)
- Save the result document using Document.SaveToFile() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
doc = Document()
# Load a Word document
doc.LoadFromFile("Sample.docx")
# Get a specific section
section = document.Sections.get_Item(0)
# Enable different headers and footers for the first page and other pages
section.PageSetup.DifferentFirstPageHeaderFooter = True
# Add a paragraph to the first page header and set its alignment style
headerParagraph = section.HeadersFooters.FirstPageHeader.AddParagraph()
headerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right
# Add an image to the header paragraph
headerimage = headerParagraph.AppendPicture("E-iceblue.png")
# Add a paragraph to the first page footer and set its alignment style
footerParagraph = section.HeadersFooters.FirstPageFooter.AddParagraph()
footerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center
# Add text to the footer paragraph and set its font style
text = footerParagraph.AppendText("Different First Page Footer")
text.CharacterFormat.FontSize = 11
# Set the header & footer for other pages. If you only headers & footers for the first page, don't set this.
para = section.HeadersFooters.Header.AddParagraph()
para.Format.HorizontalAlignment = HorizontalAlignment.Left
paraText = para.AppendText("A Professional Word Python API")
paraText.CharacterFormat.FontSize = 12
paraText.CharacterFormat.TextColor = Color.get_DeepPink()
para.Format.Borders.Bottom.BorderType = BorderStyle.Single
para.Format.Borders.Bottom.Space = 0.05
paragraph = section.HeadersFooters.Footer.AddParagraph()
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
paraText = paragraph.AppendText("E-iceblue Co. Ltd.")
paraText.CharacterFormat.FontSize = 12
paraText.CharacterFormat.Bold = True
paraText.CharacterFormat.TextColor = Color.get_DodgerBlue()
# Save the result document
doc.SaveToFile("DifferentFirstPage.docx", FileFormat.Docx)
doc.Close()

Add Different Headers and Footers for Odd and Even Pages in Word in Python
To have different headers and footers on odd and even pages, Spire.Doc for Python provides the Section.PageSetup.DifferentOddAndEvenPagesHeaderFooter property. The following are the detailed steps.
- Create a Document object.
- Load a Word document using Document.LoadFromFile() method.
- Get a specified section using Document.Sections[] property.
- Enable different headers and footers for the odd and even pages by setting the Section.PageSetup.DifferentOddAndEvenPagesHeaderFooter property to True.
- Get the header and footer of odd pages using Section.HeadersFooters.OddHeader and Section.HeadersFooters.OddFooter properties.
- Add paragraphs to the header and footer of odd pages and then add text to them.
- Get the header and footer of even pages using Section.HeadersFooters.EvenHeader and Section.HeadersFooters.EvenFooter properties.
- Add paragraphs to the header and footer of even pages and then add text to them.
- Save the result document using Document.SaveToFile() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create a Document object
doc = Document()
# Load a Word document
doc.LoadFromFile("Sample.docx")
# Get a specific section
section = document.Sections.get_Item(0)
# Enable different headers and footers for the odd and even pages
section.PageSetup.DifferentOddAndEvenPagesHeaderFooter = True
# Add headers and footers to odd pages
OHpara = section.HeadersFooters.OddHeader.AddParagraph()
OHtext = OHpara.AppendText("Odd Page Header")
OHpara.Format.HorizontalAlignment = HorizontalAlignment.Center
OHtext.CharacterFormat.FontName = "Arial"
OHtext.CharacterFormat.FontSize = 12
OHtext.CharacterFormat.TextColor = Color.get_Red()
OFpara = section.HeadersFooters.OddFooter.AddParagraph()
OFtext = OFpara.AppendText("Odd Page Footer")
OFpara.Format.HorizontalAlignment = HorizontalAlignment.Center
OFtext.CharacterFormat.FontName = "Arial"
OFtext.CharacterFormat.FontSize = 12
OFtext.CharacterFormat.TextColor = Color.get_Red()
# Add headers and footers to even pages
EHpara = section.HeadersFooters.EvenHeader.AddParagraph()
EHtext = EHpara.AppendText("Even Page Header")
EHpara.Format.HorizontalAlignment = HorizontalAlignment.Center
EHtext.CharacterFormat.FontName = "Arial"
EHtext.CharacterFormat.FontSize = 12
EHtext.CharacterFormat.TextColor = Color.get_Blue()
EFpara = section.HeadersFooters.EvenFooter.AddParagraph()
EFtext = EFpara.AppendText("Even Page Footer")
EFpara.Format.HorizontalAlignment = HorizontalAlignment.Center
EFtext.CharacterFormat.FontName = "Arial"
EFtext.CharacterFormat.FontSize = 12
EFtext.CharacterFormat.TextColor = Color.get_Blue()
# Save the result document
doc.SaveToFile("OddAndEvenHeaderFooter.docx", FileFormat.Docx)
doc.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.
Setting an appropriate background is a crucial step when creating visually captivating and impactful PowerPoint presentations. The background serves as the foundation upon which your content is displayed, and choosing the right background can greatly enhance the overall aesthetic and effectiveness of your slides. Whether you are presenting at a business meeting, educational seminar, or social event, a well-designed background can engage your audience and effectively convey your message. In this article, we will explain how to set background color or picture for PowerPoint slides in Python using Spire.Presentation for Python.
- Set a Background Color for a PowerPoint Slide in Python
- Set a Gradient Background for a PowerPoint Slide in Python
- Set a Background Picture for a PowerPoint Slide in Python
- Set a Background for a Slide Master in PowerPoint in Python
Install Spire.Presentation for Python
This scenario requires Spire.Presentation for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.Presentation
If you are unsure how to install, please refer to this tutorial: How to Install Spire.Presentation for Python on Windows
Set a Background Color for a PowerPoint Slide in Python
Adding a background color for a PowerPoint slide is very simple. You just need to set the fill mode of the slide's background as a solid fill and then set a color for the slide’s background. The detailed steps are as follows.
- Create an object of the Presentation class.
- Load a PowerPoint presentation using Presentation.LoadFromFile() method.
- Get a specific slide using Presentation.Slides[index] property.
- Access the background of the slide using ISlide.SlideBackground property.
- Set the type of the slide's background as a custom type using SlideBackground.Type property.
- Set the fill mode of the slide’s background as a solid fill using SlideBackground.Fill.FillType property.
- Set a color for the slide’s background using SlideBackground.Fill.SolidColor.Color property.
- Save the result presentation using Presentation.SaveToFile() method.
- Python
from spire.presentation import *
# Create a Presentation object
ppt = Presentation()
# Load a PowerPoint presentation
ppt.LoadFromFile("Input.pptx")
# Get the first slide
slide = ppt.Slides[0]
# Access the background of the slide
background = slide.SlideBackground
# Set the type of the slide's background as a custom type
background.Type = BackgroundType.Custom
# Set the fill mode of the slide's background as a solid fill
background.Fill.FillType = FillFormatType.Solid
# Set a color for the slide's background
background.Fill.SolidColor.Color = Color.get_PaleTurquoise()
# Save the result presentation
ppt.SaveToFile("Solidbackground.pptx", FileFormat.Pptx2013)
ppt.Dispose()

Set a Gradient Background for a PowerPoint Slide in Python
Adding a gradient background is a little complex. You need to set the fill mode of the slide’s background as a gradient fill and then set the gradient stops and colors. The detailed steps are as follows.
- Create an object of the Presentation class.
- Load a PowerPoint presentation using Presentation.LoadFromFile() method.
- Get a specific slide using Presentation.Slides[index] property.
- Access the background of the slide using ISlide.SlideBackground property.
- Set the type of the slide's background as a custom type using SlideBackground.Type property.
- Set the fill mode of the slide’s background as a gradient fill using SlideBackground.Fill.FillType property.
- Set gradient stops and colors for the slide’s background using SlideBackground.Fill.Gradient.GradientStops.AppendByColor() method.
- Set the shape type and angle for the gradient fill.
- Save the result presentation using Presentation.SaveToFile() method.
- Python
from spire.presentation import *
# Create a Presentation object
ppt = Presentation()
# Load a PowerPoint presentation
ppt.LoadFromFile("Input.pptx")
# Get the first slide
slide = ppt.Slides[0]
# Access the background of the slide
background = slide.SlideBackground
# Set the type of the slide's background as a custom type
background.Type = BackgroundType.Custom
# Set the fill mode of the slide's background as a gradient fill
background.Fill.FillType = FillFormatType.Gradient
# Set gradient stops and colors
background.Fill.Gradient.GradientStops.AppendByColor(0.1, Color.get_LightCyan())
background.Fill.Gradient.GradientStops.AppendByColor(0.7, Color.get_LightSeaGreen())
# Set the shape type of the gradient fill
background.Fill.Gradient.GradientShape = GradientShapeType.Linear
# Set the angle of the gradient fill
background.Fill.Gradient.LinearGradientFill.Angle = 45
# Save the result presentation
ppt.SaveToFile("Gradientbackground.pptx", FileFormat.Pptx2013)
ppt.Dispose()

Set a Background Picture for a PowerPoint Slide in Python
To add a background picture for a PowerPoint slide, you need to set the fill mode of the slide's background as a picture fill, then add a picture to the image collection of the presentation and set it as the slide’s background. The detailed steps are as follows:
- Create an object of the Presentation class.
- Load a PowerPoint presentation using Presentation.LoadFromFile() method.
- Get a specific slide using Presentation.Slides[index] property.
- Access the background of the slide using ISlide.SlideBackground property.
- Set the type of the slide's background as a custom type using SlideBackground.Type property.
- Set the fill mode of the slide’s background as a picture fill using SlideBackground.Fill.FillType property.
- Add an image to the image collection of the presentation using Presentation.Images.AppendStream() method.
- Set the image as the slide’s background using SlideBackground.Fill.PictureFill.Picture.EmbedImage property.
- Save the result presentation using Presentation.SaveToFile() method.
- Python
from spire.presentation import *
# Create a Presentation object
ppt = Presentation()
# Load a PowerPoint presentation
ppt.LoadFromFile("Input.pptx")
# Get the first slide
slide = ppt.Slides[0]
# Access the background of the slide
background = slide.SlideBackground
# Set the type of the slide's background as a custom type
background.Type = BackgroundType.Custom
# Set the fill mode of the slide's background as a picture fill
background.Fill.FillType = FillFormatType.Picture
# Add an image to the image collection of the presentation
stream = Stream("background.jpg")
imageData = ppt.Images.AppendStream(stream)
# Set the image as the slide's background
background.Fill.PictureFill.FillType = PictureFillType.Stretch
background.Fill.PictureFill.Picture.EmbedImage = imageData
# Save the result presentation
ppt.SaveToFile("Picturebackground.pptx", FileFormat.Pptx2013)
ppt.Dispose()

Set a Background for a Slide Master in PowerPoint in Python
If you don't wish to set backgrounds for slides one by one, you can set a background for the slide master, then all slides using the same slide master will be applied with the background automatically. The following steps show how to set a solid background color for a slide master.
- Create an object of the Presentation class.
- Load a PowerPoint presentation using Presentation.LoadFromFile() method.
- Get a specific slide master using Presentation.Masters[index] property.
- Access the background of the slide master using IMasterSlide.SlideBackground property.
- Set the type of the slide master's background as a custom type using SlideBackground.Type property.
- Set the fill mode of the slide master's background as a solid fill using SlideBackground.Fill.FillType property.
- Set a color for the slide master's background using SlideBackground.Fill.SolidColor.Color property.
- Save the result presentation using Presentation.SaveToFile() method.
- Python
from spire.presentation import *
# Create a Presentation object
ppt = Presentation()
# Load a PowerPoint presentation
ppt.LoadFromFile("Input.pptx")
# Get the first slide master
slideMaster = ppt.Masters[0]
# Access the background of the slide master
background = slideMaster.SlideBackground
# Set the type of the slide master's background as a custom type
background.Type = BackgroundType.Custom
# Set the fill mode of the slide master's background as a solid fill
background.Fill.FillType = FillFormatType.Solid
# Set a color for the slide master's background
background.Fill.SolidColor.Color = Color.get_PeachPuff()
# Save the result presentation
ppt.SaveToFile("AddBackgroundToSlideMaster.pptx", FileFormat.Pptx2013)
ppt.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.
Comments in Microsoft PowerPoint allow users to add additional information to specific slides or elements of a slide to improve collaboration and communication when sharing presentations. These comments can be related content, suggestions for changes, and so on. This feature is very useful when several people are working on a presentation together. In this article, you will learn how to use Spire.Presentation for Python to add, remove or replace comments on slides in Python programs.
- Add Comments to a Presentation Slide in Python
- Remove Comments from a Presentation Slide in Python
- Replace Comments on a Presentation Slide in Python
Install Spire.Presentation for Python
This scenario requires Spire.Presentation for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip commands.
pip install Spire.Presentation
If you are unsure how to install, please refer to this tutorial: How to Install Spire.Presentation for Python on Windows
Add Comments to a Presentation Slide in Python
Spire.Presentation for Python provides the Presentation.CommentAuthors.AddAuthor() and Presentation.Slides[].AddComment(author:ICommentAuthor,text:str,position:PointF,dateTime:DateTime) methods to support adding comments to a slide. The detailed steps are as follows.
- Create a new PowerPoint presentation.
- Load a PowerPoint presentation using Presentation.LoadFromFile() method.
- Add the author of the comment by using Presentation.CommentAuthors.AddAuthor() method.
- Then add a comment to the first slide using Presentation.Slides[].AddComment(author:ICommentAuthor,text:str,position:PointF,dateTime:DateTime) method.
- Add another comment using the same method.
- Save the result file using Presentation.SaveToFile() method.
- Python
from spire.presentation.common import *
from spire.presentation import *
inputFile = "C:/Users/Administrator/Desktop/Sample.pptx"
outputFile = "C:/Users/Administrator/Desktop/AddComment.pptx"
# Create a Presentation instance
presentation = Presentation()
# Load a presentation from disk
presentation.LoadFromFile(inputFile)
# Add the author of the comment
author = presentation.CommentAuthors.AddAuthor("E-iceblue", "comment:")
# Add a comment to the first slide
point = PointF(45.0,12.0)
presentation.Slides[0].AddComment(author, "Overview", point, DateTime.get_Now())
# Add another comment to this slide
author = presentation.CommentAuthors.AddAuthor("E-iceblue", "comment:")
point = PointF(35.0,23.0)
presentation.Slides[0].AddComment(author, "Features", point, DateTime.get_Now())
# Save the result file
presentation.SaveToFile(outputFile, FileFormat.Pptx2010)
presentation.Dispose()

Remove Comments from a Presentation Slide in Python
You can also remove the specific comment from the slides by using Presentation.Slides[].DeleteComment(Comment) method. The detailed steps are as follows.
- Create a Presentation instance.
- Load a PowerPoint presentation using Presentation.LoadFromFile() method.
- Remove the first comment from the specified slide using Presentation.Slides[].DeleteComment(Comment) method.
- Save the result file using Presentation.SaveToFile() method.
- Python
from spire.presentation.common import * from spire.presentation import * inputFile = "C:/Users/Administrator/Desktop/AddComment.pptx" outputFile = "C:/Users/Administrator/Desktop/DeleteComment.pptx" # Create a Presentation instance presentation = Presentation() # Load a presentation from disk presentation.LoadFromFile(inputFile) # Delete the first comment from the first slide presentation.Slides[0].DeleteComment(presentation.Slides[0].Comments[0]) # Save the result file presentation.SaveToFile(outputFile, FileFormat.Pptx2010) presentation.Dispose()

Replace Comments on a Presentation Slide in Python
If you want to replace the comment content with new text, please use the Presentation.Slides[].Comments[].Text property. The detailed steps are as follows.
- Create a Presentation instance.
- Load a PowerPoint presentation using Presentation.LoadFromFile() method.
- Replace the content of the second comment with new text by Presentation.Slides[].Comments[].Text property.
- Save the result file using Presentation.SaveToFile() method.
- Python
from spire.presentation.common import * from spire.presentation import * inputFile = "C:/Users/Administrator/Desktop/AddComment.pptx" outputFile = "C:/Users/Administrator/Desktop/ReplaceComment.pptx" # Create a Presentation instance presentation = Presentation() # Load a presentation from disk presentation.LoadFromFile(inputFile) # Replace the content of the second comment with new text presentation.Slides[0].Comments[1].Text = "Replace comment" # Save the result file presentation.SaveToFile(outputFile, FileFormat.Pptx2010) presentation.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.
Hyperlinks in PDF documents are commonly used tools for navigating to internal or external related information. However, these links need to be accurate and up-to-date in order to be effective. Document editors are supposed to have the power to change or delete hyperlinks to update outdated references, rectify errors, comply with evolving web standards, or enhance accessibility. This article will demonstrate how to use Spire.PDF for Python to modify or remove hyperlinks in PDF documents to ensure accurate information dissemination, seamless navigation, and inclusive user experience.
- Update the Target Address of Hyperlinks in PDF Using Python
- Remove Hyperlinks in PDF Documents Using 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 Windows 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 on Windows
Update the Target Address of Hyperlinks in PDF Using Python
In PDF documents, hyperlinks are annotations displayed on the linked content on a page. Therefore, to modify hyperlinks in PDF documents, it is needed to retrieve all annotations on a page through PdfPageBase.AnnotationsWidget property. Then, a specific hyperlink annotation can be obtained from the annotation list and the target address can be updated through PdfTextWebLinkAnnotationWidget.Url property. The detailed steps are as follows:
- Create an object of PdfDocument class and load a PDF document using PdfDocument.LoadFromFile() method.
- Get a page of the document using PdfDocument.Pages.get_Item() method.
- Get all annotations on the page through PdfPageBase.AnnotationsWidget property.
- Get a hyperlink annotation and cast it to a PdfTextWebLinkAnnotationWidget object.
- Set a new target address for the hyperlink annotation through PdfTextWebLinkAnnotationWidget.Url property.
- Save the document using PdfDocument.SaveToFile() method.
- Python
from spire.pdf.common import *
from spire.pdf import *
# Create an object of PdfDocument class and load a PDF document
pdf = PdfDocument()
pdf.LoadFromFile("Sample.pdf")
# Get the first page of the document
page = pdf.Pages.get_Item(0)
# Get all annotations on the page
widgetCollection = page.AnnotationsWidget
# Get the second hyperlink annotation
annotation = widgetCollection.get_Item(1)
# Cast the hyperlink annotation to a PdfTextWebLinkAnnotationWidget object
link = PdfTextWebLinkAnnotationWidget(annotation)
# Set a new target address for the second hyperlink
link.Url = "https://www.mcafee.com/learn/understanding-trojan-viruses-and-how-to-get-rid-of-them/"
#Save the document
pdf.SaveToFile("output/ModifyPDFHyperlink.pdf")
pdf.Close()

Remove Hyperlinks in PDF Documents Using Python
Spire.PDF for Python enables developers to effortlessly remove specific hyperlinks on a page using the PdfPageBase.AnnotationsWidget.RemoveAt() method. Additionally, developers can also iterate through each page and its annotations to identify and eliminate all hyperlink annotations in the entire PDF document with the help of Spire.PDF for Python. The detailed steps are as follows:
- Create an object of PdfDocument class and load a PDF document using PdfDocument.LoadFromFile() method.
- To remove a specific hyperlink, get a page in the document using PdfDocument.Pages.get_Item() method and remove the hyperlink annotation using PdfPageBase.AnnotationsWidget.RemoveAt() method.
- To remove all hyperlinks in the document, loop through the pages in the document to get the annotations on each page through PdfPageBase.AnnotationsWidget property.
- Loop through the annotations to check if each annotation is an instance of PdfTextWebLinkAnnotationWidget class. If it is, remove it using PdfAnnotationCollection.Remove() method.
- Save the document using PdfDocument.SaveToFile() method.
- Python
from spire.pdf import *
from spire.pdf.common import *
# # Create an object of PdfDocument class and load a PDF document
pdf = PdfDocument()
pdf.LoadFromFile("Sample.pdf")
# Remove the first hyperlink on the first page
#page = pdf.Pages.get_Item(0)
#page.AnnotationsWidget.RemoveAt(0)
# Remove all hyperlinks
# Loop through the pages in the document
for j in range(pdf.Pages.Count):
# Get each page
page = pdf.Pages.get_Item(j)
# Get the annotations on each page
annotations = page.AnnotationsWidget
# Check if there is any annotations on a page
if annotations.Count > 0:
# Loop through the annotations
i = annotations.Count - 1
while i >=0:
# Get an annotation
annotation = annotations.get_Item(i)
# Check if each annotation is a hyperlink
if isinstance(annotation, PdfTextWebLinkAnnotationWidget):
# Remove hyperlink annotations
annotations.Remove(annotation)
i -= 1
# Save the document
pdf.SaveToFile("output/RemovePDFHyperlink.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.
A PDF portfolio is a collection of files assembled into a single PDF document. It serves as a comprehensive and interactive showcase of various types of content, such as documents, images, presentations, videos, and more. Unlike a traditional PDF document, a PDF portfolio allows you to present multiple files in a cohesive and organized manner, providing a seamless browsing experience for the viewer. In this article, we will demonstrate how to create a PDF portfolio and how to identify if a PDF is a portfolio 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 Windows 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 on Windows
Create a PDF Portfolio with Python
Spire.PDF for Python allows you to generate a PDF portfolio by adding files to a PDF using the PdfDocument.Collection.AddFile() method. Furthermore, you can organize the files within the PDF portfolio by adding folders using the PdfDocument.Collection.Folders.CreateSubfolder() method. The detailed steps are as follows.
- Specify the output file path and the folders where the files to be included in the PDF portfolio are located.
- Create a PdfDocument object.
- Iterate through the files in the first folder and add them to the PDF portfolio using the PdfDocument.Collection.AddFile() method.
- Iterate through the files in the second folder. For each file, create a separate folder within the PDF portfolio using the PdfDocument.Collection.Folders.CreateSubfolder() method, and then add the file to the corresponding folder using the PdfFolder.AddFile() method.
- Save the resulting PDF portfolio using the PdfDocument.SaveToFile() method.
- Python
from spire.pdf.common import *
from spire.pdf import *
import glob
# Specify the folders where the files to be included in the PDF portfolio are located
input_folder1 = "Folder1/*"
input_folder2 = "Folder2/*"
# Specify the output file path
output_file = "CreatePDFPortfolio.pdf"
# Create a PdfDocument object
doc = PdfDocument()
# Get the list of file paths in the first folder
files1 = glob.glob(input_folder1)
# Loop through the files in the list
for i, file in enumerate(files1):
# Add each file to the PDF portfolio
doc.Collection.AddFile(file)
# Get the list of file paths in the second folder
files2 = glob.glob(input_folder2)
# Loop through the files in the list
for j, file in enumerate(files2):
# Create a separate folder for each file
folder = doc.Collection.Folders.CreateSubfolder(f"SubFolder{j + 1}")
# Add the file to the folder
folder.AddFile(file)
# Save the resulting PDF portfolio to the specified file path
doc.SaveToFile(output_file)
# Close the PdfDocument object
doc.Close()

Identify if a PDF is a Portfolio with Python
You can use the PdfDocument.IsPortfolio property to easily identify whether a PDF document is a portfolio or not. The detailed steps are as follows.
- Specify the input and output file paths.
- Create a PdfDocument object.
- Load a PDF document using the PdfDocument.LoadFromFile() method.
- Identify whether the document is a portfolio or not using the PdfDocument.IsPortfolio property.
- Save the result to a text file.
- Python
from spire.pdf.common import *
from spire.pdf import *
# Specify the input and output file paths
input_file = "CreatePDFPortfolio.pdf"
output_file = "IsPDFPortfolio.txt"
# Create a PdfDocument object
doc = PdfDocument()
# Load a PDF document
doc.LoadFromFile(input_file)
# Identify whether the document is a portfolio or not
if doc.IsPortfolio:
st = "The document is a portfolio"
else:
st = "The document is not a portfolio"
# Save the result to a text file
with open(output_file, "w") as text_file:
text_file.write(st)
# Close the PdfDocument object
doc.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.
In a PowerPoint document, the choice of fonts plays a significant role in enhancing the overall visual appeal and effectiveness of the presentation. Different fonts can be used to establish a visual hierarchy, allowing you to emphasize key points, headings, or subheadings in your presentation and guide the audience's attention. This article introduces how to set or change fonts in a PowerPoint document in Python using Spire.Presentation for Python.
- Set Fonts when Creating a New PowerPoint Document in Python
- Change Fonts in an Existing PowerPoint Document in Python
Install Spire.Presentation for Python
This scenario requires Spire.Presentation for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip commands.
pip install Spire.Presentation
If you are unsure how to install, please refer to this tutorial: How to Install Spire.Presentation for Python on Windows
Set Fonts when Creating a New PowerPoint Document in Python
Spire.Presentation for Python offers the TextRange class to represent a range of text. A paragraph can consist of one or more text ranges. To apply font formatting to the characters in a text range, you can use the properties like LatinFont, IsBold, IsItalic, and FontHeight of the TextRange class. The following are the steps to set fonts when creating a new PowerPoint document in Python.
- Create a Presentation object.
- Get the first slide through Presentation.Slides[0] property.
- Add a shape to the slide using ISlide.Shapes.AppendShape() method.
- Add text to the shape using IAutoShape.AppendTextFrame() method.
- Get TextRange object through IAutoShape.TextFrame.TextRange property.
- Set the font information such as font name, font size, bold, italic, underline, and text color through the properties under the TextRange object.
- Save the presentation to a PPTX file using Presentation.SaveToFile() method.
- Python
from spire.presentation.common import *
import math
from spire.presentation import *
# Create a Presentation object
presentation = Presentation()
# Set slide size type
presentation.SlideSize.Type = SlideSizeType.Screen16x9
# Add a shape to the first slide
rec = RectangleF.FromLTRB (30, 100, 900, 250)
shape = presentation.Slides[0].Shapes.AppendShape(ShapeType.Rectangle, rec)
# Set line color and fill type of the shape
shape.ShapeStyle.LineColor.Color = Color.get_Transparent()
shape.Fill.FillType = FillFormatType.none
# Add text to the shape
shape.AppendTextFrame("Spire.Presentation for Python is a professional presentation processing API that \
is highly compatible with PowerPoint. It is a completely independent class library that developers can \
use to create, edit, convert, and save PowerPoint presentations efficiently without installing Microsoft PowerPoint.")
# Get text of the shape as a text range
textRange = shape.TextFrame.TextRange
# Set font name
textRange.LatinFont = TextFont("Times New Roman")
# Set font style (bold & italic)
textRange.IsBold = TriState.TTrue
textRange.IsItalic = TriState.TTrue
# Set underline type
textRange.TextUnderlineType = TextUnderlineType.Single
# Set font size
textRange.FontHeight = 22
# Set text color
textRange.Fill.FillType = FillFormatType.Solid
textRange.Fill.SolidColor.Color = Color.get_CadetBlue()
# Set alignment
textRange.Paragraph.Alignment = TextAlignmentType.Left
# Set line spacing
textRange.LineSpacing = 0.5
# Save to file
presentation.SaveToFile("output/SetFont.pptx", FileFormat.Pptx2019)
presentation.Dispose()

Change Fonts in an Existing PowerPoint Document in Python
To change the font for a specific paragraph, we need to get the paragraph from the document. Then, iterate through the text ranges in the paragraph and reset the font information for each text range. Below are the steps to change the font of a paragraph in an existing PowerPoint document using Spire.Presentation for Python.
- Create a Presentation object.
- Get a specific slide through Presentation.Slides[index] property.
- Get a specific shape through ISlide.Shapes[index] property.
- Get a specific paragraph of the shape through IAutoShape.TextFrame.Paragraphs[index] property.
- Iterate through the text ranges in the paragraph.
- Set the font information such as font name, font size, bold, italic, underline, and text color of a specific text range through the properties under the TextRange object.
- Save the presentation to a PPTX file using Presentation.SaveToFile() method.
- Python
from spire.presentation.common import *
from spire.presentation import *
# Create a Presentation object
presentation = Presentation()
# Load a PowerPoint file
presentation.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.pptx")
# Get the first slide
slide = presentation.Slides[0]
"# Get the first shape on the slide
shape = (IAutoShape)(slide.Shapes[0])
# Get the first paragraph of the shape
paragraph = shape.TextFrame.Paragraphs[0]
# Get the first paragraph of the shape
paragraph = shape.TextFrame.Paragraphs[0]
# Create a font
newFont = TextFont("Times New Roman")
# Loop through the text ranges in the paragraph
for textRange in paragraph.TextRanges:
# Apply font to a specific text range
textRange.LatinFont = newFont
# Set font to Italic
textRange.Format.IsItalic = TriState.TTrue
# Set font size
textRange.FontHeight = 25
# Set font color
textRange.Fill.FillType = FillFormatType.Solid
textRange.Fill.SolidColor.Color = Color.get_Purple()
# Save to file
presentation.SaveToFile("output/ChangeFont.pptx", FileFormat.Pptx2019)
presentation.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.
Setting the background colors for paragraphs and text in Word documents can significantly enhance the presentation and readability of content. Customizing background color is an effective approach to emphasize key information, categorize content, and add a personalized touch, thereby making it easy to create polished and professional documents. By carefully selecting and applying background colors, documents can be transformed into visually appealing works that effectively convey information and engage the reader. This article shows how to use Spire.Doc for Python to set background colors for paragraphs and text in Word documents, unlocking new possibilities for document styling and customization.
- Set Background Colors for Paragraphs Using Python
- Set Background Colors for Selected Text Using Python
Install Spire.Doc for Python
This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.
pip install Spire.Doc
If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python on Windows
Set Background Color for Paragraphs Using Python
By using Spire.Doc for Python, developers can get any paragraph in any section. After getting a paragraph, developers can apply a background color to it by assigning a Color object to Paragraph.Format.BackColor property. Below are the detailed steps:
- Create an instance of Document class and load a Word document using Document.LoadFromFile() method.
- Get a section using Document.Sections.get_Item() method.
- Get a paragraph in the section using Section.Paragraphs.get_Item() method.
- Set the background color of the paragraph through Paragraph.Format.BackColor property.
- Save the document using Document.SaveToFile() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create an instance of Document class and load a Word document
doc = Document()
doc.LoadFromFile("Sample.docx")
# Get the first section
section = doc.Sections.get_Item(0)
# Get the fifth paragraph
paragraph = section.Paragraphs.get_Item(4)
# Set background color for the paragraph
paragraph.Format.BackColor = Color.get_DarkGreen()
# Save the document
doc.SaveToFile("output/ParagraphBackground.docx")
doc.Close()

Set Background Colors for Selected Text Using Python
Spire.Doc for Python enables developers to find all the occurrences of specific text in a Word document with Document.FindAllString() method. After getting the finding results, developers can set the background for them through TextRange.CharacterFormat.TextBackgroundColor property. The detailed steps are as follows:
- Create an instance of Document class and load a Word document using Document.LoadFromFile() method.
- Find all the occurrences of specific text using Document.FindAllString() method.
- Loop through the occurrences, get each occurrence as a text range using TextSelection.GetAsOneRange(True) method, and set the background color of each occurrence through TextRange.CharacterFormat.TextBackgroundColor property. It is also possible to get only one occurrence from the result list and set the background color for the occurrence.
- Save the document using Document.SaveToFile() method.
- Python
from spire.doc import *
from spire.doc.common import *
# Create an instance of Document class and load a Word document
doc = Document()
doc.LoadFromFile("Sample.docx")
# Find text in the Word document
findResults = doc.FindAllString("advantages of LCD screens", False, False)
# Loop through the finding results to set background color for all occurrences
for text in findResults:
# Get an occurrence as a text range
textRange = text.GetAsOneRange(True)
# Set the background color of the text range
textRange.CharacterFormat.TextBackgroundColor = Color.get_LightCoral()
# Set the background color of a sepecified occurrence
# Get an occurrence as one text range
# textRange = findResults[1].GetAsOneRange()
# Set the background color of the text range
# textRange.CharacterFormat.BackgroundColor = Color.get_DarkCyan()
# Save the document
doc.SaveToFile("output/TextBackground.docx")
doc.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.
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 Windows 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 on Windows
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()

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.
Hyperlinks in PDF are interactive elements that, when clicked, can jump to a specific location in the document, to an external website, or to other resources. By inserting hyperlinks in a PDF document, you can provide supplementary information and enhance the overall integrity of the document. This article will demonstrate how to add hyperlinks to PDF files 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 Windows 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 on Windows
Add Hyperlinks to a PDF Document in Python
With Spire.PDF for Python, you can add web links, email links and file links to a PDF document. The following are the detailed steps:
- Create a pdf document and add a page to it.
- Specify a URL address and draw it directly on the page using PdfPageBase.Canvas.DrawString() method.
- Create a PdfTextWebLink object.
- Set the link's display text, URL address, and the font and brush used to draw it using properties of PdfTextWebLink class.
- Draw the link on the page using PdfTextWebLink.DrawTextWebLink() method.
- Create a PdfFileLinkAnnotation object and with a specified file.
- Add the file link to the page annotations using PdfPageBase.AnnotationsWidget.Add(PdfFileLinkAnnotation) method.
- Draw hypertext of the file link using PdfPageBase.Canvas.DrawString() method.
- Save the result file using PdfDocument.SaveToFile() method.
- Python
from spire.pdf.common import *
from spire.pdf import *
# Create a PdfDocument instance
pdf = PdfDocument()
# Add a page
page = pdf.Pages.Add()
# Initialize x, y coordinates
y = 30.0
x = 10.0
# Create true type fonts
font = PdfTrueTypeFont("Arial", 14.0,PdfFontStyle.Regular,True)
font1 = PdfTrueTypeFont("Arial", 14.0, PdfFontStyle.Underline,True)
# Add a simply link
label = "Simple Text Link: "
format = PdfStringFormat()
format.MeasureTrailingSpaces = True
page.Canvas.DrawString(label, font, PdfBrushes.get_Orange(), 0.0, y, format)
x = font.MeasureString(label, format).Width
url = "http://www.e-iceblue.com"
page.Canvas.DrawString(url, font1, PdfBrushes.get_Blue(), x, y)
y = y + 28
# Add a hypertext link
label = "Hypertext Link: "
page.Canvas.DrawString(label, font, PdfBrushes.get_Orange(), 0.0, y, format)
x = font.MeasureString(label, format).Width
webLink = PdfTextWebLink()
webLink.Text = "Home Page"
webLink.Url = url
webLink.Font = font1
webLink.Brush = PdfBrushes.get_Blue()
webLink.DrawTextWebLink(page.Canvas, PointF(x, y))
y = y + 28
# Add an Email link
label = "Email Link: "
page.Canvas.DrawString(label, font, PdfBrushes.get_Orange(), 0.0, y, format)
x = font.MeasureString(label, format).Width
link = PdfTextWebLink()
link.Text = "Contact Us"
link.Url = "mailto:support@e-iceblue.com"
link.Font = font1
link.Brush = PdfBrushes.get_Blue()
link.DrawTextWebLink(page.Canvas, PointF(x, y))
y = y + 28
# Add a file link
label = "Document Link: "
page.Canvas.DrawString(label, font, PdfBrushes.get_Orange(), 0.0, y, format)
x = font.MeasureString(label, format).Width
text = "Open File"
location = PointF(x, y)
size = font1.MeasureString(text)
linkBounds = RectangleF(location, size)
fileLink = PdfFileLinkAnnotation(linkBounds,"C:\\Users\\Administrator\\Desktop\\Report.xlsx")
fileLink.Border = PdfAnnotationBorder(0.0)
page.AnnotationsWidget.Add(fileLink)
page.Canvas.DrawString(text, font1, PdfBrushes.get_Blue(), x, y)
#Save the result pdf file
pdf.SaveToFile("AddLinkstoPDF.pdf")
pdf.Close()

Insert Hyperlinks into Existing Text in PDF in Python
Adding a hyperlink to existing text in a PDF document requires locating the text first. Once the location has been obtained, an object of PdfUriAnnotation class with the link can be created and added to the position. The following are the detailed steps:
- Create a PdfDocument instance.
- Load a PDF file using PdfDocument.LoadFromFile() method.
- Get the first page using PdfDocument.Pages property.
- Find all occurrences of the specified text on the page using PdfPageBase.FindText() method.
- Loop through all occurrences of the found text and create a PdfUriAnnotation instance based on the text bounds of each occurrence.
- Set the hyperlink URL, border, and border color using properties under PdfUriAnnotation class.
- Insert the hyperlink to the page annotations using PdfPageBase.AnnotationsWidget.Add(PdfUriAnnotation) method.
- Save the PDF file using PdfDocument.SaveToFile() method.
- Python
from spire.pdf.common import *
from spire.pdf import *
# Create a PdfDocument instance
pdf = PdfDocument()
# Load a PDF file
pdf.LoadFromFile("input.pdf")
# Get the first page
page = pdf.Pages.get_Item(0)
# Find all occurrences of the specified text on the page
collection = page.FindText("big O notation", TextFindParameter.IgnoreCase)
# Loop through all occurrences of the specified text
for find in collection.Finds:
# Create a hyperlink annotation
uri = PdfUriAnnotation(find.Bounds)
# Set the URL of the hyperlink
uri.Uri = "https://en.wikipedia.org/wiki/Big_O_notation"
# Set the border of the hyperlink annotation
uri.Border = PdfAnnotationBorder(1.0)
# Set the color of the border
uri.Color = PdfRGBColor(Color.get_Blue())
# Add the hyperlink annotation to the page
page.AnnotationsWidget.Add(uri)
#Save the result file
pdf.SaveToFile("SearchTextAndAddHyperlink.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.