Spire.Office Knowledgebase Page 30 | E-iceblue

Python: Insert Paragraphs in Word

2024-11-27 01:02:52 Written by Koohji

In Word, each paragraph should convey a unique idea or point, helping to organize information in a way that is easy for readers to understand. Inserting new paragraphs allows you to introduce new concepts or expand on different aspects of a topic, making the text clearer. In this article, you will learn how to insert a new paragraph in Word in Python using Spire.Doc for 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 commands.

pip install Spire.Doc

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python on Windows

Add a Paragraph at the End of a Word Document in Python

To add a new paragraph at the end, you need to get the last section of the Word document through the Document.LastSection property, and then add a paragraph at the end of the section through the Section.AddParagraph() method. The following are the detailed steps:

  • Create a Document instance.
  • Load a Word document using Document.LoadFromFile() method.
  • Get the last section of the document using Document.LastSection property.
  • Add a paragraph at the end of the section using Section.AddParagraph() method, and then add text to it using Paragraph.AppendText() method.
  • Create a ParagraphStyle object and set the font name, size, style of the paragraph text.
  • Apply the paragraph style using Paragraph.ApplyStyle() method
  • Save the result document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

# Load a Word document
doc.LoadFromFile("Test.docx")

# Get the first section
section = doc.LastSection

# Add a paragraph at the end and set its text content
para = section.AddParagraph()
para.AppendText("Add a paragraph to the end of the document.")

# Set the paragraph style
style = ParagraphStyle(doc)
style.Name = "Style1"
style.CharacterFormat.FontName = "Times New Roman"
style.CharacterFormat.FontSize = 12
style.CharacterFormat.TextColor = Color.get_Blue()
style.CharacterFormat.Bold= True
doc.Styles.Add(style)
para.ApplyStyle("Style1")
para.Format.BeforeSpacing = 10

# Save the result file
doc.SaveToFile("AddParagraph.docx", FileFormat.Docx2016)
doc.Close()

An output file that adds a new paragraph with text in Word using Python

Insert a Paragraph at a Specified Location in Word in Python

You can also add a paragraph and then insert it to a specified position in Word through the Section.Paragraphs.Insert(index: int, paragraph: IParagraph) method. The following are the detailed steps:

  • Create a Document instance.
  • Load a Word document using Document.LoadFromFile() method.
  • Get a specified section using Document.Sections[] property.
  • Add a paragraph using Section.AddParagraph() method, and then add text to it using Paragraph.AppendText() method.
  • Set the font name, size, style of the paragraph text.
  • Insert the newly added paragraph at a specified index using Section.Paragraphs.Insert(index: int, paragraph: IParagraph) method.
  • Save the result document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

# Load a Word document
doc.LoadFromFile("Test.docx")

# Get the first section
section = doc.Sections[0]

# Add a paragraph and set its text content
para = section.AddParagraph()
textRange = para.AppendText("Insert a paragraph at a specified location in the Word document.")

# Set the font name, size, color and style
textRange.CharacterFormat.TextColor = Color.get_Blue()
textRange.CharacterFormat.FontName = "Times New Roman"
textRange.CharacterFormat.FontSize = 14
textRange.CharacterFormat.UnderlineStyle = UnderlineStyle.Single

# Insert the paragraph as the third paragraph
section.Paragraphs.Insert(2, para)

# Set spacing after the paragraph
para.Format.AfterSpacing = 10

# Save the result file
doc.SaveToFile("InsertParagraph.docx", FileFormat.Docx2016)
doc.Close()

An output file that inserts a new paragraph as the third paragraph in Word with Python

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 are a powerful tool for presenting information in an organized and engaging manner. To further enhance the organization of slides, PowerPoint allows users to group slides into sections. This feature makes navigating and managing large presentations much easier. In this article, we'll show you how to manage slides within PowerPoint sections in Python using Spire.Presentation for Python. Specifically, we'll cover how to add, retrieve, reorder, and remove slides in these sections.

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 Slides into a PowerPoint Section in Python

