Converting XLS files to various formats is necessary for data management and presentation. ODS, XPS, PostScript, and PDF/A-1b offer unique advantages and are suitable for different scenarios.

ODS is widely used for compatibility with many office suites. XPS preserves document fidelity and is ideal for sharing and archiving. PostScript is a versatile page description language often used for printing and graphic design. PDF/A-1b ensures long-term archiving by complying with strict preservation standards.

This guide will illustrate how to convert Excel to ODS, XPS, PostScript, and PDF/A-1b with Python using Spire.XLS for Python, leveraging their specific strengths to meet diverse needs.

Install Spire.XLS for Python

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

pip install Spire.XLS

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

Convert Excel to ODS, XPS, and PostScript with Python

To convert Excel to ODS, XPS, and PostScript documents, you can utilize Workbook.SaveToFile() method. It supports converting CSV to Excel and PDF, Excel to PDF and XLSX, etc. By using this method provided by Spire.XLS for Python, you can seamlessly transform your documents into these formats while maintaining accuracy without data loss. Read the following steps to learn more:

Steps to convert Excel to ODS, XPS, and PostScript:

  1. Create a new Workbook object.
  2. Import the file to be converted from the disk using Workbook.LoadFromFile() method.
  3. Convert it to ODS, XPS, or PostScript with Workbook.SaveToFile() method.

Here is the code example for reference:

  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load the file from the disk
workbook.LoadFromFile("sample.xlsx")

# Save the document to an ODS file
workbook.SaveToFile("to_ods.ods", FileFormat.ODS)
# Save the document as an XPS file
workbook.SaveToFile("to_xps.xps", FileFormat.XPS)
# Save the document as a PostScript file
workbook.SaveToFile("to_postscript.ps", FileFormat.PostScript)

workbook.Dispose()

Python: Convert Excel to ODS, XPS, PostScript and PDF/A-1b

Note: Images 1, 2, and 3 show the results of converting Excel files to ODS, XPS, and PostScript formats, respectively.

How to Convert Excel Documents to PDF/A-1b Format

If you need to convert Excel to PDF/A-1b Format with Python, call Workbook.SaveToFile will help you. The steps to transform Excel documents to PDF/A-1b are similar to those above, except the former involves an additional step. This tutorial will guide you through the process with detailed steps and a code example.

Steps to convert Excel to PDF/A-1b

  1. Instantiate a new Workbook object.
  2. Read the Excel document from the disk using Workbook.LoadFromFile() method.
  3. Set the PDF conformance level to PDF/A-1b.
  4. Save the generated document as PDF with Workbook.SaveToFile() method.

Here is the code example for you:

  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Open the file from the disk
workbook.LoadFromFile("sample.xlsx")

# Set the PDF conformance to PDF/A-1b
workbook.ConverterSetting.PdfConformanceLevel = PdfConformanceLevel.Pdf_A1B
# Convert the Excel document to PDF/A-1b
workbook.SaveToFile("to_pdfa1b", FileFormat.PDF)

workbook.Dispose()

Python: Convert Excel to ODS, XPS, PostScript and PDF/A-1b

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 Word, adding, adjusting, and removing page borders is an effective strategy to enhance the aesthetics and professionalism of your documents. The inclusion of borders can lend a page a more refined and dignified appearance, particularly suitable for formal contexts such as reports, certificates, or invitations, conveying a sense of meticulous elegance. By customizing the color, pattern, and thickness of borders, users can ingeniously integrate personal creativity according to the document theme, crafting a unique design style that makes the content more captivating. Conversely, opting to remove borders can achieve a streamlined page layout, effectively eliminating unnecessary visual clutter—a practice especially fitting for those pursuing minimalist aesthetics or aiming to save on printing costs. This article will introduce how to add, modify, or remove Word page borders in Python projects 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 VS Code through the following pip command.

pip install Spire.Doc

Python Add Word Page Borders

When setting page borders in a Word document using the Spire.Doc library, you can achieve this by invoking the Section.PageSetup.Borders property. Here are the detailed steps:

  • Create a Document object.
  • Load a document using the Document.LoadFromFile() method.
  • Use a for loop to iterate through each section (Section) in the document.
  • Apply borders to all pages by setting the Section.PageSetup.PageBordersApplyType property to PageBordersApplyType.AllPages.
  • Set the page border style using the Secton.PageSetup.Borders.BorderType(BorderStyle.DashDotStroker) method.
  • Define the border width using the Section.PageSetup.Borders.LineWidth(2) method.
  • Set the border color using the Section.PageSetup.Borders.Color(Color.get_Orange()) method.
  • Set the distance between the border and the page content using the Section.PageSetup.Borders.Top.Space, Bottom.Space, Left.Space, and Right.Space properties.
  • Save the changes to a Word document using the Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

# Load an existing Word document
doc.LoadFromFile("Sample01.docx")

