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.

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()

Python: Set Background Color or Picture for PowerPoint Slides

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()

Python: Set Background Color or Picture for PowerPoint Slides

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()

Python: Set Background Color or Picture for PowerPoint Slides

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()

Python: Set Background Color or Picture for PowerPoint Slides

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.

Published in Document Operation
Friday, 01 December 2023 01:30

Python: Create and Identify PDF Portfolios

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()

Python: Create and Identify PDF Portfolios

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()

Python: Create and Identify PDF Portfolios

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.

Published in Document Operation
Tuesday, 28 November 2023 00:52

Python: Add Hyperlinks to PDF

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:[email protected]"
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()

Python: Add Hyperlinks to PDF

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[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()

Python: Add Hyperlinks to PDF

Apply for a Temporary License

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

Published in Link
Tuesday, 21 November 2023 01:24

Python: Add, Hide, or Remove Layers in PDF

Layers in PDF are similar to layers in image editing software, where different elements of a document can be organized and managed separately. Each layer can contain different content, such as text, images, graphics, or annotations, and can be shown or hidden independently. PDF layers are often used to control the visibility and positioning of specific elements within a document, making it easier to manage complex layouts, create dynamic designs, or control the display of information. In this article, you will learn how to add, hide, remove layers in a PDF document in Python using Spire.PDF for Python.

Install Spire.PDF for Python

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

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 Layer to PDF in Python

A layer can be added to a PDF document using the Document.Layers.AddLayer() method. After the layer object is created, you can draw text, images, fields, or other elements on it to form its appearance. The detailed steps to add a layer to PDF using Spire.PDF for Java are as follows.

  • Create a PdfDocument object.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Create a layer using Document.Layers.AddLayer() method.
  • Get a specific page through PdfDocument.Pages[index] property.
  • Create a canvas for the layer based on the page using PdfLayer.CreateGraphics() method.
  • Draw text on the canvas using PdfCanvas.DrawString() method.
  • Save the document to a different PDF file using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

def AddLayerWatermark(doc):

    # Create a layer named "Watermark"
    layer = doc.Layers.AddLayer("Watermark")

    # Create a font
    font = PdfTrueTypeFont("Bodoni MT Black", 50.0, 1, True)

    # Specify watermark text
    watermarkText = "DO NOT COPY"

    # Get text size
    fontSize = font.MeasureString(watermarkText)

    # Get page count
    pageCount = doc.Pages.Count

    # Loop through the pages
    for i in range(0, pageCount):

        # Get a specific page
        page = doc.Pages[i]

        # Create canvas for layer
        canvas = layer.CreateGraphics(page.Canvas)

        # Draw sting on the graphics
        canvas.DrawString(watermarkText, font, PdfBrushes.get_Gray(), (canvas.Size.Width - fontSize.Width)/2, (canvas.Size.Height - fontSize.Height)/2 )

# Create a PdfDocument instance
doc = PdfDocument()

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

# Invoke AddLayerWatermark method to add a layer
AddLayerWatermark(doc)

# Save to file
doc.SaveToFile("output/AddLayer.pdf", FileFormat.PDF)
doc.Close()

Python: Add, Hide, or Remove Layers in PDF

Set Visibility of a Layer in PDF in Python

To control the visibility of layers in a PDF document, you can use the PdfDocument.Layers[index].Visibility property. Set it to off to hide a layer, or set it to on to unhide a layer. The detailed steps are as follows.

  • Create a PdfDocument object.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Set the visibility of a certain layer through Document.Layers[index].Visibility property.
  • Save the document to a different PDF file using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument instance
doc = PdfDocument()

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

# Hide a layer by setting the visibility to off
doc.Layers[0].Visibility = PdfVisibility.Off

# Save to file
doc.SaveToFile("output/HideLayer.pdf", FileFormat.PDF)
doc.Close()

Remove a Layer from PDF in Python

If a layer is no more wanted, you can remove it using the PdfDocument.Layers.RmoveLayer() method. The following are the detailed steps.

  • Create a PdfDocument object.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Get a specific layer through PdfDocument.Layers[index] property.
  • Remove the layer from the document using PdfDcument.Layers.RemoveLayer(PdfLayer.Name) method.
  • Save the document to a different PDF file using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument instance
doc = PdfDocument()

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

# Delete the specific layer 
doc.Layers.RemoveLayer(doc.Layers[0].Name)

# Save to file
doc.SaveToFile("output/RemoveLayer.pdf", FileFormat.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.

Published in Document Operation
Friday, 17 November 2023 06:52

Python: Apply Different Fonts in PDF

The use of appropriate fonts in PDF can greatly improve the overall readability and aesthetics of the document. In addition to the commonly used standard fonts, sometimes you may also need to embed private fonts. In this article, you will learn how to use different fonts in PDF 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

Apply Different Fonts in a PDF Document in Python

Spire.PDF for Python supports standard PDF fonts, TrueType fonts, private fonts as well as CJK font. The following are the steps to draw text in PDF using these fonts.

  • Create a PdfDocument instance.
  • Add a page and then create a brush.
  • Create an instance of the PdfFont class with a standard PDF font, and then use the PdfPageBase.getCanvas().drawString() method to draw text on the page with the standard font.
  • Create an instance of the PdfTrueTypeFont class with a specified font, and then draw text on the page with the TrueType font.
  • Load a private font and create an instance of the PdfTrueTypeFont class with it. Then draw text on the page with the private font.
  • Create an instance of PdfCjkStandardFont class with a CJK font, and then draw text on the page with the CJK font.
  • Save the result document using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
pdf = PdfDocument()

# Add a page
page = pdf.Pages.Add()

# Create a brush
brush = PdfBrushes.get_Black()

# Initialize y coordinate
y = 30.0

# Draw text using standard fonts
font = PdfFont(PdfFontFamily.Helvetica, 14.0)
page.Canvas.DrawString("Standard Font: Helvetica", font, brush, 0.0, y)
font = PdfFont(PdfFontFamily.Courier, 14.0)
page.Canvas.DrawString("Standard Font: Courier", font, brush, 0.0, (y := y + 16.0))
font = PdfFont(PdfFontFamily.TimesRoman, 14.0)
page.Canvas.DrawString("Standard Font: TimesRoman", font, brush, 0.0, (y := y + 16.0))

#Draw text using truetype font
trueTypeFont = PdfTrueTypeFont("Arial", 14.0, PdfFontStyle.Bold,True)
page.Canvas.DrawString("TrueType Font: Arial", trueTypeFont, brush, 0.0, (y := y + 30.0))

# Draw Arabic text from right to left
arabicText = "\u0627\u0644\u0630\u0647\u0627\u0628\u0021\u0020" + "\u0628\u062F\u0648\u0631\u0647\u0020\u062D\u0648\u0644\u0647\u0627\u0021\u0020" + "\u0627\u0644\u0630\u0647\u0627\u0628\u0021\u0020" + "\u0627\u0644\u0630\u0647\u0627\u0628\u0021\u0020" + "\u0627\u0644\u0630\u0647\u0627\u0628\u0021"
trueTypeFont = PdfTrueTypeFont("Arial", 14.0, PdfFontStyle.Bold,True)
rctg = RectangleF(PointF(0.0, (y := y + 16.0)), page.Canvas.ClientSize)
strformat = PdfStringFormat(PdfTextAlignment.Right)
strformat.RightToLeft = True
page.Canvas.DrawString(arabicText, trueTypeFont, brush, rctg, strformat)

# Draw text using private font
trueTypeFont = PdfTrueTypeFont("Khadija.ttf", 14.0)
page.Canvas.DrawString("Private Font - Khadija", trueTypeFont, brush, 0.0, (y := y + 30.0))

# Draw text using cjk fonts
cjkFont = PdfCjkStandardFont(PdfCjkFontFamily.MonotypeHeiMedium, 14.0)
page.Canvas.DrawString("How to say 'Font' in Chinese? \u5B57\u4F53", cjkFont, brush, 0.0, (y := y + 30.0))
cjkFont = PdfCjkStandardFont(PdfCjkFontFamily.HanyangSystemsGothicMedium, 14.0)
page.Canvas.DrawString("How to say 'Font' in Japanese? \u30D5\u30A9\u30F3\u30C8", cjkFont, brush, 0.0, (y := y + 16.0))
cjkFont = PdfCjkStandardFont(PdfCjkFontFamily.HanyangSystemsShinMyeongJoMedium, 14.0)
page.Canvas.DrawString("How to say 'Font' in Korean? \uAE00\uAF34", cjkFont, brush, 0.0, (y := y + 16.0))

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

Python: Apply Different Fonts in PDF

Apply for a Temporary License

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

Published in Font
Monday, 13 November 2023 00:56

Python: Set and Retrieve PDF Properties

PDF properties refer to the information embedded within the document that provides detailed information about the documents, such as author, creation date, last modification date, etc. Users can check the properties of a PDF document in PDF viewers to quickly grasp the key information of the document. Apart from the built-in properties, PDF documents also offer the feature of customizing properties to help provide additional information about the document. Understanding how to specify and access this document information facilitates the creation of user-friendly documents and the processing of documents in large quantities. In this article, we will explore how to set and retrieve PDF properties through Python programs 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 commands.

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

Set PDF Properties with Python

Spire.PDF for Python provides several properties under the PdfDocumentInformation class for setting built-in document properties, such as author, subject, keywords. Besides, it also provides the PdfDocumentInformation.SetCustomProperty() method to set custom properties. The following are the detailed steps to set PDF properties:

  • Create an object of PdfDocument class and load a PDF document using PdfDocument.LoadFromFile() method.
  • Get the properties of the document through PdfDocument.DocumentInformation property.
  • Set the built-in properties through properties under PdfDocumentInformation class.
  • Set custom properties using PdfDocumentInformation.SetCustomProperty() 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")

# Get the properties of the document
properties = pdf.DocumentInformation

# Set built-in properties
properties.Author = "Tim Taylor"
properties.Creator = "Spire.PDF"
properties.Keywords = "cloud service; digital business"
properties.Subject = "The introduction of cloud service and its advantages"
properties.Title = "The Power of Cloud Services: Empowering Businesses in the Digital Age"
properties.Producer = "Spire.PDF for Python"

# Set custom properties
properties.SetCustomProperty("Company", "E-iceblue")
properties.SetCustomProperty("Tags", "Cloud; Business; Server")

# Save the document
pdf.SaveToFile("output/SetPDFProperties.pdf")
pdf.Close()

Python: Set and Retrieve PDF Properties

Retrieve PDF Properties with Python

Information in built-in PDF properties can be obtained using the properties under the PdfDocumentInformation class, while that in custom PDF properties can be obtained using PdfDocumentInformation.GetCustomProperty() method. The detailed steps are as follows:

  • Create an object of PdfDocument class and load a PDF document using PdfDocument.LoadFromFile() method.
  • Get the properties of the document through PdfDocument.DocumentInformation property.
  • Retrieve the built-in properties through properties under PdfDocumentInformation class and custom properties using PdfDocumentInformation.GetCustomProperty() method and print them.
  • 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("output\SetPDFProperties.pdf")

# Get the properties of the document
properties = pdf.DocumentInformation

# Create a StringBuilder object
information = ""

# Retrieve the built-in properties
information += "Author: " + properties.Author
information += "\nTitle: " + properties.Title
information += "\nSubject: " + properties.Subject
information += "\nKeywords: " + properties.Keywords
information += "\nCreator: " + properties.Creator
information += "\nProducer: " + properties.Producer

# Retrieve the custom properties
information += "\nCompany: " + properties.GetCustomProperty("Company")
information += "\nTags: " + properties.GetCustomProperty("Tags")

# Print the document properties
print(information)
pdf.Close()

Python: Set and Retrieve PDF Properties

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.

Published in Document Operation
Thursday, 28 September 2023 03:20

Python: Split a PDF File into Multiple PDFs

Large PDF files can sometimes be cumbersome to handle, especially when sharing or uploading them. Splitting a large PDF file into multiple smaller PDFs reduces the file size, making it more manageable and quicker to open and process. In this article, we will demonstrate how to split PDF documents 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

Split a PDF File into Multiple Single-Page PDFs in Python

Spire.PDF for Python offers the PdfDocument.Split() method to divide a multi-page PDF document into multiple single-page PDF files. The following are the detailed steps.

  • Create a PdfDocument object.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Split the document into multiple single-page PDFs using PdfDocument.Split() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
doc = PdfDocument()
# Load a PDF file
doc.LoadFromFile("Sample.pdf")

# Split the PDF file into multiple single-page PDFs
doc.Split("Output/SplitDocument-{0}.pdf", 1)

# Close the PdfDocument object
doc.Close()

Python: Split a PDF File into Multiple PDFs

Split a PDF File by Page Ranges in Python

To split a PDF file into two or more PDF files by page ranges, you need to create two or more new PDF files, and then import the specific page or range of pages from the source PDF into the newly created PDF files. The following are the detailed steps.

  • Create a PdfDocument object.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Create three PdfDocument objects.
  • Import the first page from the source file into the first document using PdfDocument.InsertPage() method.
  • Import pages 2-4 from the source file into the second document using PdfDocument.InsertPageRange() method.
  • Import the remaining pages from the source file into the third document using PdfDocument.InsertPageRange() method.
  • Save the three documents using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
doc = PdfDocument()
# Load a PDF file
doc.LoadFromFile("Sample.pdf")

# Create three PdfDocument objects
newDoc_1 = PdfDocument()
newDoc_2 = PdfDocument()
newDoc_3 = PdfDocument()

# Insert the first page of the source file into the first document
newDoc_1.InsertPage(doc, 0)

# Insert pages 2-4 of the source file into the second document
newDoc_2.InsertPageRange(doc, 1, 3)

# Insert the rest pages of the source file into the third document
newDoc_3.InsertPageRange(doc, 4, doc.Pages.Count - 1)

# Save the three documents
newDoc_1.SaveToFile("Output1/Split-1.pdf")
newDoc_2.SaveToFile("Output1/Split-2.pdf")
newDoc_3.SaveToFile("Output1/Split-3.pdf")

# Close the PdfDocument objects
doc.Close()
newDoc_1.Close()
newDoc_2.Close()
newDoc_3.Close()

Python: Split a PDF File into Multiple PDFs

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.

Published in Document Operation
Wednesday, 06 September 2023 01:09

Python: Merge PDF Documents

A large number of scattered but content-related PDF documents will be very inefficient to deal with and difficult to manage. Merging them into a single PDF file is a good solution. By consolidating these files, not only can you streamline your document handling process, but you can also share and view them conveniently, significantly increasing efficiency. This article will show how to merge PDF files in Python programs 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 commands.

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

Merge PDF Documents in Python

Spire.PDF for Python provides the PdfDocument.MergeFiles() method to easily merge multiple PDF documents into one PDF document. The detailed steps are as follows:

  • Create a list of the PDF file paths.
  • Merge the PDF files using Document.MergeFiles(inputFiles: List[str]) method.
  • Save the merged document using PdfDocumentBase.Save(filename: str, FileFormat.PDF) method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a list of the PDF file paths
inputFile1 = "Sample1.pdf"
inputFile2 = "Sample2.pdf"
inputFile3 = "Sample3.pdf"
files = [inputFile1, inputFile2, inputFile3]

# Merge the PDF documents
pdf = PdfDocument.MergeFiles(files)

# Save the result document
pdf.Save("output/MergePDF.pdf", FileFormat.PDF)
pdf.Close()

Python: Merge PDF Documents

Merge PDF Documents by Cloning Pages

Merging PDF files can also be done by cloning pages from PDF files to a new PDF file using PdfDocument.AppendPage(PdfDocument) method. The detailed steps are as follows:

  • Create a list of the PDF file paths.
  • Load each PDF document as an object of PdfDocument class and add them to a list.
  • Create an object of PdfDocument class to create a new PDF document.
  • Loop through each loaded PDF document and insert their pages to the new PDF document using PdfDocument.appendPage() method.
  • Save the new PDF document using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a list of the PDF file paths
file1 = "Sample1.pdf"
file2 = "Sample2.pdf"
file3 = "Sample3.pdf"
files = [file1, file2, file3]

# Load each PDF file as an PdfDocument object and add them to a list
pdfs = []
for file in files:
    pdfs.append(PdfDocument(file))

# Create an object of PdfDocument class
newPdf = PdfDocument()

# Insert the pages of the loaded PDF documents into the new PDF document
for pdf in pdfs:
    newPdf.AppendPage(pdf)

# Save the new PDF document    
newPdf.SaveToFile("output/ClonePage.pdf")

Merge Selected Pages of PDF Documents

Spire.PDF for Python also allows users to select and insert pages from one PDF document to another using PdfDocument.InsertPage() method and PdfDocument.InsertPageRange() method, enabling the merging of specified PDF pages. The detailed steps are as follows:

  • Create a list of the PDF file paths.
  • Load each PDF document as an object of PdfDocument class and add them to a list.
  • Create an object of PdfDocument class to create a new PDF document.
  • Insert the selected pages of the loaded documents into the new PDF document using PdfDocument.InsertPage(PdfDocument, pageIndex: int) method and PdfDocument.InsertPageRange(PdfDocument, startIndex: int, endIndex: int) method.
  • Save the new PDF document using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf import *
from spire.pdf.common import *

# Create a list of the PDF file paths
file1 = "Sample1.pdf"
file2 = "Sample2.pdf"
file3 = "Sample3.pdf"
files = [file1, file2, file3]

# Load each PDF file as an PdfDocument object and add them to a list
pdfs = []
for file in files:
    pdfs.append(PdfDocument(file))

# Create an object of PdfDocument class
newPdf = PdfDocument()

# Insert the selected pages from the loaded PDF documents into the new document
newPdf.InsertPage(pdfs[0], 0)
newPdf.InsertPage(pdfs[1], 1)
newPdf.InsertPageRange(pdfs[2], 0, 1)

# Save the new PDF document
newPdf.SaveToFile("output/SelectedPages.pdf")

Python: Merge PDF Documents

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.

Published in Document Operation
Page 2 of 2