Inserting slides is essential when you want to introduce new content to a section. Using Spire.Presentation for Python, you can quickly insert a slide into a section with the Section.Insert() method. The detailed steps are as follows.

  • Create an instance of the Presentation class.
  • Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
  • Get a specific section through its index (0-based) using the Presentation.SectionList(index) property.
  • Add a new slide to the presentation, then insert it into the section using the Section.Insert() method.
  • Remove the added slide from the presentation.
  • Save the resulting presentation using the Presentation.SaveToFile() method.
  • Python
from spire.presentation import *

# Create an instance of the Presentation class
presentation = Presentation()
# Load a PowerPoint presentation
presentation.LoadFromFile("Example.pptx")

# Access the first section
first_section = presentation.SectionList.get_Item(0)

# Add a new slide to the presentation and insert it at the start of the section
slide = presentation.Slides.Append()
first_section.Insert(0, slide)

# Remove the added slide from the presentation
presentation.Slides.Remove(slide)

# Save the modified presentation
presentation.SaveToFile("InsertSlidesInSection.pptx", FileFormat.Pptx2016)
# Close the Presentation object
presentation.Dispose()

Insert Slides into a PowerPoint Section in Python

Retrieve Slides from a PowerPoint Section in Python

Retrieving slides from a specific section allows you to focus on a smaller group of slides for tasks such as reordering or applying custom formatting. Using the Section.GetSlides() method in Spire.Presentation for Python, you can easily access all the slides in a particular section. The detailed steps are as follows.

  • Create an instance of the Presentation class.
  • Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
  • Get a specific section through its index (0-based) using the Presentation.SectionList(index) property.
  • Retrieve the slides within the section using the Section.GetSlides() method.
  • Iterate through the retrieved slides and get the slide number (1-based) of each slide.
  • Python
from spire.presentation import *

# Create an instance of the Presentation class
presentation = Presentation()
# Load a PowerPoint presentation
presentation.LoadFromFile("Example.pptx")

# Retrieve the slides in the 3rd section
section = presentation.SectionList.get_Item(2)
slides = section.GetSlides()

output_content = "The slide numbers in this section are:\n"

# Get the slide number of each slide in the section
for slide in slides:
    output_content += str(slide.SlideNumber) + " "

# Save the slide number to a text file
with open("slide_numbers.txt", "w") as file:
    file.write(output_content)

Retrieve Slides from a PowerPoint Section in Python

Reorder Slides in a PowerPoint Section in Python

Reordering slides is important to ensure related content is in the right order. Spire.Presentation for Python offers the Section.Move() method, which allows you to move a slide to a new position within a section. The detailed steps are as follows.

  • Create an instance of the Presentation class.
  • Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
  • Get a specific section through its index (0-based) using the Presentation.SectionList(index) property.
  • Move a specific slide in the section to another position using the Section.Move() method.
  • Save the resulting presentation using the Presentation.SaveToFile() method.
  • Python
from spire.presentation import *

# Create an instance of the Presentation class
presentation = Presentation()
# Load a PowerPoint presentation
presentation.LoadFromFile("Example.pptx")

# Access the 3rd section
section = presentation.SectionList.get_Item(2)

# Retrieve the slides in the section
slides = section.GetSlides()

# Move the 1st slide in the section to the specified position
section.Move(2, slides[0])

# Save the modified presentation
presentation.SaveToFile("ReorderSlidesInSection.pptx", FileFormat.Pptx2016)
# Close the Presentation object
presentation.Dispose()

Reorder Slides in a PowerPoint Section in Python

Remove Slides from a PowerPoint Section in Python

Removing slides from a section streamlines your presentation, particularly when some slides become outdated or unnecessary. With Spire.Presentation for Python, you can easily remove a single slide or multiple slides from a section using the Section.RemoveAt() or Section.RemoveRange() method. The detailed steps are as follows.

  • Create an instance of the Presentation class.
  • Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
  • Get a specific section through its index (0-based) using the Presentation.SectionList(index) property.
  • Remove a specific slide or a range of slides from the presentation using the Section.RemoveAt() or Section.RemoveRange() method.
  • Save the resulting presentation using the Presentation.SaveToFile() method.
  • Python