# Iterate through all sections in the document
for i in range(doc.Sections.Count):
    # Set borders for all pages in the current section
    doc.Sections.get_Item(i).PageSetup.PageBordersApplyType = PageBordersApplyType.AllPages

    # Set border style
    doc.Sections.get_Item(i).PageSetup.Borders.BorderType(BorderStyle.DashDotStroker)

    # Set border width
    doc.Sections.get_Item(i).PageSetup.Borders.LineWidth(2)

    # Set border color
    doc.Sections.get_Item(i).PageSetup.Borders.Color(Color.get_Orange())

    # Set the distance between the top border and page content
    doc.Sections.get_Item(i).PageSetup.Borders.Top.Space = 20.0

    # Set the distance between the bottom border and page content
    doc.Sections.get_Item(i).PageSetup.Borders.Bottom.Space = 20.0

    # Set the distance between the left border and page content
    doc.Sections.get_Item(i).PageSetup.Borders.Left.Space = 20.0

    # Set the distance between the right border and page content
    doc.Sections.get_Item(i).PageSetup.Borders.Right.Space = 20.0

# Save the modified document to a new file
doc.SaveToFile("AddWordPageBorders.docx", FileFormat.Docx)

# Release resources used by the Document object
doc.Dispose()

Python: Add, Modify or Remove Word Page Borders

Python Modify Word Page Borders

Leveraging the Spire.Doc library, we can extensively customize the page borders in Word documents, including the style, hue, width, and other visual attributes of the borders. By tweaking these properties, achieving the desired visual presentation becomes effortless. Here are the detailed steps:

  • Create a Document object.
  • Load a document using the Document.LoadFromFile() method.
  • Retrieve the first section of the document using Document.Sections.get_Item(0).
  • Alter the page border style using the Section.PageSetup.Borders.BorderType(BorderStyle.DoubleWave) method.
  • Change the color of the page border with the Section.PageSetup.Borders.Color(Color.get_Orange()) method.
  • Adjust the width of the page border through the Section.PageSetup.Borders.LineWidth(2) method.
  • Save the changes to a Word document using the Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

# Load an existing Word document
doc.LoadFromFile("Sample02.docx")

# Get the first section
section = doc.Sections.get_Item(0)

# Set border style
section.PageSetup.Borders.BorderType(BorderStyle.DoubleWave)

# Set border color
section.PageSetup.Borders.Color(Color.get_Orange())

# Set border width
section.PageSetup.Borders.LineWidth(2)

# Save the modified document to a new file
doc.SaveToFile("ModifyWordPageBorders.docx", FileFormat.Docx)

# Release resources occupied by the Document object
doc.Dispose()

Python: Add, Modify or Remove Word Page Borders

Python Remove Word Page Borders

To remove page borders in Word, you can use the Section.PageSetup.Borders.BorderType(BorderStyle.none) method. Here are the detailed steps:

  • Create a Document object.
  • Load a document using the Document.LoadFromFile() method.
  • Use a for loop to iterate through each section (Section) in the document.
  • Apply the Section.PageSetup.Borders.BorderType(BorderStyle.none) method to remove the page borders.
  • Save the document using the Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()

# Load an existing Word document
doc.LoadFromFile("Sample02.docx")

# Iterate through all sections in the document
for i in range(doc.Sections.Count):
    # Remove page borders
    doc.Sections.get_Item(i).PageSetup.Borders.BorderType(BorderStyle.none)

# Save the modified document to a new file
doc.SaveToFile("RemoveWordPageBorders.docx", FileFormat.Docx)

# Release the resources occupied by the Document object
doc.Dispose()

Python: Add, Modify or Remove Word Page Borders

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: Convert PPS and PPT to PPTX

2024-07-24 09:21:47 Written by Koohji

Converting between presentation documents is a common task, especially when dealing with different versions of Microsoft PowerPoint. PPS is used to display presentations directly as finalized documents. PPT is an older format compatible with PowerPoint 97-2003. PPTX, the default editable format in the latest version of PowerPoint, offers better data recovery capabilities, smaller file sizes, and enhanced security.

Whether you need to edit PPS documents or ensure compatibility with modern tools and features, converting them to PPTX is essential. This article will demonstrate how to convert PPS and PPT to PPTX documents using Python with Spire.Presentation for Python. Read on to learn more.

Install Spire.Presentation

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

pip install Spire.Presentation

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

How to Convert PPS to PPTX with Python

To convert PPS to PPTX format, you can call Document.SaveToFile() method offered by Spire.Presentation for Python. It supports converting various formats to PPT(X), such as PPS and PPT, as well as converting PPT documents to other formats like PDF and images (PNG, JPG, BMP, SVG).

Steps to convert PPS to PPTX:

  1. Create an object for the Presentation class.
  2. Import the document to be converted with Document.LoadFromFile() method.
  3. Convert it to a PPTX document using Document.SaveToFile() method.

Here is the code example for you:

  • Python
from spire.presentation.common import *
from spire.presentation import *
# Create a Presentation document object
pre = Presentation()
# Load the file from the disk
pre.LoadFromFile("input/sample.pps")
# Save the document as PPTX
pre.SaveToFile("ppstopptx.pptx", FileFormat.Pptx2010)
pre.Dispose()

