
Python (318)
One powerful feature that enhances the interactivity and utility of PDF documents is the actions in these documents. By embedding actions such as document jumping, navigation controls, or even media playing, users can transform static documents into dynamic tools that streamline workflows, improve user engagement, and automate routine tasks, making the use of PDFs more efficient and versatile than ever before. This article will show how to use Spire.PDF for Python to create actions in PDF documents with Python code effortlessly.
- Create a Navigation Action in PDF with Python
- Create a Sound Action in PDF with Python
- Create a File Open Action in PDF with 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: How to Install Spire.PDF for Python on Windows
Create a Navigation Action in PDF with Python
A navigation button is an action that allows users to jump to a specified position on a designated page within a document. Developers can create a PdfDestination object, use it to create a PdfGoToAction, and then create an annotation based on this object and add it to the page to complete the creation of the navigation button. The following are the detailed steps:
- Create an object of PdfDocument class and load a PDF document using PdfDocument.LoadFromFile() method.
- Create a PdfDestination object and set its property.
- Create a PdfGoToAction object based on the destination.
- Draw a rectangle on a page using PdfPageBase.Canvas.DrawRectangle() method.
- Create a PdfActionAnnotation object based on the action and add it to the page using PdfPageBase.Annotations.Add() method.
- Save the document using PdfDocument.SaveToFile() method.
- Python
from spire.pdf import * # Create an instance of PdfDocument class and load a PDF document pdf = PdfDocument() pdf.LoadFromFile("Sample.pdf") # Create a PdfDestination instance and set its properties destination = PdfDestination(pdf.Pages[0]) destination.Location = PointF(0.0, 0.0) destination.Mode = PdfDestinationMode.Location destination.Zoom = 0.8 # Create a rectangle rect = RectangleF.FromLTRB(70, pdf.PageSettings.Size.Height - 120, 140, pdf.PageSettings.Size.Height - 100) # Create a PdfGoToAction instance action = PdfGoToAction(destination) # Draw a rectangle on the second page pdf.Pages.get_Item(1).Canvas.DrawRectangle(PdfBrushes.get_LightGray(), rect) # Draw text of the button font = PdfFont(PdfFontFamily.TimesRoman, 14.0) stringFormat = PdfStringFormat(PdfTextAlignment.Center) pdf.Pages.get_Item(1).Canvas.DrawString("To Page 1", font, PdfBrushes.get_Green(), rect, stringFormat) # Create a PdfActionAnnotation instance annotation = PdfActionAnnotation(rect, action) # Add the annotation to the second page pdf.Pages.get_Item(1).Annotations.Add(annotation) # Save the document pdf.SaveToFile("output/AddPDFNavigationButton.pdf") pdf.Close()
Create a Sound Action in PDF with Python
Developers can embed audio as actions in PDF documents, which allows the audio to play when the user performs a specified action, such as playing when the file opens or when a button is clicked. The following are the steps for creating a sound action:
- Create an instance of PdfDocument class.
- Load a PDF document using PdfDocument.LoadFromFile() method.
- Create an instance of PdfSoundAction class with an audio file.
- Set the audio parameters through properties under PdfSound class.
- Set the playing parameters through properties under PdfSoundAction class.
- Get a page using PdfDocument.Pgaes.get_Item(() method.
- Draw an image on the page using PdfPageBase.Canvas.Draw() method.
- Create a PdfActionAnnotation object with the sound action at the location of the image.
- Add the annotation to the page
- Or you can only set the sound action as the action performed after the document is opened through PdfDocument.AfterOpenAction property. This doesn’t need to add it as an annotation on a PDF page.
- Save the document using PdfDocument.SaveToFile() method.
- Python
from spire.pdf import * # Create a PdfDocument instance and load a PDF file pdf = PdfDocument() pdf.LoadFromFile("Sample.pdf") # Get the first page of the document page = pdf.Pages.get_Item(0) # Create an instance of PdfSoundAction with the sound file path soundAction = PdfSoundAction("Wave.wav") # Set the audio parameters soundAction.Sound.Bits = 16 soundAction.Sound.Channels = PdfSoundChannels.Stereo soundAction.Sound.Encoding = PdfSoundEncoding.Signed soundAction.Sound.Rate = 44100 # Set the playing parameters soundAction.Volume = 0.5 soundAction.Repeat = True soundAction.Mix = True soundAction.Synchronous = False # Draw an image on the page image = PdfImage.FromFile("Sound.png") page.Canvas.DrawImage(image, PointF(30.0, 30.0)) # Create an instance of PdfActionAnnotation with the sound action rect = RectangleF.FromLTRB(30.0, 30.0, image.GetBounds().Width + 30.0, image.GetBounds().Height + 30.0) annotation = PdfActionAnnotation(rect, soundAction) # Add the annotation to the page page.Annotations.Add(annotation) # Set the sound action to play after the document is opened # pdf.AfterOpenAction = soundAction # Save the document pdf.SaveToFile("output/AddMusicPDF.pdf") pdf.Close()
Create a File Open Action in PDF with Python
The PdfLaunchAction class represents a file open action in PDF that allows users to open the corresponding file by clicking on a button on a PDF page. Developers can specify the absolute or relative path of the file to be opened and whether to open in a new window when creating a file open action. The detailed steps for creating a file open action in a PDF document 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.
- Draw a rectangle on the page using PdfPageBase.Canvas.DrawRectangle() method.
- Create an object of PdfLaunchAction class and specify the file path and path type.
- Set the opening mode to new window through PdfLaunchAction.IsNewWindow property.
- Create an object of PdfActionAnnotation class based on the action and set its color through PdfActionAnnotation.Color property.
- Add the annotation to the page using PdfPageBase.Annotations.Add() method.
- Save the document using PdfDocument.SaveToFile() method.
- Python
from spire.pdf import * # Create an instance of PdfDocument class pdf = PdfDocument() # Load a PDF file pdf.LoadFromFile("Sample.pdf") # Get the first page of the document page = pdf.Pages.get_Item(0) # Draw a rectangle on the page rect = RectangleF.FromLTRB(50, pdf.PageSettings.Size.Height - 100, 200, pdf.PageSettings.Size.Height - 80) page.Canvas.DrawRectangle(PdfPens.get_LightGray(), rect) # Draw text in the rectangle page.Canvas.DrawString("Click to open Sample 2", PdfFont(PdfFontFamily.Helvetica, 14.0), PdfBrushes.get_Green(), rect, PdfStringFormat(PdfTextAlignment.Center)) # Create a PdfLaunchAction object action = PdfLaunchAction("Sample2.pdf", PdfFilePathType.Relative) action.IsNewWindow = True # Create a PdfActionAnnotation object based on the action annotation = PdfActionAnnotation(rect, action) annotation.Color = PdfRGBColor(Color.get_Blue()) # Add the annotation to the page page.Annotations.Add(annotation) # Save the document pdf.SaveToFile("output/CreatePDFLaunchAction.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.
Proper presentation of a PDF document is critical for maintaining its accuracy and professionalism. By checking the orientation and rotation of each PDF page, you can confirm that all elements, including diagrams and images, are displayed correctly as intended on the viewing device or platform, thus avoiding confusion or misinterpretation of content. In this article, you will learn how to detect the orientation and rotation angle of a PDF page in Python using Spire.PDF for Python.
Install Spire.PDF for Python
This scenario requires Spire.PDF for Python. It 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
Detect PDF Page Orientation in Python
Page orientation is determined by the relationship between page width and height. Using Spire.PDF for Python, you can compare these two values to detect whether a page is landscape (width greater than height) or portrait (width less than height). The following are the detailed steps.
- Create 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.
- Compare the values of page width and height to detect the page orientation.
- Print out the result.
- Python
from spire.pdf.common import * from spire.pdf import * # Create a PdfDocument object pdf = PdfDocument() # Load a PDF file from disk pdf.LoadFromFile("SamplePDF.pdf") # Get the first page page = pdf.Pages[0] # Get the width and height of the page Width = page.Size.Width Height = page.Size.Height # Compare the values of page width and height if Width > Height: print("The page orientation is Landscape.") else: print("The page orientation is Portrait.")
Detect PDF Page Rotation Angle in Python
PDF pages can be rotated by a certain angle. To detect the rotation angle of a PDF page, you can use the PdfPageBase.Rotation property. The following are the detailed steps.
- Create a PdfDocument instance.
- Load a PDF file using PdfDocument.LoadFromFile() method.
- Get a specified page using PdfDocument.Pages[] property.
- Get the rotation angle of the page using PdfPageBase.Rotation property, and then convert it to text string.
- Print out the result.
- Python
from spire.pdf.common import * from spire.pdf import * # Create a PdfDocument object pdf = PdfDocument() # Load a PDF file from disk pdf.LoadFromFile("Sample.pdf") # Get the first page page = pdf.Pages[0] # Get the rotation angle of the current page rotationAngle = page.Rotation rotation = str(rotationAngle) # Print out the result print("The rotation angle is: " + rotation)
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.
Digital signatures are vital for maintaining the authenticity and integrity of PDF documents. They provide a reliable way to verify the signer's identity and ensure that the document's content has not been tampered with since the signature was applied. By using digital signatures, you can enhance the security and trustworthiness of your documents. In this article, we will explore how to add and remove digital signatures in PDF files in Python using Spire.PDF for Python.
- Add a Digital Signature to PDF in Python
- Add an Invisible Digital Signature to PDF in Python
- Remove Digital Signature from PDF in 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 a Digital Signature to PDF in Python
You can use the PdfOrdinarySignatureMaker.MakeSignature(sigFieldName: str, page: PdfPageBase, x: float, y: float, width: float, height: float, signatureAppearance: IPdfSignatureAppearance) method to add a visible digital signature with a custom appearance to a specific page of a PDF document. The detailed steps are as follows.
- Create a PdfDocument instance.
- Load a PDF document using PdfDocument.LoadFromFile() method.
- Create a PdfOrdinarySignatureMaker instance and pass the PdfDocument object, certificate (.pfx) file path and certificate password to the class instructor as parameters.
- Set signature details, such as the signer’s name, contact information, location, and signature reason, using the properties of the PdfOrdinarySignatureMaker class.
- Create a PdfSignatureAppearance instance for the signature, and then customize the labels for the signature and set the signature image.
- Get a specific page in the PDF document using PdfDocument.Pages[] property.
- Call the PdfOrdinarySignatureMaker.MakeSignature(sigFieldName: str, page: PdfPageBase, x: float, y: float, width: float, height: float, signatureAppearance: IPdfSignatureAppearance) method to add the digital signature to a specific location of the page.
- Save the result document using the PdfDocument.SaveToFile() method.
- Python
from spire.pdf.common import * from spire.pdf import * # Create a PdfDocument instance doc = PdfDocument() # Load a PDF file doc.LoadFromFile("Sample.pdf") # Create a signature maker signatureMaker = PdfOrdinarySignatureMaker(doc, "gary.pfx", "e-iceblue") # Configure the signature properties like the signer's name, contact information, location and signature reason signature = signatureMaker.Signature signature.Name = "Gary" signature.ContactInfo = "+86 12345678" signature.Location = "China" signature.Reason = "I am the author." # Create a custom signature appearance appearance = PdfSignatureAppearance(signature) # Set label for the signer's name appearance.NameLabel = "Signer: " # Set label for the contact information appearance.ContactInfoLabel = "Phone: " # Set label for the location appearance.LocationLabel = "Location: " # Set label for the signature reason appearance.ReasonLabel = "Reason: " # Set signature image appearance.SignatureImage = PdfImage.FromFile("SigImg.png") # Set the graphic render/display mode for the signature appearance.GraphicMode = GraphicMode.SignImageAndSignDetail # Set the layout for the signature image appearance.SignImageLayout = SignImageLayout.none # Get the first page page = doc.Pages[0] # Add the signature to a specified location of the page signatureMaker.MakeSignature("Signature by Gary", page, 90.0, 600.0, 260.0, 100.0, appearance) # Save the signed document doc.SaveToFile("Signed.pdf") doc.Close()
Add an Invisible Digital Signature to PDF in Python
An invisible signature in a PDF is a type of digital signature that provides all the security and authentication benefits of a standard digital signature but does not appear visibly on the document itself. Using the PdfOrdinarySignatureMaker.MakeSignature(sigFieldName: str) method of Spire.PDF for Python, you can add an invisible digital signature to a PDF document. The detailed steps are as follows.
- Create a PdfDocument instance.
- Load a PDF document using PdfDocument.LoadFromFile() method.
- Create a PdfOrdinarySignatureMaker instance and pass the PdfDocument object, certificate (.pfx) file path and password to the class instructor as parameters.
- Add an invisible digital signature to a PDF document using the PdfOrdinarySignatureMaker.MakeSignature(sigFieldName: str) method
- Save the result document using the PdfDocument.SaveToFile() method.
- Python
from spire.pdf.common import * from spire.pdf import * # Create a PdfDocument instance doc = PdfDocument() # Load a PDF document doc.LoadFromFile("test2.pdf") # Create a signature maker signatureMaker = PdfOrdinarySignatureMaker(doc, "gary.pfx", "e-iceblue") # Add an invisible signature to the document signatureMaker.MakeSignature("Signature by Gary") # Save the signed document doc.SaveToFile("InvisibleSignature.pdf") doc.Close()
Remove Digital Signature from PDF in Python
To remove digital signatures from a PDF document, you need to iterate through all form fields in the document, find the form fields that are of PdfSignatureFieldWidget type and then remove them from the document. The detailed steps are as follows.
- Create a PdfDocument instance.
- Load a PDF document using PdfDocument.LoadFromFile() method.
- Get the form field collection of the document using PdfDocument.Form property.
- Iterate through the form fields in the collection from the last to the first.
- Check if the field is a PdfSignatureFieldWidget object.
- If the result is True, remove the field from the document using PdfFormFieldWidgetCollection.FieldsWidget.RemoveAt(index) method.
- Save the result document using the PdfDocument.SaveToFile() method.
- Python
from spire.pdf.common import * from spire.pdf import * # Create a PdfDocument instance doc = PdfDocument() # Load a PDF document doc.LoadFromFile("Signed.pdf") # Get form field collection from the document pdfForm = doc.Form formWidget = PdfFormWidget(pdfForm) # Check if there are any form fields in the collection if formWidget.FieldsWidget.Count > 0: # Loop through all form fields from the last to the first for i in range(formWidget.FieldsWidget.Count - 1, -1, -1): field = formWidget.FieldsWidget[i] # Check if the field is a PdfSignatureFieldWidget if isinstance(field, PdfSignatureFieldWidget): # Remove the field formWidget.FieldsWidget.RemoveAt(i) # Save the document doc.SaveToFile("RemoveSignature.pdf") 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 Microsoft PowerPoint, animations are not limited to just text; they can also be applied to shapes or other objects to create dynamic and engaging slides. Animations can be used to achieve various effects, such as drawing attention to a specific shape, demonstrating a process, or simply adding a touch of flair to your presentation. For instance, you might want to animate a shape to make it appear, disappear, or move in a particular sequence. Additionally, extracting and reusing animations can save time and ensure consistency across multiple presentations. In this article, we will demonstrate how to add animations to shapes in PowerPoint along with how to extract animation information from slides in PowerPoint in Python using Spire.Presentation for Python.
- Add Animations to Shapes and Text within Shapes in PowerPoint in Python
- Add Exit Animations to Shapes in PowerPoint in Python
- Extract the Animation Information from PowerPoint Slides 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
Add Animations to Shapes and Text within Shapes in PowerPoint in Python
You can use the IShape.Slide.Timeline.MainSequence.AddEffect(shape:IShape, animationEffectType:AnimationEffectType) method to add an animation effect to a shape. If you want to apply the animation effect to the text of a specific paragraph(s) within a shape, you can use the AnimationEffect.SetStartEndParagraph(startParaIndex:int, endParaIndex:int) method. The detailed steps are as follows.
- Create an instance of the Presentation class.
- Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
- Access a specific slide using the Presentation.Slides[] property.
- Add a rectangle shape to the slide using the ISlide.Shapes.AppendShape(shapeType:ShapeType, rectangle:RectangleF) method.
- Set the fill type, fill color, and border color for the rectangle.
- Add a text frame to the rectangle using the IShape.AppendTextFrame() method.
- Add an animation effect to the rectangle using IShape.Slide.Timeline.MainSequence.AddEffect(shape:IShape, animationEffectType:AnimationEffectType) method.
- Add another animation effect to the rectangle. Then apply the animation effect to specific paragraph(s) within the rectangle using the AnimationEffect.SetStartEndParagraph(startParaIndex:int, endParaIndex:int) method.
- Save the result presentation using the Presentation.SaveToFile() method.
- Python
from spire.presentation.common import * from spire.presentation import * # Create an object of the Presentation class ppt = Presentation() # Get the first slide in the presentation slide = ppt.Slides[0] # Add a rectangle shape to the slide shape = slide.Shapes.AppendShape(ShapeType.Rectangle, RectangleF.FromLTRB(100, 150, 300, 230)) # Set an alternative title for the shape (optional) shape.AlternativeTitle = "Rectangle" # Set the fill type, fill color and border color for the shape shape.Fill.FillType = FillFormatType.Solid shape.Fill.SolidColor.Color = Color.get_LightBlue() shape.ShapeStyle.LineColor.Color = Color.get_White() # Add a text frame to the shape and set the text content shape.AppendTextFrame("Animated Shape") # Add the 'fade-out swivel' animation effect to the shape shape.Slide.Timeline.MainSequence.AddEffect(shape, AnimationEffectType.FadedSwivel) # Add the 'float' animation effect to the shape animation = shape.Slide.Timeline.MainSequence.AddEffect(shape, AnimationEffectType.Float) # Set the start and end index of the paragraph(s) to apply the 'float' animation animation.SetStartEndParagraphs(0, 0) # Save the presentation to a new file ppt.SaveToFile("ApplyAnimation.pptx", FileFormat.Pptx2013) ppt.Dispose()
Add Exit Animations to Shapes in PowerPoint in Python
In PowerPoint, animations are categorized into four main types: entrance, emphasis, exit, and motion paths. Some animations, like "fly in" or "fade", can be used as both entrance and exit effects. When using Spire.Presentation to add these animations to shapes in your presentations, these animations are typically set as entrance effects by default. If you want to change the type of the animation to exit, you can use the AnimationEffect.PresetClassType property. The detailed steps are as follows.
- Create an instance of the Presentation class.
- Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
- Access a specific slide using the Presentation.Slides[] property.
- Add a cube shape to the slide using the ISlide.Shapes.AppendShape(shapeType:ShapeType, rectangle:RectangleF) method.
- Set the fill type, fill color, and border color for the cube.
- Add a text frame to the cube using the IShape.AppendTextFrame() method.
- Add an animation effect to the cube using the IShape.Slide.Timeline.MainSequence.AddEffect(shape:IShape, animationEffectType:AnimationEffectType) method.
- Change the animation effect type to exit using the AnimationEffect.PresetClassType property.
- Save the presentation using the Presentation.SaveToFile() method.
- Python
from spire.presentation.common import * from spire.presentation import * # Create an object of the Presentation class ppt = Presentation() # Get the first slide in the presentation slide = ppt.Slides[0] # Add a cube shape to the slide shape = slide.Shapes.AppendShape(ShapeType.Cube, RectangleF.FromLTRB(100, 150, 300, 230)) # Set an alternative title for the shape (optional) shape.AlternativeTitle = "Cube" # Set the fill type, fill color and border color for the shape shape.Fill.FillType = FillFormatType.Solid shape.Fill.SolidColor.Color = Color.get_LightBlue() shape.ShapeStyle.LineColor.Color = Color.get_White() # Add a text frame to the shape and set the text content shape.AppendTextFrame("Exit Animation") # Add a 'random bars' animation effect to the shape effect = shape.Slide.Timeline.MainSequence.AddEffect(shape, AnimationEffectType.RandomBars) # Set the animation effect type to exit animation effect.PresetClassType = TimeNodePresetClassType.Exit # Save the presentation to a new file ppt.SaveToFile("ExitAnimation.pptx", FileFormat.Pptx2013) ppt.Dispose()
Extract the Animation Information from PowerPoint Slides in Python
To extract animation information from slides in a PowerPoint presentation, you need to iterate through all slides and all animations within each slide, then use the properties of the AnimationEffect class to retrieve the information of the animations. The detailed steps are as follows.
- Create an instance of the Presentation class.
- Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
- Iterate through all slides in the presentation and all animations within each slide.
- Use the AnimationEffect.ShapeTarget.AlternativeTitle property to get the title of the shape affected by the animation.
- Use the ISlide.SlideNumber property to get the number of the current slide.
- Use the AnimationEffect.AnimationEffectType property to get the type of animation effect.
- Use the AnimationEffect.Timing.Duration property to get the duration of the animation effect.
- Use the AnimationEffect.Timing.RepeatCount property to get the number of repetitions of the animation effect.
- Save the retrieved information to a text file.
- Python
from spire.presentation.common import * from spire.presentation import * # Create an object of the Presentation class ppt = Presentation() # Load a PowerPoint presentation ppt.LoadFromFile("ApplyAnimation.pptx") # Create a list to store the extracted animation information sb = [] # Iterate through all slides in the presentation for slide in ppt.Slides: # Iterate through all animation effects in the slide for effect in slide.Timeline.MainSequence: # Get the alternative title of the shape affected by the animation shapeTitle = effect.ShapeTarget.AlternativeTitle sb.append("Shape Title: " + shapeTitle) # Get the number of the current slide slideNumber = slide.SlideNumber sb.append("Current Slide Number: " + str(slideNumber)) # Get the type of the animation effect animationEffectType = effect.AnimationEffectType sb.append("Animation Effect Type: " + str(animationEffectType)) # Get the duration of the animation effect duration = effect.Timing.Duration sb.append("Animation Effect Duration: " + str(duration)) # Get the number of repetitions of the animation effect count = effect.Timing.RepeatCount sb.append("Animation Effect Repeat Count: " + str(count)) sb.append("\n") # Save the extracted animation information to a text file with open("AnimationInformation.txt", "w") as fp: for s in sb: fp.write(s + "\n") 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.
Adding annotations to PDFs is a common practice for adding comments, highlighting text, drawing shapes, and more. This feature is beneficial for collaborative document review, education, and professional presentations. It allows users to mark up documents digitally, enhancing communication and productivity.
In this article, you will learn how to add various types of annotations to a PDF document in Python using Spire.PDF for Python.
- Add a Text Markup Annotation to PDF
- Add a Free Text Annotation to PDF
- Add a Popup Annotation to PDF
- Add a Stamp Annotation to PDF
- Add a Shape Annotation to PDF
- Add a Web Link Annotation to PDF
- Add a File Link Annotation to PDF
- Add a Document Link Annotation to PDF
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 a Text Markup Annotation to PDF in Python
Text markup in PDF refers to the ability to emphasize important text by selecting and highlighting it. To add a text markup annotation to a PDF, you first need to locate the specific text within the document with the help of the PdfTextFinder class. Once the text is identified, you can create a PdfTextMarkupAnnotation object and apply it to the document.
The following are the steps to add a text markup annotation to PDF using Python:
- Create a PdfDocument object.
- Load a PDF file from the specified location.
- Get a page from the document.
- Find a specific piece of text within the page using PdfTextFinder class.
- Create a PdfTextMarkupAnnotation object based on the text found.
- Add the annotation to the page using PdfPageBase.AnnotationsWidget.Add() method.
- Save the modified document to a different PDF file.
- 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") # Get a specific page page = doc.Pages[0] # Create a PdfTextFinder object based on the page finder = PdfTextFinder(page) # Set the find options finder.Options.Parameter = TextFindParameter.WholeWord finder.Options.Parameter = TextFindParameter.IgnoreCase # Find the instances of the specified text fragments = finder.Find("However, we cannot and do not guarantee that these measures will prevent "+ "every unauthorized attempt to access, use, or disclose your information since "+ "despite our efforts, no Internet and/or other electronic transmissions can be completely secure."); # Get the first instance textFragment = fragments[0] # Specify annotation text text = "Here is a markup annotation." # Iterate through the text bounds for i in range(len(textFragment.Bounds)): # Get a specific bound rect = textFragment.Bounds[i] # Create a text markup annotation annotation = PdfTextMarkupAnnotation("Administrator", text, rect) # Set the markup color annotation.TextMarkupColor = PdfRGBColor(Color.get_Green()) # Add the annotation to the collection of the annotations page.AnnotationsWidget.Add(annotation) # Save result to file doc.SaveToFile("output/MarkupAnnotation.pdf") # Dispose resources doc.Dispose()
Add a Free Text Annotation to PDF in Python
Free text annotations allow adding freeform text comments directly on a PDF. To add a free text annotation at a specific location, you can use the PdfTextFinder class to obtain the coordinate information of the searched text, then create a PdfFreeTextAnnotation object based on that coordinates and add it to the document.
The following are the steps to add a free text annotation to PDF using Python:
- Create a PdfDocument object.
- Load a PDF file from the specified location.
- Get a page from the document.
- Find a specific piece of text within the page using PdfTextFinder class.
- Create a PdfFreeTextAnnotation object based on the coordinate information of the text found.
- Set the annotation content using PdfFreeTextAnnotation.Text property.
- Add the annotation to the page using PdfPageBase.AnnotationsWidget.Add() method.
- Save the modified document to a different PDF file.
- 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") # Get a specific page page = doc.Pages[0] # Create a PdfTextFinder object based on the page finder = PdfTextFinder(page) # Set the find options finder.Options.Parameter = TextFindParameter.WholeWord finder.Options.Parameter = TextFindParameter.IgnoreCase # Find the instances of the specified text fragments = finder.Find("Children"); # Get the first instance textFragment = fragments[0] # Get the text bound rect = textFragment.Bounds[0] # Get the coordinates to add annotation right = bound.Right top = bound.Top # Create a free text annotation rectangle = RectangleF(right + 5, top + 2, 160.0, 18.0) textAnnotation = PdfFreeTextAnnotation(rectangle) # Set the content of the annotation textAnnotation.Text = "Here is a free text annotation." # Set other properties of annotation font = PdfFont(PdfFontFamily.TimesRoman, 13.0, PdfFontStyle.Regular) border = PdfAnnotationBorder(1.0) textAnnotation.Font = font textAnnotation.Border = border textAnnotation.BorderColor = PdfRGBColor(Color.get_SkyBlue()) textAnnotation.Color = PdfRGBColor(Color.get_LightBlue()) textAnnotation.Opacity = 1.0 # Add the annotation to the collection of the annotations page.AnnotationsWidget.Add(textAnnotation) # Save result to file doc.SaveToFile("output/FreeTextAnnotation.pdf") # Dispose resources doc.Dispose()
Add a Popup Annotation to PDF in Python
A popup annotation allows for the display of additional information or content in a pop-up window. To get a specific position to add a popup annotation, you can still use the PdfTextFinder class. Once the coordinate information is obtained, you can create a PdfPopupAnnotation object and add it to the document.
The steps to add a popup annotation to PDF using Python are as follows:
- Create a PdfDocument object.
- Load a PDF file from the specified location.
- Get a page from the document.
- Find a specific piece of text within the page using PdfTextFinder class.
- Create a PdfPopupAnnotation object based on the coordinate information of the text found.
- Set the annotation content using PdfPopupAnnotation.Text property.
- Add the annotation to the page using PdfPageBase.AnnotationsWidget.Add() method.
- Save the modified document to a different PDF file.
- 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") # Get a specific page page = doc.Pages[0] # Create a PdfTextFinder object based on the page finder = PdfTextFinder(page) # Set the find options finder.Options.Parameter = TextFindParameter.WholeWord finder.Options.Parameter = TextFindParameter.IgnoreCase # Find the instances of the specified text fragments = finder.Find("Children"); # Get the first instance textFragment = fragments[0] # Get the text bound bound = textFragment.Bounds[0] # Get the coordinates to add annotation right = bound.Right top = bound.Top # Create a free text annotation rectangle = RectangleF(right + 5, top, 30.0, 30.0) popupAnnotation = PdfPopupAnnotation(rectangle) # Set the content of the annotation popupAnnotation.Text = "Here is a popup annotation." # Set the icon and color of the annotation popupAnnotation.Icon = PdfPopupIcon.Comment popupAnnotation.Color = PdfRGBColor(Color.get_Red()) # Add the annotation to the collection of the annotations page.AnnotationsWidget.Add(popupAnnotation) # Save result to file doc.SaveToFile("output/PopupAnnotation.pdf") # Dispose resources doc.Dispose()
Add a Stamp Annotation to PDF in Python
Stamp annotations in PDF documents are a type of annotation that allow users to add custom "stamps" or symbols to a PDF file. To define the appearance of a stamp annotation, use the PdfTemplate class. Then, create a PdfRubberStampAnnotation object and apply the previously defined template as its appearance. Finally, add the annotation to the PDF document.
The steps to add a stamp annotation to PDF using Python are as follows:
- Create a PdfDocument object.
- Load a PDF file from the specified location.
- Get a page from the document.
- Create a PdfTemplate object and draw an image on the template.
- Create a PdfRubberStampAnnotation object and apply the template as its appearance.
- Add the annotation to the page using PdfPageBase.AnnotationsWidget.Add() method.
- Save the modified document to a different PDF file.
- Python
from spire.pdf.common import * from spire.pdf import * # Create a PdfDocument object doc = PdfDocument() # Load a PDF document doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf") # Get a specific page page = doc.Pages[0] # Load an image file image = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\confidential.png") # Get the width and height of the image width = (float)(image.Width) height = (float)(image.Height) # Create a PdfTemplate object based on the size of the image template = PdfTemplate(width, height, True) # Draw image on the template template.Graphics.DrawImage(image, 0.0, 0.0, width, height) # Create a rubber stamp annotation, specifying its location and position rect = RectangleF((float) (page.ActualSize.Width/2 - width/2), 90.0, width, height) stamp = PdfRubberStampAnnotation(rect) # Create a PdfAppearance object pdfAppearance = PdfAppearance(stamp) # Set the template as the normal state of the appearance pdfAppearance.Normal = template # Apply the appearance to the stamp stamp.Appearance = pdfAppearance # Add the stamp annotation to PDF page.AnnotationsWidget.Add(stamp) # Save the file doc.SaveToFile("output/StampAnnotation.pdf") # Dispose resources doc.Dispose()
Add a Shape Annotation to PDF in Python
Shape annotations in PDF documents are a type of annotation that allow users to add various geometric shapes to the PDF file. Spire.PDF for Python offers the classes such as PdfPolyLineAnnotation, PdfLineAnnotation, and PdfPolygonAnnotation, allowing developers to add different types of shape annotations to PDF.
The steps to add a shape annotation to PDF using Python are as follows:
- Create a PdfDocument object.
- Load a PDF file from the specified location.
- Get a page from the document.
- Find a specific piece of text within the page using PdfTextFinder class.
- Create a PdfPolyLineAnnotation object based on the coordinate information of the text found.
- Set the annotation content using PdfPolyLineAnnotation.Text property.
- Add the annotation to the page using PdfPageBase.AnnotationsWidget.Add() method.
- Save the modified document to a different PDF file.
- 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") # Get a specific page page = doc.Pages[0] # Create a PdfTextFinder object based on the page finder = PdfTextFinder(page) # Set the find options finder.Options.Parameter = TextFindParameter.WholeWord finder.Options.Parameter = TextFindParameter.IgnoreCase # Find the instances of the specified text fragments = finder.Find("Children"); # Get the first instance textFragment = fragments[0] # Get the text bound bound = textFragment.Bounds[0] # Get the coordinates to add annotation left = bound.Left top = bound.Top right = bound.Right bottom = bound.Bottom # Create a shape annotation polyLineAnnotation = PdfPolyLineAnnotation(page, [PointF(left, top), PointF(right, top), PointF(right - 5, bottom), PointF(left - 5, bottom), PointF(left, top)]) # Set the annotation text polyLineAnnotation.Text = "Here is a shape annotation." # Add the annotation to the collection of the annotations page.AnnotationsWidget.Add(polyLineAnnotation) # Save result to file doc.SaveToFile("output/ShapeAnnotation.pdf") # Dispose resources doc.Dispose()
Add a Web Link Annotation to PDF in Python
Web link annotations in PDF documents enable users to embed clickable links to webpages, providing easy access to additional resources or related information online. You can use the PdfTextFinder class to find the specified text in a PDF document, and then create a PdfUriAnnotation object based on that text.
The following are the steps to add a web link annotation to PDF using Python:
- Create a PdfDocument object.
- Load a PDF file from the specified location.
- Get a page from the document.
- Find a specific piece of text within the page using PdfTextFinder class.
- Create a PdfUriAnnotation object based on the bound of the text.
- Add the annotation to the page using PdfPageBase.AnnotationsWidget.Add() method.
- Save the modified document to a different PDF file.
- 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") # Get a specific page page = doc.Pages[0] # Create a PdfTextFinder object based on the page finder = PdfTextFinder(page) # Set the find options finder.Options.Parameter = TextFindParameter.WholeWord finder.Options.Parameter = TextFindParameter.IgnoreCase # Find the instances of the specified text fragments = finder.Find("Children"); # Get the first instance textFragment = fragments[0] # Get the text bound bound = textFragment.Bounds[0] # Create a Url annotation urlAnnotation = PdfUriAnnotation(bound, "https://www.e-iceblue.com/"); # Add the annotation to the collection of the annotations page.AnnotationsWidget.Add(urlAnnotation) # Save result to file doc.SaveToFile("output/WebLinkAnnotation.pdf") # Dispose resources doc.Dispose()
Add a File Link Annotation to PDF in Python
A file link annotation in a PDF document is a type of annotation that allows users to create a clickable link to an external file, such as another PDF, image, or document. Still, you can use the PdfTextFinder class to find the specified text in a PDF document, and then create a PdfFileLinkAnnotation object based on that text.
The following are the steps to add a file link annotation to PDF using Python:
- Create a PdfDocument object.
- Load a PDF file from the specified location.
- Get a page from the document.
- Find a specific piece of text within the page using PdfTextFinder class.
- Create a PdfFileLinkAnnotation object based on the bound of the text.
- Add the annotation to the page using PdfPageBase.AnnotationsWidget.Add() method.
- Save the modified document to a different PDF file.
- 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") # Get a specific page page = doc.Pages[0] # Create a PdfTextFinder object based on the page finder = PdfTextFinder(page) # Set the find options finder.Options.Parameter = TextFindParameter.WholeWord finder.Options.Parameter = TextFindParameter.IgnoreCase # Find the instances of the specified text fragments = finder.Find("Children"); # Get the first instance textFragment = fragments[0] # Get the text bound bound = textFragment.Bounds[0] # Create a file link annotation fileLinkAnnotation = PdfFileLinkAnnotation(bound, "C:\\Users\\Administrator\\Desktop\\Report.docx") # Add the annotation to the collection of the annotations page.AnnotationsWidget.Add(fileLinkAnnotation) # Save result to file doc.SaveToFile("output/FileLinkAnnotation.pdf") # Dispose resources doc.Dispose()
Add a Document Link Annotation to PDF in Python
A document link annotation in a PDF document is a type of annotation that creates a clickable link to a specific location within the same PDF file. To create a document link annotation, you can first use the PdfTextFinder class to identify the target text in the PDF document. Then, a PdfDocumentLinkAnnotation object is instantiated, and its destination property is configured to redirect the user to the specified location in the PDF.
The steps to add a document link annotation to PDF using Python are as follows:
- Create a PdfDocument object.
- Load a PDF file from the specified location.
- Get a page from the document.
- Find a specific piece of text within the page using PdfTextFinder class.
- Create a PdfDocumentLinkAnnotation object based on the bound of the text.
- Set the destination of the annotation using PdfDocumentLinkAnnotation.Destination property.
- Add the annotation to the page using PdfPageBase.AnnotationsWidget.Add() method.
- Save the modified document to a different PDF file.
- 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") # Get a specific page page = doc.Pages[0] # Create a PdfTextFinder object based on the page finder = PdfTextFinder(page) # Set the find options finder.Options.Parameter = TextFindParameter.WholeWord finder.Options.Parameter = TextFindParameter.IgnoreCase # Find the instances of the specified text fragments = finder.Find("Children"); # Get the first instance textFragment = fragments[0] # Get the text bound bound = textFragment.Bounds[0] # Create a document link annotation documentLinkAnnotation = PdfDocumentLinkAnnotation(bound) # Set the destination of the annotation documentLinkAnnotation.Destination = PdfDestination(doc.Pages[1]); # Add the annotation to the collection of the annotations page.AnnotationsWidget.Add(documentLinkAnnotation) # Save result to file doc.SaveToFile("output/DocumentLinkAnnotation.pdf") # Dispose resources doc.Dispose()
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
PowerPoint presentations often contain hyperlinks that guide audiences to additional resources or locations within the presentations. While these links can be useful for providing further information and easy navigation, there are instances where they may detract from the presentation's flow or compromise its professional appearance. Those invalid or unnecessary links in slides can be easily removed using Python, enhancing the overall quality of the presentations.
This article will show how Spire.Presentation for Python can be utilized to remove hyperlinks from PowerPoint presentations efficiently.
- Remove Hyperlinks from Text in PowerPoint Slides
- Remove Hyperlinks from All Shapes in PowerPoint Slides
- Remove Hyperlinks from Specific Types of Shapes in PowerPoint Slides
- Remove Hyperlinks from Table Text in PowerPoint Slides
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: How to Install Spire.Presentation for Python on Windows
Remove Hyperlinks from Text in PowerPoint Slides
The normal text in a PowerPoint presentation is contained in auto shapes. Developers can access the text ranges within these shapes using the IAutoShape.TextFrame.Paragraphs[].TextRanges[] property and read or set the hyperlinks on them using the TextRange.ClickAction property. Hyperlinks on text can be removed by setting the TextRange.ClickAction property to None.
The detailed steps are as follows:
- Create an instance of Presentation class and load a PowerPoint presentation using Presentation.LoadFromFile() method.
- Iterate through the slides in the presentation and then iterate through the shapes in the slides.
- Check if the shape is an instance of IAutoShape. If it is, iterate through the paragraphs in the shape, and then the text ranges in the paragraphs.
- Check if the TextRange.ClickAction property of a text range is None. If it is not, remove the hyperlink by setting TextRange.ClickAction property to None.
- Save the presentation using Presentation.SaveToFile() method.
- Python
from spire.presentation import Presentation, IAutoShape, FileFormat # Create an instance of Presentation presentation = Presentation() # Load a PowerPoint presentation presentation.LoadFromFile("Sample.pptx") # Iterate through the slides in the presentation for slide in presentation.Slides: # Iterate through the shapes for shape in slide.Shapes: # Check if the shape is an AutoShape instance if isinstance(shape, IAutoShape): # Iterate through the paragraphs in the shape for paragraph in shape.TextFrame.Paragraphs: # Iterate through the text ranges in the paragraph for textRange in paragraph.TextRanges: # Check if the text range has a hyperlink if textRange.ClickAction is not None: # Remove the hyperlink textRange.ClickAction = None # Save the presentation presentation.SaveToFile("output/RemoveSlideTextHyperlink.pptx", FileFormat.Pptx2013) presentation.Dispose()
Remove Hyperlinks from All Shapes in PowerPoint Slides
The IShape class represents all types of shapes in a presentation slide, such as auto shapes, images, tables, and more. The hyperlink on all these shapes can be removed by setting the value obtained from the IShape.Click.get_NoAction() method as the value of the shapes’ IShape.Click property. The detailed steps are as follows:
- Create an instance of Presentation class and load a PowerPoint presentation using Presentation.LoadFromFile() method.
- Iterate through the slides in the presentation and then iterate through the shapes in the slides.
- Check if the IShape.Click property is None. If it is not, remove the hyperlink by setting the property to the result of IShape.Click.get_NoAction() method.
- Save the presentation using Presentation.SaveToFile() method.
- Python
from spire.presentation import Presentation, FileFormat # Create an instance of Presentation presentation = Presentation() # Load a PowerPoint presentation presentation.LoadFromFile("Sample.pptx") # Iterate through the slides in the presentation for slide in presentation.Slides: # Iterate through the shapes in the slide for shape in slide.Shapes: # Check if the shape has a hyperlink if shape.Click is not None: # Remove the click action shape.Click = shape.Click.get_NoAction() # Save the presentation presentation.SaveToFile("output/RemoveSlideShapeHyperlink.pptx", FileFormat.Pptx2013) presentation.Dispose()
Remove Hyperlinks from Specific Types of Shapes in PowerPoint Slides
In addition to directly removing hyperlinks for all shapes, we can also determine the shape type before removing the hyperlinks to find and remove hyperlinks from shapes of the specified type. The detailed steps are as follows:
- Create an instance of Presentation class and load a PowerPoint presentation using Presentation.LoadFromFile() method.
- Iterate through the slides in the presentation and then iterate through the shapes in the slides.
- Check if the shape is an instance of IEmbedImage, ITable, or IChart. If it is, check if the IShape.Click property of the shape is None. If it is not, remove the hyperlink by setting the property to the result of IShape.Click.get_NoAction() method.
- Save the presentation using Presentation.SaveToFile() method.
- Python
from spire.presentation import Presentation, FileFormat, IEmbedImage, ITable, IChart # Create an instance of Presentation presentation = Presentation() # Load a PowerPoint presentation presentation.LoadFromFile("Sample.pptx") # Iterate through the slides in the presentation for slide in presentation.Slides: # Iterate through the shapes in the slide for shape in slide.Shapes: # Check if the shape is an embedded image if isinstance(shape, (IEmbedImage, ITable, IChart)): # check if the click action is not None if shape.Click is not None: # Remove the click action shape.Click = shape.Click.get_NoAction() # Save the presentation presentation.SaveToFile("output/RemoveSlideShapeTypeHyperlink.pptx", FileFormat.Pptx2013) presentation.Dispose()
Remove Hyperlinks from Table Text in PowerPoint Slides
To remove hyperlinks from text within a table, it is necessary to iterate through the table's cells and the text ranges within each cell. Afterward, the hyperlinks on the text ranges in each cell can be removed by setting the TextRange.ClickAction property to None. The detailed steps are as follows:
- Create an instance of Presentation class and load a PowerPoint presentation using Presentation.LoadFromFile() method.
- Iterate through the slides in the presentation and then iterate through the shapes in the slides.
- Check if a shape is an instance of ITable class. If it is, iterate through the rows in the table and then the cells in the rows.
- Iterate through the paragraphs in the cells and then the text ranges in the paragraphs.
- Check if the TextRange.ClickAction property of a text range is None. If it is not, remove the hyperlink by setting the value of the property to None.
- Save the presentation using Presentation.SaveToFile() method.
- Python
from spire.presentation import Presentation, ITable, FileFormat # Create an instance of Presentation presentation = Presentation() # Load a PowerPoint presentation presentation.LoadFromFile("Sample.pptx") # Iterate through the slides in the presentation for slide in presentation.Slides: # Iterate through the shapes in the slide for shape in slide.Shapes: # Check if the shape is a table if isinstance(shape, ITable): # Get the table table = ITable(shape) # Iterate through the rows in the table for row in table.TableRows: # Iterate through the cells in the row for cell in row: # Iterate through the paragraphs in the cell for para in cell.TextFrame.Paragraphs: # Iterate through the text ranges in the paragraph for range in para.TextRanges: # Check if the text run contains a hyperlink if range.ClickAction is not None: # Remove the hyperlink range.ClickAction = None presentation.SaveToFile("output/RemoveSlideTableTextHyperlink.pptx", FileFormat.Pptx2013) 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.
Barcodes in PDFs can facilitate quicker data retrieval and processing. You can add barcodes to PDF files that contain detailed information such as the document's unique identifier, version number, creator, or even the entire document content. When scanned, all information is decoded immediately. This instant access is invaluable for businesses dealing with large volumes of documents, as it minimizes the time and effort required for manual searching and data entry. In this article, you will learn how to add barcodes to PDF in Python using Spire.PDF for Python and Spire.Barcode for Python.
Install Spire.PDF for Python
This scenario requires Spire.PDF for Python and Spire.Barcode for Python. They can be easily installed in your Windows through the following pip command.
pip install Spire.PDF pip install Spire.Barcode
If you are unsure how to install, please refer to this tutorial: How to Install Spire.PDF for Python on Windows
Add Barcodes to PDF in Python
Spire.PDF for Python support several 1D barcode types represented by different classes, such as PdfCodabarBarcode, PdfCode11Barcode, PdfCode32Barcode, PdfCode39Barcode, PdfCode93Barcode.
Each class provides corresponding properties for setting the barcode text, size, color, etc. The following are the steps to draw the common Codabar, Code39 and Code93 barcodes at the specified locations on a PDF page.
- Create a PdfDocument object.
- Add a PDF page using PdfDocument.Pages.Add() method.
- Create a PdfTextWidget object and draw text on the page using PdfTextWidget.Draw() method.
- Create PdfCodabarBarcode, PdfCode39Barcode, PdfCode93Barcode objects.
- Set the gap between the barcode and the displayed text through the BarcodeToTextGapHeight property of the corresponding classes.
- Sets the barcode text display location through the TextDisplayLocation property of the corresponding classes.
- Set the barcode text color through the TextColor property of the corresponding classes.
- Draw the barcodes at specified locations on the PDF page using the Draw(page: PdfPageBase, location: PointF) method of the corresponding classes.
- Save the result PDF file using PdfDocument.SaveToFile() method.
- Python
from spire.pdf.common import * from spire.pdf import * # Create a PDF document pdf = PdfDocument() # Add a page page = pdf.Pages.Add(PdfPageSize.A4()) # Initialize y-coordinate y = 20.0 # Create a true type font font = PdfTrueTypeFont("Arial", 12.0, PdfFontStyle.Bold, True) # Draw text on the page text = PdfTextWidget() text.Font = font text.Text = "Codabar:" result = text.Draw(page, 0.0, y) page = result.Page y = result.Bounds.Bottom + 2 # Draw Codabar barcode on the page Codabar = PdfCodabarBarcode("00:12-3456/7890") Codabar.BarcodeToTextGapHeight = 1.0 Codabar.EnableCheckDigit = True Codabar.ShowCheckDigit = True Codabar.TextDisplayLocation = TextLocation.Bottom Codabar.TextColor = PdfRGBColor(Color.get_Blue()) Codabar.Draw(page, PointF(0.0, y)) y = Codabar.Bounds.Bottom + 6 # Draw text on the page text.Text = "Code39:" result = text.Draw(page, 0.0, y) page = result.Page y = result.Bounds.Bottom + 2 # Draw Code39 barcode on the page Code39 = PdfCode39Barcode("16-273849") Code39.BarcodeToTextGapHeight = 1.0 Code39.TextDisplayLocation = TextLocation.Bottom Code39.TextColor = PdfRGBColor(Color.get_Blue()) Code39.Draw(page, PointF(0.0, y)) y = Code39.Bounds.Bottom + 6 # Draw text on the page text.Text = "Code93:" result = text.Draw(page, 0.0, y) page = result.Page y = result.Bounds.Bottom + 2 # Draw Code93 barcode on the page Code93 = PdfCode93Barcode("16-273849") Code93.BarcodeToTextGapHeight = 1.0 Code93.TextDisplayLocation = TextLocation.Bottom Code93.TextColor = PdfRGBColor(Color.get_Blue()) Code93.QuietZone.Bottom = 5.0 Code93.Draw(page, PointF(0.0, y)) # Save the document pdf.SaveToFile("AddBarcodes.pdf") pdf.Close()
Add QR Codes to PDF in Python
To add 2D barcodes to a PDF file, the Spire.Barcode for Python library is required to generate QR code first, and then you can add the QR code image to the PDF file with the Spire.PDF for Python library. The following are the detailed steps.
- Create a PdfDocument object.
- Add a PDF page using PdfDocument.Pages.Add() method.
- Create a BarcodeSettings object.
- Call the corresponding properties of the BarcodeSettings class to set the barcode type, data, error correction level and width, etc.
- Create a BarCodeGenerator object based on the settings.
- Generate QR code image using BarCodeGenerator.GenerateImage() method.
- Save the QR code image to a PNG file.
- Draw the QR code image at a specified location on the PDF page using PdfPageBase.Canvas.DrawImage() method.
- Save the result PDF file using PdfDocument.SaveToFile() method.
- Python
from spire.pdf.common import * from spire.pdf import * from spire.barcode import * # Create a PdfDocument instance pdf = PdfDocument() # Add a page page = pdf.Pages.Add() # Create a BarcodeSettings object settings = BarcodeSettings() # Set the barcode type to QR code settings.Type = BarCodeType.QRCode # Set the data of the QR code settings.Data = "E-iceblue" settings.Data2D = "E-iceblue" # Set the width of the QR code settings.X = 2 # Set the error correction level of the QR code settings.QRCodeECL = QRCodeECL.M # Set to show QR code text at the bottom settings.ShowTextOnBottom = True # Generate QR code image based on the settings barCodeGenerator = BarCodeGenerator(settings) QRimage = barCodeGenerator.GenerateImage() # Save the QR code image to a .png file with open("QRCode.png", "wb") as file: file.write(QRimage) # Initialize y-coordinate y = 20.0 # Create a true type font font = PdfTrueTypeFont("Arial", 12.0, PdfFontStyle.Bold, True) # Draw text on the PDF page text = PdfTextWidget() text.Font = font text.Text = "QRCode:" result = text.Draw(page, 0.0, y) page = result.Page y = result.Bounds.Bottom + 2 # Draw QR code image on the PDF page pdfImage = PdfImage.FromFile("QRCode.png") page.Canvas.DrawImage(pdfImage, 0.0, y) # Save the document pdf.SaveToFile("PdfQRCode.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.
Superscript and subscript are formatting options that allow you to raise or lower characters in relation to the main text. Superscript is typically used for mathematical expressions, footnotes, ordinal indicators (such as "1st" or "2nd"), and chemical formulas. Subscript is commonly employed in chemical equations, mathematical notation, and certain linguistic elements. By adding superscripts and subscripts, you can enhance the readability and professionalism of your documents, especially in scientific, mathematical, and technical writing. In this article, we will demonstrate how to add superscripts and subscripts to Word documents in Python using Spire.Doc for Python.
- Add Superscript and Subscript Text to Word in Python
- Apply Superscript and Subscript Formatting to Existing Text in Word 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
Add Superscript and Subscript Text to Word in Python
You can add text to a paragraph using the Paragraph.AppentText() method. After that, you can apply superscript or subscript formatting to the text through the TextRange.CharacterFormat.SubSuperScript property. The detailed steps are as follows.
- Create an object of the Document class.
- Add a section to the document using Document.AddSection() method.
- Add a paragraph to the section using Section.AddParagraph() method.
- Add normal text to the paragraph using Paragraph.AppendText() method.
- Add superscript or subscript text to the paragraph using Paragraph.AppendText() method.
- Apply superscript or subscript formatting to the superscript or subscript text using TextRange.CharacterFormat.SubSuperScript property.
- Save the resulting document using Document.SaveToFile() method.
- Python
from spire.doc import * from spire.doc.common import * # Create a Document instance document = Document() # Add a section to the document section = document.AddSection() # Add a paragraph to the section paragraph = section.AddParagraph() # Add normal text to the paragraph paragraph.AppendText("E = mc") # Add superscript text to the paragraph superscript_text = paragraph.AppendText("2") # Apply superscript formatting to the superscript text superscript_text.CharacterFormat.SubSuperScript = SubSuperScript.SuperScript # Start a new line paragraph.AppendBreak(BreakType.LineBreak) # Add normal text to the paragraph paragraph.AppendText("H") # Add subscript text to the paragraph subscript_text = paragraph.AppendText("2") # Apply subscript formatting to the subscript text subscript_text.CharacterFormat.SubSuperScript = SubSuperScript.SubScript # Add normal text to the paragraph paragraph.AppendText("O") # Set the font size for the text in the paragraph for i in range(paragraph.Items.Count): item = paragraph.Items[i] if isinstance(item, TextRange): text_range = item text_range.CharacterFormat.FontSize = 36 # Save the resulting document document.SaveToFile("AddSuperscriptAndSubscriptText.docx", FileFormat.Docx2013) document.Close()
Apply Superscript and Subscript Formatting to Existing Text in Word in Python
To apply superscript or subscript formatting to a specific text, you need to search for the text using the Document.FindAllString() method, then apply superscript or subscript formatting to the instances of that text through the TextRange.CharacterFormat.SubSuperScript property. The detailed steps are as follows.
- Create an object of the Document class.
- Load a Word document using Document.LoadFromFile() method.
- Find a specific text in the document using Document.FindAllString() method. This method will return a list of TextSelection objects, each representing an instance of the text in the document.
- Get the first instance of the text as a single text range using TextSelection.GetAsOneRange() method, then apply superscript formatting to the text range by setting the TextRange.CharacterFormat.SubSuperScript property to SubSuperScript.SuperScript.
- Get the second instance of the text as a single text range using TextSelection.GetAsOneRange() method, then apply subscript formatting to the text range by setting the TextRange.CharacterFormat.SubSuperScript property to SubSuperScript.SubScript.
- Save the resulting document using Document.SaveToFile() method.
- Python
from spire.doc import * from spire.doc.common import * # Create a Document instance document = Document() # Load a Word document document.LoadFromFile("Sample.docx") # Find a specific number in the document text_selections = document.FindAllString("2", False, False) # Apply superscript formatting to the first instance of the number superscript_text = text_selections[0].GetAsOneRange() superscript_text.CharacterFormat.SubSuperScript = SubSuperScript.SuperScript # Apply subscript formatting to the second instance of the number subscript_text = text_selections[1].GetAsOneRange() subscript_text.CharacterFormat.SubSuperScript = SubSuperScript.SubScript # Save the resulting document document.SaveToFile("ApplySuperscriptAndSubscriptFormatting.docx", FileFormat.Docx2013) document.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.
Python: Insert, Rotate, Resize, Reposition, and Reorder Shapes in PowerPoint
2024-08-15 00:52:47 Written by KoohjiShapes are the fundamental building blocks that bring your PowerPoint slides to life. From simple geometric forms to complex icons and illustrations, these versatile visual elements enable you to add interest, highlight key information, and craft visually striking layouts. Whether you are creating professional-looking slides from scratch or enhancing existing ones, knowing how to insert and manipulate shapes is an essential skill. In this guide, we'll cover how to insert, rotate, resize, reposition, and reorder shapes in PowerPoint presentations in Python using Spire.Presentation for Python.
- Insert Shapes in PowerPoint in Python
- Rotate Shapes in PowerPoint in Python
- Resize and Reposition Shapes in PowerPoint in Python
- Reorder Shapes 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
Insert Shapes in PowerPoint in Python
Spire.Presentation for Python enables you to add various types of shapes such as rectangles, circles, triangles, arrows, and eclipses to a PowerPoint slide by using the ISlide.Shapes.AppendShape() method.
Here are the steps to insert shapes in PowerPoint using Spire.Presentation for Python:
- Create an object of the Presentation class.
- Load a PowerPoint presentation using Presentation.LoadFromFile() method.
- Get a specific slide in the presentation using Presentation.Slides[index] property.
- Add various types of shapes to the slide using ISlide.Shapes.AppendShape() method and then set styles for the shapes.
- Save the resulting presentation using Presentation.SaveToFile() method.
- Python
from spire.presentation import * # Create an object of the Presentation class ppt = Presentation() # Get the first slide slide = ppt.Slides[0] # Add a triangle shape to the slide shape = slide.Shapes.AppendShape(ShapeType.Triangle, RectangleF.FromLTRB (115, 130, 215, 230)) shape.Fill.FillType = FillFormatType.Solid shape.Fill.SolidColor.Color = Color.get_LightGreen() shape.ShapeStyle.LineColor.Color = Color.get_White() # Add an ellipse shape to the slide shape = slide.Shapes.AppendShape(ShapeType.Ellipse, RectangleF.FromLTRB (290, 130, 440, 230)) shape.Fill.FillType = FillFormatType.Solid shape.Fill.SolidColor.Color = Color.get_LightSkyBlue() shape.ShapeStyle.LineColor.Color = Color.get_White() # Add a heart shape to the slide shape = slide.Shapes.AppendShape(ShapeType.Heart, RectangleF.FromLTRB (470, 130, 600, 230)) shape.Fill.FillType = FillFormatType.Solid shape.Fill.SolidColor.Color = Color.get_Red() shape.ShapeStyle.LineColor.Color = Color.get_LightGray() # Add a five-pointed star shape to the slide shape = slide.Shapes.AppendShape(ShapeType.FivePointedStar, RectangleF.FromLTRB (90, 270, 240, 420)) shape.Fill.FillType = FillFormatType.Gradient shape.Fill.SolidColor.Color = Color.get_Black() shape.ShapeStyle.LineColor.Color = Color.get_White() # Add a rectangle shape to the slide shape = slide.Shapes.AppendShape(ShapeType.Rectangle, RectangleF.FromLTRB (320, 290, 420, 410)) shape.Fill.FillType = FillFormatType.Solid shape.Fill.SolidColor.Color = Color.get_Pink() shape.ShapeStyle.LineColor.Color = Color.get_LightGray() # Add an arrow shape to the slide shape = slide.Shapes.AppendShape(ShapeType.BentUpArrow, RectangleF.FromLTRB (470, 300, 580, 400)) shape.Fill.FillType = FillFormatType.Gradient shape.Fill.Gradient.GradientStops.AppendByKnownColors(1, KnownColors.Olive) shape.Fill.Gradient.GradientStops.AppendByKnownColors(0, KnownColors.PowderBlue) shape.ShapeStyle.LineColor.Color = Color.get_Red() # Save the resulting presentation to a new file ppt.SaveToFile("InsertShapes.pptx", FileFormat.Pptx2010) ppt.Dispose()
Rotate Shapes in PowerPoint in Python
The IShape.Rotation property in Spire.Presentation for Python is used to rotate a shape on a PowerPoint slide. Setting this property to a positive value will rotate the shape clockwise, while setting it to a negative value will rotate the shape counterclockwise.
Here are the steps to rotate a shape in PowerPoint using Spire.Presentation for Python:
- Create an object of the Presentation class.
- Load a PowerPoint presentation using Presentation.LoadFromFile() method.
- Get a specific slide in the presentation using Presentation.Slides[index] property.
- Get a specific shape on the slide using ISlide.Shapes[index] property.
- Rotate the shape by specific degrees using IShape.Rotation property.
- Save the resulting presentation using Presentation.SaveToFile() method.
- Python
from spire.presentation import * # Create an object of the Presentation class ppt = Presentation() # Load a PowerPoint presentation ppt.LoadFromFile("ShapeTemplate1.pptx") # Get the first slide slide = ppt.Slides[0] # Get the first shape on the slide shape = slide.Shapes[0] if isinstance(slide.Shapes[0], IAutoShape) else None # Rotate the shape 180 degrees clockwise shape.Rotation = 180 # Save the resulting presentation to a new file ppt.SaveToFile("RotateShape.pptx", FileFormat.Pptx2016) ppt.Dispose()
Resize and Reposition Shapes in PowerPoint in Python
The size and position of a shape can be reset through the IShape.Height, IShape.Width and IShape.Left, IShape.Top properties.
Here are the steps to reset the size and position of shapes in PowerPoint using Spire.Presentation for Python:
- Create an object of the Presentation class.
- Load a PowerPoint presentation using Presentation.LoadFromFile() method.
- Get the original slide height and width using Presentation.SlideSize.Size.Height and Presentation.SlideSize.Size.Width properties.
- Change the slide size using Presentation.SlideSize.Type property, and then get the new slide height and width.
- Calculate the ratio for resetting the size and position of the shapes based on the original and new slide heights and widths.
- Iterate through the slides in the presentation and the shapes on each slide.
- Reset the size and position of each shape based on the specified ratio using IShape.Height, IShape.Width, IShape.Left and IShape.Top properties.
- Save the resulting presentation using Presentation.SaveToFile() method.
- Python
from spire.presentation import * # Create an object of the Presentation class ppt = Presentation() # Load a PowerPoint presentation ppt.LoadFromFile("ShapeTemplate.pptx") # Get the original slide height and width currentHeight = ppt.SlideSize.Size.Height currentWidth = ppt.SlideSize.Size.Width # Change the slide size to A3 ppt.SlideSize.Type = SlideSizeType.A3 # Get the new slide height and width newHeight = ppt.SlideSize.Size.Height newWidth = ppt.SlideSize.Size.Width # Calculate the ratio for resizing shapes based on the original and new slide heights and widths ratioHeight = newHeight / currentHeight ratioWidth = newWidth / currentWidth # Iterate through the slides in the presentation for slide in ppt.Slides: # Iterate through the shapes on the slide for shape in slide.Shapes: if isinstance(shape, IAutoShape): # Reset the size of the shape based on the specified ratio shape.Height = shape.Height * ratioHeight shape.Width = shape.Width * ratioWidth # Reset the position (x and y coordinates) of the shape based on the specified ratio shape.Top = shape.Top * ratioHeight shape.Left = shape.Left * ratioWidth # Save the resulting presentation to a new file ppt.SaveToFile("ResizeAndRepositionShapes.pptx", FileFormat.Pptx2016) ppt.Dispose()
Reorder Shapes in PowerPoint in Python
The order in which shapes are arranged determines which shapes appear in front of or behind others. Using the ISlide.Shapes.ZOrder() method, you can easily change the order of multiple overlapping shapes on a PowerPoint slide.
Here are the steps to change the order of shapes in PowerPoint using Spire.Presentation for Python:
- Create an object of the Presentation class.
- Load a PowerPoint presentation using Presentation.LoadFromFile() method.
- Get a specific slide in the presentation using Presentation.Slides[index] property.
- Get a specific shape on the slide using ISlide.Shapes[index] property.
- Change the stacking order of the shape using ISlide.Shapes.ZOrder() method.
- Save the resulting presentation using Presentation.SaveToFile() method.
- Python
from spire.presentation import * # Create an object of the Presentation class ppt = Presentation() # Load a PowerPoint presentation ppt.LoadFromFile("ShapeTemplate3.pptx") # Get the first slide slide = ppt.Slides[0] # Get the first shape on the slide shape = slide.Shapes[0] if isinstance(slide.Shapes[0], IAutoShape) else None # Change the stacking order of the shape slide.Shapes.ZOrder(1, shape) # Save the resulting presentation to a new file ppt.SaveToFile("ReorderShapes.pptx", FileFormat.Pptx2016) 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.
When preparing multiple PowerPoint presentations with similar themes, copying slides helps to maintain consistency in terms of design, layout and content. This ensures that all presentations have a uniform appearance, which can enhance the aesthetics of your document. In this article, you will learn how to copy or clone slides in PowerPoint presentations in Python using Spire.Presentation for Python.
- Copy Slides Within the Same Presentation with Python
- Copy Slides to Another Presentation with 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
Copy Slides Within the Same Presentation with Python
You can clone a slide either at a specified location or at the end of a PowerPoint presentation through the Presentation.Slides.Insert(Index: int, slide: ISlide) or Presentation.Slides.AppendBySlide(slide: ISlide) methods. The following are the detailed steps.
- Create a Presentation instance.
- Load a PowerPoint presentation using Presentation.LoadFromFile() method.
- Get a specified slide using Prenstion.Slides[] property.
- Clone the slide to the end of the same presentation using Presentation.Slides.AppendBySlide() method.
- Clone the slide to a specific position within the same presentation using Presentation.Slides.Insert() method.
- Save the result file using Presentation.SaveToFile() method.
- Python
from spire.presentation.common import * from spire.presentation import * inputFile ="Input1.pptx" outputFile ="CloneSlidesWithinTheSame.pptx" # Create a Presentation instance ppt = Presentation() #Load a PowerPoint presentation ppt.LoadFromFile(inputFile) # Get the first slide in the presentation slide = ppt.Slides[0] # Clone the slide to the end of the presentation ppt.Slides.AppendBySlide(slide) # Clone the slide to the third position within the presentation ppt.Slides.Insert(2, slide) # Save the result file ppt.SaveToFile(outputFile, FileFormat.Pptx2016) ppt.Dispose()
Copy Slides to Another Presentation with Python
Spire.Presentation for Python also allows you to load two PowerPoint files and then clone the slides from one presentation to another presentation. The following are the detailed steps.
- Create a Presentation instance.
- Load two PowerPoint presentations using Presentation.LoadFromFile() method.
- Get two slides in the first presentation using Prenstion.Slides[] property.
- Clone the first slide to a specific position in the second presentation using Presentation.Slides.Insert() method.
- Clone the second slide to the end of the second presentation using Presentation.Slides.AppendBySlide() method.
- Save the result file using Presentation.SaveToFile() method.
- Python
from spire.presentation.common import * from spire.presentation import * inputFile_1 = "Input1.pptx" inputFile_2 = "Input2.pptx" outputFile ="CloneSlidesToAnother.pptx" # Load the first PowerPoint presentation sourcePPT = Presentation() sourcePPT.LoadFromFile(inputFile_1) # Load the second PowerPoint presentation destPPT = Presentation() destPPT.LoadFromFile(inputFile_2) # Get two slides in the first presentation slide1 =sourcePPT.Slides[1] slide2 =sourcePPT.Slides[2] # Clone slide1 to the second position in the second presentation destPPT.Slides.Insert(1, slide1) # Clone slide2 to the end of the second presentation destPPT.Slides.AppendBySlide(slide2) # Save the second presentation destPPT.SaveToFile(outputFile, FileFormat.Pptx2016) destPPT.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.