from spire.presentation import *

# Create an instance of the Presentation class
presentation = Presentation()
# Load a PowerPoint presentation
presentation.LoadFromFile("Example.pptx")

# Access the 3rd section
section = presentation.SectionList.get_Item(2)

# Remove the first slide from the section
section.RemoveAt(0)

# Or remove a range of slides from the section
# section.RemoveRange(0, 2)

# Save the modified presentation
presentation.SaveToFile("RemoveSlidesInSection.pptx", FileFormat.Pptx2016)
# Close the Presentation object
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.

C#: Create Actions in PDF Documents

2024-11-25 01:09:22 Written by Koohji

Enhancing the interactivity of PDF files is a crucial aspect of document management and user engagement. Creating actions within PDFs using C# in the .NET framework allows developers to add dynamic elements such as file links, web links, and audio that can execute various functions like navigating to different pages, launching external applications, or playing background music, which improves the user experience by making PDFs more functional and engaging. This article demonstrates how to use the Spire.PDF for .NET library to create actions in PDF documents with C#.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

General Steps for Adding Actions to PDF with C#

Adding actions to a PDF using C# involves integrating interactive elements that enhance user experience, such as navigation buttons, file links, web links, or sound triggers. With the Spire.PDF for .NET library, developers can create various actions in PDF documents with C# code. Below is a table of the classes for commonly used actions and their descriptions:

Class Decryption
PdfGoToAction Represents an action that navigates to a destination within the current document.
PdfLaunchAction Represents an action that opens a file.
PdfSoundAction Represents an action that plays a sound.
PdfJavaScriptAction Represents an action that executes JavaScript code in a PDF document.
PdfUriAction Represents an action that resolves a Uniform Resource Identifier (URI).
PdfGoToAction Represents an action that navigates to a destination within the current document.

For more action classes and their descriptions, refer to Spire.PDF for .NET action API references.

Actions can be added to PDF documents in two primary ways:

1. Using Action Annotations

This method involves creating an action and linking it to an annotation on the page. The action is displayed and triggered when the annotation is clicked.

General Steps:

  • Create an instance of PdfDocument class and load a PDF document using PdfDocument.LoadFromFile() method.
  • Get a page using PdfDocument.Pages[] property.
  • Create an instance of the class that represents the action and set the action properties.
  • Create an instance of PdfActionAnnotation class in a rectangular area on the page using the action.
  • Add the cue word for the action to the page (optional).
  • Add the action annotation to the page using PdfPageBase.Annotations.Add() method.
  • Save the result document using PdfDocument.SaveToFile() method.

2. Assigning Actions to Document Events

Actions can also be assigned to document-level events such as opening, closing, or printing the document. These actions are triggered automatically when the specified events occur.

General Steps:

  • Create an instance of PdfDocument class and load a PDF document using PdfDocument.LoadFromFile() method.
  • Create an instance of the class that represents the action and set the action properties.
  • Assign the action to a document event using the following properties:
    • PdfDocument.AfterOpenAction
    • PdfDocument.AfterSaveAction
    • PdfDocument.AfterPrintAction
    • PdfDocument.BeforeCloseAction
    • PdfDocument.BeforeSaveAction
    • PdfDocument.BeforePrintAction
  • Save the result document using PdfDocument.SaveToFile() method.

Create Navigation Actions in PDF with C#

Navigation actions can be created using the PdfGoToAction class, which defines navigation within the document to a specified destination. To achieve this, developers can create a PdfDestination object and pass it as a parameter to a PdfGoToAction instance.