Python: Convert PPS and PPT to PPTX

How to Convert PPT to PPTX with Python

Compared with PPT, PPTX has many advantages. Despite being mentioned above, it supports inserting more multimedia content and advanced formats, thereby improving the overall quality and performance of presentations. Spire.Presentation for Python provides Document.SaveToFile() to convert PPT to PPTX without data loss.

Steps to convert PPT to PPTX:

  1. Instantiate a new Presentation object.
  2. Load the document from the files with Document.LoadFromFile().
  3. Save the PPT document as a PPTX document by Document.SaveToFile().

Below is the code example to refer to:

  • Python
from spire.presentation.common import *
from spire.presentation import *

# Create an instance of the Presentation class
pre = Presentation()

# Load the file to be converted
pre.LoadFromFile("input/Sample1.ppt")

# Convert the document to PPTX format
pre.SaveToFile("ppttopptx.pptx", FileFormat.Pptx2010)

pre.Dispose()

Python: Convert PPS and PPT to PPTX

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: Add a Watermark to Excel

2024-07-23 01:10:21 Written by Koohji

While watermarks are a common design element used in many types of documents to convey ownership, confidentiality, or branding, Microsoft Excel does not provide a built-in watermark feature. However, there are workaround methods to achieve a watermark effect in Excel spreadsheets.

One approach is to add an image to the header or footer of the worksheet, and another approach is to add an image to a worksheet as the background. In this article, you will learn how to add a header or background image watermark to Excel in Python using Spire.XLS for Python.

Install Spire.XLS for Python

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

pip install Spire.XLS

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

Header vs Background Image Watermarks

Header Image Watermark:

Advantages:

  • The watermark is preserved on the printed sheet, ensuring it appears in the final output.

Disadvantages:

  • The watermark is invisible under the "Normal" view mode in Excel, only becoming visible in "Page Layout" or "Page Break Preview" views.
  • To centrally position the watermark graphic on the Excel page, you need to carefully adjust the white margins, especially on the top and left sides of the image.

Background Image Watermark:

Advantages:

  • The watermark image covers the entire worksheet area, providing a consistent background appearance.

Disadvantages:

  • The watermark is not preserved on the printed sheet, meaning it will not appear in the final printed output.

Add a Watermark to Excel Using a Header Image in Python

Spire.XLS for Python offers the PageSetup class to control various settings related to the appearance and layout of the printed worksheet. Under this class, you can find the CenterHeader and CenterHeaderImage properties, allowing you set an image for the center section of the header.

Here are the steps to add a header image watermark to Excel using Python.

  • Create a Workbook object.
  • Load an Excel document from a give file path.
  • Load an image while initialing the Stream class.
  • Get a specific worksheet from the workbook.
  • Add an image field to the header center by setting Worksheet.PageSetup.CenterHeader property to "&G".
  • Apply the image to the header center through Worksheet.PageSetup.CenterHeaderImage property.
  • Save the workbook to a different Excel file.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load an Excel document
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx")

# Load an image file
stream = Stream("C:\\Users\\Administrator\\Desktop\\confidential.png")

# Loop through all worksheets in the file
for i in range(workbook.Worksheets.Count):

    # Get a specific worksheet
    worksheet = workbook.Worksheets[i]

    # Add an image field to the header center
    worksheet.PageSetup.CenterHeader = "&G"

    # Add the image to the header center
    worksheet.PageSetup.CenterHeaderImage = stream

# Save the result file
workbook.SaveToFile("output/AddWatermark.xlsx", ExcelVersion.Version2016)

# Dispose resources
workbook.Dispose()

Python: Add a Watermark to Excel

Add a Watermark to Excel Using a Background Image in Python

The PageSetup class provides the BackgroundImage property to get or set the image for the background. Below are the steps to add a background image watermark to Excel using Python.

  • Create a Workbook object.
  • Load an Excel document from a give file path.
  • Load an image while initialing the Stream class.
  • Get a specific worksheet from the workbook.
  • Apply the image to the worksheet as the background through Worksheet.PageSetup.BackgroundImage property.
  • Save the workbook to a different Excel file.
  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load an Excel document
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx")

# Load an image file
stream = Stream("C:\\Users\\Administrator\\Desktop\\sample-background.png")

# Loop through all worksheets in the file
for i in range(workbook.Worksheets.Count):

    # Get a specific worksheet
    worksheet = workbook.Worksheets[i]

    # Set the image as the background of the worksheet
    worksheet.PageSetup.BackgoundImage = stream

# Save the result file
workbook.SaveToFile("output/AddWatermark.xlsx", ExcelVersion.Version2016)

# Dispose resources
workbook.Dispose()

Python: Add a Watermark to Excel

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: Convert Word to XML, Word XML

2024-07-19 08:04:36 Written by Koohji

XML (Extensible Markup Language) is widely used for its structured format and readability on different platforms and systems. Its self-descriptive tags enable you to process data more easily. Meanwhile, Word XML focuses specifically on storing and exchanging Microsoft Word documents. It allows Word documents to transfer without loss. They both show flexibility under various scenarios that Word documents cannot achieve.

On the page, you will learn how to convert Word to XML and Word XML formats using Python with 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 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.

Convert Word to XML in Python with Spire.Doc for Python

This part will explain how to convert Word documents to XML in Python with step-by-step instructions and a code example. Spire.Doc for Python provides the Document.SaveToFile() method to make it easy to save Word as XML. Check out the steps below and start processing your Word documents without effort!

Steps to Convert Word to XML:

  • Create a new Document object.
  • Load the Word document that you wish to be operated using Document.LoadFromFile() method.
  • Covert it to XML by calling Document.SaveToFile() method.

Here's the code example:

  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Word document object
document = Document()

# Load the file from the disk
document.LoadFromFile("sample.docx")

# Save the document to an XML file
document.SaveToFile("WordtoXML.xml", FileFormat.Xml)

document.Close()

Python: Convert Word to XML, Word XML

Convert Word to Word XML in Python

To convert Word to Word XML, you can utilize the Document.SaveToFile() method provided by Spire.Doc for Python. It not only helps to convert Word documents to Word XML but also to many other formats, such as PDF, XPS, HTML, RTF, etc.

Steps to Convert Word to Word XML:

  • Create a new Document object.
  • Load the Word document by Document.LoadFromFile() method.
  • Convert it to Word XML using Document.SaveToFile() method.

Here's the code example for you:

  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Word document object
document = Document()

# Load the file from the disk
document.LoadFromFile("sample.docx")

# For Word 2003
document.SaveToFile("WordtoWordML.wordml", FileFormat.WordML)

# For Word 2007-2013
document.SaveToFile("WordtoWordXML.wordxml", FileFormat.WordXml)
document.Close()

Python: Convert Word to XML, Word XML

Get a Free License

To fully experience the capabilities of Spire.Doc for Python without any evaluation limitations, you can request a free 30-day trial license.

Python: Copy Cell Formatting in Excel

2024-07-19 02:07:39 Written by Koohji

Formatting plays a crucial role in making your Excel spreadsheets clean, organized, and visually appealing. Often, you may want to apply the same formatting to multiple cells or ranges in your workbook. Instead of manually formatting each cell individually, Excel provides a convenient feature called "Copy Cell Formatting" that allows you to quickly replicate the formatting from one cell to others.

Here in this article, you will learn how to programmatically copy cell formatting in Excel using Spire.XLS for Python.

Install Spire.XLS for Python

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

pip install Spire.XLS

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

Copy Formatting from One Cell to Another in Python

You can access a specific cell by using the Worksheet.Range[row:int, column:int] property. The formatting of that cell can be retrieved through the CellRange.Style property, and this formatting can then be applied to a different cell.

The steps to copy formatting from one to cell to anther are as follows.

  • Create a Workbook object.
  • Load an Excel document from a give path.
  • Get a specific worksheet within the workbook.
  • Get a specific cell through Worksheet.Range[row:int, column:int] property.
  • Get the cell formatting through CellRange.Style property, and apply it to another cell through the same property.
  • Save the workbook to a different Excel file.

This code example loads an existing Excel document, copies the formatting (style) from the cells in the second column to the cells in the fourth column for rows 2 through 14, and then saves the modified workbook to a new Excel file.

  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load an Excel document
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx")

# Get a specific worksheet
worksheet = workbook.Worksheets[0]

# Loop through the selected rows
for i in range(2, 15):

    # Get style (formatting) of a specific cell
    style = worksheet.Range[i, 2].Style

    # Apply the style to a different cell
    worksheet.Range[i, 4].Style = style

# Save the workbook to file
workbook.SaveToFile("output/CopyFormatting.xlsx",ExcelVersion.Version2016)

# Dispose resources
workbook.Dispose()

Python: Copy Cell Formatting in Excel

Copy Formatting from One Cell to a Cell Range in Python

Once you get the style (formatting) of a certain cell, you can apply it to a cell rang which is retrieved through the Worksheet.Range[row:int, column:int, endRow:int, endColumn:int] property.

Here are the steps to copy formatting from once cell to a cell range.

  • Create a Workbook object.
  • Load an Excel document from a give path.
  • Get a specific worksheet within the workbook.
  • Get a specific cell through Worksheet.Range[row:int, column:int] property.
  • Get the formatting of the cell through CellRange.Style property.
  • Get a cell range through Worksheet.Range[row:int, column:int, endRow:int, endColumn:int] property.
  • Apply the formatting to the cell range through CellRange.Style property.
  • Save the workbook to a different Excel file.

This code example loads an existing Excel document, retrieves the style of a cell located in the third row and first column, and then applies that style to a range of cells from the third row, fourth column to the fourth row, sixth column.

  • Python
from spire.xls import *
from spire.xls.common import *

# Create a Workbook object
workbook = Workbook()

# Load an Excel document
workbook.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.xlsx")

# Get a specific worksheet
worksheet = workbook.Worksheets[0]

# Get style (formatting) of a specific cell
style = worksheet.Range[3, 1].Style