The following is a code example of adding a navigation action to a PDF:

  • C#
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Annotations;
using Spire.Pdf.General;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace AddNavigationButtonPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of PdfDocument
            PdfDocument pdf = new PdfDocument();

            // Load a PDF file
            pdf.LoadFromFile("Sample.pdf");

            // Create a PdfDestination instance and set the destination
            PdfDestination destination = new PdfDestination(pdf.Pages[1]);
            destination.Location = new PointF(0, 0);
            destination.Mode = PdfDestinationMode.Location;
            destination.Zoom = 0.8f;

            // Create a PdfGoToAction based on the destination
            PdfGoToAction action = new PdfGoToAction(destination);

            // Create a rectangle and draw it on the first page
            RectangleF rect = new RectangleF(70, pdf.PageSettings.Size.Height - 120, 140, 20);
            pdf.Pages[0].Canvas.DrawRectangle(PdfBrushes.LightGray, rect);
            // Draw cue words on the rectangle
            PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 14);
            PdfStringFormat stringFormat = new PdfStringFormat(PdfTextAlignment.Center);
            pdf.Pages[0].Canvas.DrawString("To Page 2", font, PdfBrushes.Green, rect, stringFormat);

            // Create a PdfActionAnnotation instance based on the rectangle and the action
            PdfActionAnnotation actionAnnotation = new PdfActionAnnotation(rect, action);

            // Add the action annotation to the first page
            pdf.Pages[0].Annotations.Add(actionAnnotation);

            // Save the document
            pdf.SaveToFile("output/NavigationButton.pdf");
            pdf.Close();
        }
    }
}

Result of Creating Navigation Buttons with C#

Create File Launch Actions in PDF with C#

The PdfLaunchAction class defines a file open action in a PDF that enables users to open a specific file by clicking a button embedded on a PDF page. When implementing this action, developers can set the file path (absolute or relative) and decide whether the file should open in a new window. Here is a code example for adding a file launch action in a PDF document:

  • C#
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Annotations;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace AddFileLaunchActionPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of PdfDocument
            PdfDocument pdf = new PdfDocument();

            // Load a PDF file
            pdf.LoadFromFile("Sample.pdf");

            // Get the first page
            PdfPageBase page = pdf.Pages[0];

            // Draw a rectangle on the page
            RectangleF rect = new RectangleF(50, 50, 180, 20);
            page.Canvas.DrawRectangle(PdfBrushes.LightGray, rect);
            // Darw the cue words in the rectangle
            PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 14);
            PdfStringFormat stringFormat = new PdfStringFormat(PdfTextAlignment.Center);
            pdf.Pages[0].Canvas.DrawString("Click to launch Sample2", font, PdfBrushes.Green, rect, stringFormat);

            // Create a PdfLaunchAction instance
            PdfLaunchAction action = new PdfLaunchAction("C:/Sample2.pdf", PdfFilePathType.Absolute);
            // Set the launch mode to open in new window
            action.IsNewWindow = true;

            // Create a PdfActionAnnotation instance based on the rectangle and the launch action
            PdfActionAnnotation actionAnnotation = new PdfActionAnnotation(rect, action);

            // Add the action annotation to the first page
            page.Annotations.Add(actionAnnotation);

            // Save the document
            pdf.SaveToFile("output/LaunchAction.pdf");
            pdf.Close();
        }
    }
}

Result of Creating File Launch Actions with C#

Create Sound Actions in PDF with C#

Developers can embed audio as an action in PDF documents with the PdfSoundAction class, enabling the audio to play in response to specific triggers, such as opening the file or clicking a button. Below is a code example for creating a sound action in a PDF document:

  • C#
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Annotations;
using Spire.Pdf.Graphics;
using Spire.Pdf.General;
using System.Drawing;