# Apply the style to a cell range
worksheet.Range[3, 4, 4, 6].Style = style

# Save the workbook to file
workbook.SaveToFile("output/ApplyFormatToCellRange.xlsx",ExcelVersion.Version2016)

# Dispose resources
workbook.Dispose()

Python: Copy Cell Formatting in Excel

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 creating a new PDF document, you can add information about the company, icons, and page numbers as the header and footer to enhance the appearance and professionalism of PDF documents.

This detailed guide will introduce how to add a header and footer when creating a new PDF Document in Python with Spire.PDF for Python effortlessly. Read on.

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.

Background Knowledge

Spire.PDF for Python offers the PdfPageTemplateElement class for defining page template elements. It provides users with PdfPageTemplateElement.Graphics.DrawString()PdfPageTemplateElement.Graphics.DrawLine()PdfPageTemplateElement.Graphics.DrawImage(), and more to draw text, lines, and images. Furthermore, Spire.PDF for Python supports drawing automatic fields like PdfPageCountField and PdfPageNumberField to the template element by PdfGraphicsWidget.Draw() method.

To draw content on the PdfPageTemplateElement template element, the coordinate system settings are as follows:

  • The coordinates system's origin is positioned at the top left corner of the template.
  • The x-axis extends to the right, and the y-axis extends downward.

Spire.PDF for Python provides PdfDocumentTemplate class to design the entire page templates of a PDF. The defined PdfPageTemplateElement page template elements above can be applied to the PdfDocumentTemplate page template directly.

PdfDocumentTemplate can apply one or more PdfPageTemplateElement page template elements. For example, apply them to PdfDocumentTemplate.Top and PdfDocumentTemplate.Bottom page templates to create a header and footer in the PDF.

The new page generated by Spire.PDF contains margins by default. The initialization coordinates for the PdfDocumentTemplate page template are set as follows:

Python: Add Header and Footer When Creating a PDF Document

Content cannot be drawn in the margins. To apply PdfPageTemplateElement to PdfDocumentTemplate for the header and footer, you can reset the PDF margins to 0. This way, the coordinate system of the PdfDocumentTemplate page template on the new page will adjust based on the size set by the PdfPageTemplateElement. For example:

Python: Add Header and Footer When Creating a PDF Document

Add a Header with Python When Creating a PDF Document

The following explains how to add text, images, and lines to the header using Spire.PDF for Python when creating a new PDF.

Part 1: Design the header template elements by customizing the CreateHeaderTemplate() method.

  • Create PdfPageTemplateElement objects.
  • Set the font, brush, pen, and text alignment format for drawing the content of the header by defining PdfTrueTypeFont, PdfBrushes, PdfPen, and PdfTextAlignment.
  • Load images to be drawn in the header with PdfImage.FromFile() method.
  • Draw text, lines, and images at specified positions in the header template elements using PdfPageTemplateElement.Graphics.DrawString(), PdfPageTemplateElement.Graphics.DrawLine(), and PdfPageTemplateElement.Graphics.DrawImage() methods.

Part 2: Create PDF document objects and call the custom method above to add the header

  • Create a new PdfDocument object.
  • Set page size by  PdfDocoment.PageSettings.Size. Reset the top, bottom, left, and right margins to 0 using PageSettings.Margins.
  • Create a new PdfMargins object to set the sizes of the header, the footer, and the left and right templates.
  • Call the custom method CreateHeaderTemplate() to add a header.
  • Add pages using PdfDocument.Pages.Add() method.
  • Define PdfTrueTypeFont and PdfBrushes to set font and brushes for drawing the main content.
  • Draw content in the specified area on the newly created page using PdfPageBase.Canvas.DrawString() method.
  • Save the resulting file with PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Define CreateHeaderTemplate()
def CreateHeaderTemplate(doc, pageSize, margins):
    #Create a header template with a specified size
    headerSpace = PdfPageTemplateElement(pageSize.Width, margins.Top)
    headerSpace.Foreground = True
    doc.Template.Top = headerSpace

    # Initialize the x and y coordinate points
    x = margins.Left
    y = 0.0

    # Set font, brush, pen, and ext alignment format
    font = PdfTrueTypeFont("Arial", 10.0, PdfFontStyle.Italic, True)
    brush = PdfBrushes.get_Gray()
    pen = PdfPen(PdfBrushes.get_Gray(), 1.0)
    leftAlign = PdfTextAlignment.Left

    # Load the header image and get its height and width values
    headerImage = PdfImage.FromFile("E:\Administrator\Python1\header.png")
    width = headerImage.Width
    height = headerImage.Height
    unitCvtr = PdfUnitConvertor()
    pointWidth = unitCvtr.ConvertUnits(width, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point)
    pointFeight = unitCvtr.ConvertUnits(height, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point)

    # Draw a header image at the specified position
    headerSpace.Graphics.DrawImage(headerImage, headerSpace.Width-x-pointWidth, headerSpace.Height-pointFeight)

    # Draw the header text at the specified place
    headerSpace.Graphics.DrawString("E-iceblue Co. Ltd.\nwww.e-iceblue.com", font, brush, x, headerSpace.Height-font.Height*2, PdfStringFormat(leftAlign))
   
    # Draw the header line at the specified position
    headerSpace.Graphics.DrawLine(pen, x, margins.Top, pageSize.Width - x,  margins.Top)

   
# Create a PdfDocument object
doc = PdfDocument()

# Set the page size and margins
pageSize =PdfPageSize.A4()
doc.PageSettings.Size = pageSize
doc.PageSettings.Margins = PdfMargins(0.0)

# Create a new PdfMargins object to set the size of the header, footer, and left and right templates
margins = PdfMargins(50.0, 50.0, 50.0, 50.0)
doc.Template.Left = PdfPageTemplateElement(margins.Left, pageSize.Height-margins.Bottom-margins.Top)
doc.Template.Right = PdfPageTemplateElement(margins.Right, pageSize.Height-margins.Bottom-margins.Top)
doc.Template.Bottom = PdfPageTemplateElement(pageSize.Width, margins.Bottom)

# Call CreateHeaderTemplate() to add a header
CreateHeaderTemplate(doc, pageSize, margins)

# Add pages according to the settings above
page = doc.Pages.Add()

# Define the font and brush to be used for the page content
font = PdfTrueTypeFont("Arial", 14.0, PdfFontStyle.Regular, True)
brush = PdfBrushes.get_Blue()

# Draw text on the page
text = "Adding a header using Spire.PDF for Python"
page.Canvas.DrawString(text, font, brush, 0.0, 20.0)

# Save the document as PDF
doc.SaveToFile("output/result.pdf", FileFormat.PDF)

# Dispose document objects
doc.Close()

Python: Add Header and Footer When Creating a PDF Document

Adding A Footer When Creating A New PDF Document with Python

The following is about how to add text, lines, and page content to the footer by Spire.PDF for Python when creating a new PDF:

Part 1: Customize CreateFooterTemplate() to design footer template elements

  • Create a PdfPageTemplateElement object.
  • Define PdfTrueTypeFont, PdfBrushes, PdfPen, and PdfTextAlignment to set font, brush, pen, and the text alignment format for drawing the content of footers.
  • Draw lines and text in the footer template element using PdfPageTemplateElement Graphics.DrawString() and PdfPageTemplateElement Graphics.DrawLine() methods.
  • Create PdfPageNumberField () and  PdfPageCountField() objects.
  • Create a PdfCompositeField() object to set the composite format and convert it to a PdfGraphicsWidget type. Use PdfGraphicsWidget.Draw() method to draw the page number field content.

Part 2: Create PDF document objects and call the custom method above to add the footer

  • Create a PdfDocument object.
  • Set page size using PdfDocoment.PageSettings.Size. Reset the top, bottom, left, and right margins to 0 by PageSettings.Margins.
  • Create a new PdfMargins object to set the sizes of the header, footer, and left and right templates.
  • Call the custom method CreateFooterTemplate() to add a Footer.
  • Add pages using PdfDocument.Pages.Add() method.
  • Define PdfTrueTypeFont and PdfBrushes to set font and brushes for drawing the main content.
  • Draw content in the specified area on the newly created page using PdfPageBase.Canvas.DrawString() method.
  • Save the resulting file using PdfDocument.SaveToFile() method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Define CreateFooterTemplate()
def CreateFooterTemplate(doc, pageSize, margins):
    # Create a footer template with specified sizes
    footerSpace = PdfPageTemplateElement(pageSize.Width, margins.Bottom)
    footerSpace.Foreground = True
    doc.Template.Bottom = footerSpace

    # Initialize the x and y coordinate points
    x = margins.Left
    y = 0.0

    # Set font, brush, pen, and ext alignment format
    font = PdfTrueTypeFont("Arial", 12.0, PdfFontStyle.Italic, True)
    brush = PdfBrushes.get_Gray()
    pen = PdfPen(PdfBrushes.get_Gray(), 1.0)
    leftAlign = PdfTextAlignment.Left

     # Draw footer lines at the specified place
    footerSpace.Graphics.DrawLine(pen, x, y, pageSize.Width - x, y)

    # Draw footer text at the specified position
    footerSpace.Graphics.DrawString("email: sales @e-iceblue.com\ntel:028-81705109 ", font, brush, x, y, PdfStringFormat(leftAlign))
   
    # Create fields for page number and total page count
    number = PdfPageNumberField()
    count = PdfPageCountField()
    listAutomaticField = [number, count]

    # Create a composite field and set string formatting for drawing
    compositeField = PdfCompositeField(font, PdfBrushes.get_Gray(), "Page {0} of {1}", listAutomaticField)
    compositeField.StringFormat = PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Top)
    size = font.MeasureString(compositeField.Text)
    compositeField.Bounds = RectangleF(pageSize.Width -x-size.Width, y, size.Width, size.Height)
    newTemplate = compositeField
    templateGraphicsWidget = PdfGraphicsWidget(newTemplate.Ptr)
    templateGraphicsWidget.Draw(footerSpace.Graphics)

   