namespace AddSoundActionPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of PdfDocument
            PdfDocument pdf = new PdfDocument();

            // Load a PDF file
            pdf.LoadFromFile("Sample.pdf");

            // Get the first page
            PdfPageBase page = pdf.Pages[0];

            // Darw the cue image on the page
            PdfImage image = PdfImage.FromFile("Sound.png");
            page.Canvas.DrawImage(image, new PointF(30, 30));

            // Create a PdfSoundAction instance and set its property
            PdfSoundAction action = new PdfSoundAction("Wave.wav");
            // Set the sound parameters
            action.Sound.Bits = 16;
            action.Sound.Channels = PdfSoundChannels.Stereo;
            action.Sound.Encoding = PdfSoundEncoding.Signed;
            action.Sound.Rate = 44100;
            // Set the play options
            action.Volume = 0;
            action.Repeat = true;
            action.Mix = true;
            action.Synchronous = true;

            // Create a PdfActionAnnotation instance using the sound action at the location of the cue image
            RectangleF rect = new RectangleF(30, 30, image.Width, image.Height);
            PdfActionAnnotation actionAnnotation = new PdfActionAnnotation(rect, action);

            // Add the action annotation to the first page
            page.Annotations.Add(actionAnnotation);

            // Set the sound action to play after the document is opened
            pdf.AfterOpenAction = action;

            // Save the document
            pdf.SaveToFile("output/SoundAction.pdf");
            pdf.Close();
        }
    }
}

Result of Creating Sound Actions with C#

Create Web Link Actions in PDF with C#

Developers can use the PdfUriAction class to create a web link action in PDF documents, allowing users to open a web link when performing specific actions, such as clicking a button. Below is a code example for creating a web link action in a PDF document:

  • C#
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Annotations;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace AddSoundActionPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of PdfDocument
            PdfDocument pdf = new PdfDocument();

            // Load a PDF file
            pdf.LoadFromFile("Sample.pdf");

            // Get the first page
            PdfPageBase page = pdf.Pages[0];

            // Draw a rectangle on the page
            RectangleF rect = new RectangleF(30, 30, 120, 20);
            page.Canvas.DrawRectangle(PdfBrushes.LightGray, rect);
            // Draw the cue words in the rectangle
            PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 14);
            PdfStringFormat stringFormat = new PdfStringFormat(PdfTextAlignment.Center);
            page.Canvas.DrawString("Go to Google Search", font, PdfBrushes.LightSkyBlue, rect);

            // Create a PdfUriAction instance and set its property
            PdfUriAction action = new PdfUriAction();
            action.Uri = "https://www.google.com/";

            // Create a PdfActionAnnotation instance using the web link action and the rectangle
            PdfActionAnnotation actionAnnotation = new PdfActionAnnotation(rect, action);

            // Add the action annotation to the first page
            page.Annotations.Add(actionAnnotation);

            // Save the document
            pdf.SaveToFile("output/WebLinkAction.pdf");
            pdf.Close();
        }
    }
}

Result of Creating Web Link Actions with C#

Create JavaScript Actions in PDF with C#

The PdfJavaScriptAction represents a JavaScript action in PDF, which allows developers to create complex interactions such as form validations, data calculations, and custom user interfaces. Below is a code example for adding a simple JavaScript action to a PDF document with C#:

  • C#
using Spire.Pdf;
using Spire.Pdf.Actions;

namespace AddJavaScriptActionPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a PdfDocument instance
            PdfDocument pdf = new PdfDocument();

            // Load a PDF file
            pdf.LoadFromFile("Sample.pdf");

            // Define JavaScript code
            var jsCode =
            "app.alert({" +
            "    cMsg: 'Welcome to the article about the Evolution and Advantages of LCD Screens!\\n\\nThis article explores the history and benefits of LCD technology, including its impact on visual experiences across various devices.', " +
            "    nIcon: 3, " +
            "    cTitle: 'Document Introduction'" +
            "});";

            // Create a PdfJavaScriptAction instance using the JavaScript code
            PdfJavaScriptAction action = new PdfJavaScriptAction(jsCode);

            // Set the action to be executed when the PDF document is launched
            pdf.AfterOpenAction = action;

            // Save the document
            pdf.SaveToFile("output/PDFJavaScriptAction.pdf");
            pdf.Close();
        }
    }
}

Result of Creating JavaScript Actions with C#

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.

page 30