# Create a PdfDocument object
doc = PdfDocument()

# Set page sizes and the margin
pageSize =PdfPageSize.A4()
doc.PageSettings.Size = pageSize
doc.PageSettings.Margins = PdfMargins(0.0)

# Create a new PdfMargins object for setting sizes of the header, footer, and left and right templates

margins = PdfMargins(50.0, 50.0, 50.0, 50.0)
doc.Template.Left = PdfPageTemplateElement(margins.Left, pageSize.Height-margins.Top-margins.Bottom)
doc.Template.Right = PdfPageTemplateElement(margins.Right, pageSize.Height-margins.Top-margins.Bottom)
doc.Template.Top = PdfPageTemplateElement(pageSize.Width, margins.Top)

# Call CreateFooterTemplate() to add a footer
CreateFooterTemplate(doc, pageSize, margins)

# Add pages according to the settings above
page = doc.Pages.Add()

# Create font and brush for page content
font = PdfTrueTypeFont("Arial", 14.0, PdfFontStyle.Regular, True)
brush = PdfBrushes.get_Blue()

# Draw text on the page
text = "Adding a footer using Spire.PDF for Python"
page.Canvas.DrawString(text, font, brush, 0.0, pageSize.Height-margins.Bottom-margins.Top-font.Height-20)

# Save the document as PDF
doc.SaveToFile("output/result.pdf", FileFormat.PDF)

# Dispose document object
doc.Close()

Python: Add Header and Footer When Creating a PDF Document

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: Merge or Split Tables in Word

2024-07-16 01:17:05 Written by Koohji

Merge tables in Word can be useful when you want to combine data from multiple tables into a single, larger table to create a more comprehensive view of the information. On the contrary, split tables can help you divide a large table into smaller, more manageable sections so you can focus on specific data sets. This article will demonstrate how to merge or split tables 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

Merge Tables in Word in Python

With Spire.Doc for Python, you can combine two or more tables into one by copying all rows from other tables to the target table and then deleting the other tables. 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.
  • Get two tables in the section using Section.Tables[] property.
  • Iterate through all rows in the second table and copy them using Table.Rows[].Clone() method.
  • Add the rows of the second table to the first table using Table.Rows.Add() method.
  • Save the result document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

inputFile = "Cost.docx"
outputFile = "CombineTables.docx"

# Create a Document instance
doc = Document()

# Load a Word document
doc.LoadFromFile(inputFile)

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

# Get the first and second table in the section
table1 = section.Tables[0] if isinstance(section.Tables[0], Table) else None
table2 = section.Tables[1] if isinstance(section.Tables[1], Table) else None

# Add rows of the second table to the first table
for i in range(table2.Rows.Count):
    table1.Rows.Add(table2.Rows[i].Clone())

# Remove the second table
section.Tables.Remove(table2)

# Save the result document
section.Document.SaveToFile(outputFile, FileFormat.Docx2013)
doc.Close()

Python: Merge or Split Tables in Word

Spilt a Table in Word in Python

To split a table into two or more tables, you need to create a new table, then copy the specified rows from the original table to the new table, and then delete those rows from the original table. 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.
  • Get a specified table in the section using Section.Tables[] property.
  • Specify the row index where the table will be split.
  • Create a new instance of the Table class.
  • Iterate through the specified rows in the original table and copy them using Table.Rows[].Clone() method.
  • Add the specified rows to the new table using Table.Rows.Add() method.
  • Iterate through the copied rows and remove each row from the original table using Table.Rows.RemoveAt() method.
  • Add the new table to the section using Section.Tables.Add() method.
  • Save the result document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

inputFile = "CombineTables.docx"
outputFile = "SplitTable.docx"

# Create a Document instance
doc = Document()

# Load a Word document
doc.LoadFromFile(inputFile)

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

# Get the first table in the section
table = section.Tables[0] if isinstance(section.Tables[0], Table) else None

# Specify to split the table from the fifth row
splitIndex = 4

# Create a new table
newTable = Table(section.Document, True)

# Adds rows (from the 5th to the last row) to the new table
for i in range(splitIndex, table.Rows.Count):
    newTable.Rows.Add(table.Rows[i].Clone())

# Delete rows from the original table
for i in range(table.Rows.Count - 1, splitIndex - 1, -1):
    table.Rows.RemoveAt(i)

# Add the new table to the section
section.Tables.Add(newTable)

# Save the result document
section.Document.SaveToFile(outputFile, FileFormat.Docx2013)
doc.Close()

Python: Merge or Split Tables in Word

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.

The inclusion of line numbers in Word documents serves as a critical tool for enhancing readability, facilitating reference, and streamlining collaborative editing processes. Whether you're a lawyer marking up contracts, a researcher annotating scientific papers, or a student revising a thesis, line numbers provide a precise way to cite specific lines, making discussions and revisions more efficient.

The powerful Python programming language enables users to batch add or remove line numbers in Word documents, providing a robust means to automate document preparation workflows. This article will demonstrate how to utilize Spire.Doc for Python to add or remove line numbers in Word documents with Python code.

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: How to Install Spire.Doc for Python on Windows

Add Line Numbers to Word Documents with Python

Spire.Doc for Python provides properties under PageSetup class for line number formatting. The properties and their functions are as follows:

  • LineNumberingStep: Used to set the interval of the line number display.
  • LineNumberingStartValue: Used to set the start number of the line number.
  • LineNumberingDistanceFromText: Used to set the distance between the line number and the text.
  • LineNumberingRestartMode: Used to set when the line number restarts, like every page, every section, or continuously without restarting.

It is important to note that line numbers will only be displayed when the PageSetup.LineNumberingStep property is set to a value greater than 0.

The detailed steps for adding line numbers to Word documents are as follows:

  • Create an instance of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Iterate through the sections in the document:
    • Get the current section using Document.Sections.get_Item() method.
    • Get the page setup of the section through Section.PageSetup property.
    • Set the display interval of the line numbers through PageSetup.LineNumberingStep property.
    • Set the start number of the line numbers through PageSetup.LineNumberingStartValue property.
    • Set the distance between line numbers and text through PageSetup.LineNumberingDistanceFromText property.
    • Set the restarting mode of the line numbers through PageSetup.LineNumberingRestartMode property.
  • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an instance of Document class
doc = Document()

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

# Iterate through the sections
for i in range(0, doc.Sections.Count):
    # Get the current section
    section = doc.Sections.get_Item(i)
    # Get the page setup of the section
    pageSetup = section.PageSetup
    # Set the interval of the line numbering
    pageSetup.LineNumberingStep = 2
    # Set the start number of the line numbering
    pageSetup.LineNumberingStartValue = 1
    # Set the distance between the line number and text
    pageSetup.LineNumberingDistanceFromText = 20
    # Set the restarting mode of the line number
    pageSetup.LineNumberingRestartMode = LineNumberingRestartMode.Continuous

# Save the document
doc.SaveToFile("output/AddLineNumberWord.docx", FileFormat.Docx)
doc.Close()

Python: Add or Remove Line Numbers in Word Documents

Remove Line Numbers from Word Documents with Python

Since the value of the PageSetup.LineNumberingStep property directly determines the display of line numbers, developers can simply set the value to 0 to remove the line numbers from Word documents.

The detailed steps for removing line numbers from a Word document are as follows:

  • Create an instance of Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Iterate through the sections in the document:
    • Get the current section using Document.Sections.get_Item() method.
    • Set the display interval of the line numbers to 0 through Section.PageSetup.LineNumberingStep property to remove the line numbers.
  • Save the document using Document.SaveToFile() method.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create an instance of Document class
doc = Document()

# Load a Word document
doc.LoadFromFile("output/AddLineNumberWord.docx")

# Iterate through the sections
for i in range(0, doc.Sections.Count):
    # Get the current section
    section = doc.Sections.get_Item(i)
    # Set the interval of the line numbering to 0 to remove the line numbering
    section.PageSetup.LineNumberingStep = 0

# Save the document
doc.SaveToFile("output/RemoveLineNumberWord.docx", FileFormat.Docx)
doc.Close()

Python: Add or Remove Line Numbers in Word 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.

Python: Convert PDF to PowerPoint

2024-07-12 01:05:03 Written by Koohji

PDF (Portable Document Format) files are widely used for sharing and distributing documents due to their consistent formatting and broad compatibility. However, when it comes to presentations, PowerPoint remains the preferred format for many users. PowerPoint offers a wide range of features and tools that enable the creation of dynamic, interactive, and visually appealing slideshows. Unlike static PDF documents, PowerPoint presentations allow for the incorporation of animations, transitions, multimedia elements, and other interactive components, making them more engaging and effective for delivering information to the audience.

By converting PDF to PowerPoint, you can transform a static document into a captivating and impactful presentation that resonates with your audience and helps to achieve your communication goals. In this article, we will explain how to convert PDF files to PowerPoint format 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

Convert PDF to PowerPoint in Python

Spire.PDF for Python provides the PdfDocument.SaveToFile(filename:str, FileFormat.PPTX) method to convert a PDF document into a PowerPoint presentation. With this method, each page of the original PDF document will be converted into a single slide in the output PPTX presentation.

The detailed steps to convert a PDF document to PowerPoint format are as follows:

  • Create an object of the PdfDocument class.
  • Load a sample PDF document using the PdfDocument.LoadFromFile() method.
  • Save the PDF document as a PowerPoint PPTX file using the PdfDocument.SaveToFile(filename:str, FileFormat.PPTX) method.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create an object of the PdfDocument class
pdf = PdfDocument()
# Load a sample PDF document
pdf.LoadFromFile("Sample.pdf")

# Save the PDF document as a PowerPoint PPTX file
pdf.SaveToFile("PdfToPowerPoint.pptx", FileFormat.PPTX)
pdf.Close()

Python: Convert PDF to PowerPoint

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 9 of 26
page 9