冰蓝科技
|
028-81705109
|
|
微信扫一扫
|

Spire.Cloud 纯前端文档控件

在 PDF 文件中添加附件的作用是为了增强文件的交互性和功能性。通过添加附件,我们可以将其他文件(如文档、图像、音频或视频)与PDF文件关联起来,并允许用户轻松地访问这些附件。

Spire.PDF for Python 允许您以两种方式附加文件:

本文将介绍如何使用 Spire.PDF for Python 在 Python 中添加或删除 PDF 文档中的附件。

安装 Spire.PDF for Python

本教程需要用到 Spire.PDF for Python 和 plum-dispatch v1.7.4。可以通过以下 pip 命令将它们轻松安装到 Windows 中。

pip install Spire.PDF

如果您不确定如何安装,请参考此教程: 如何在 Windows 中安装 Spire.PDF for Python

Python 在 PDF 中添加文档附件

Spire.PDF for Python 提供的 PdfDocument.Attachments.Add() 方法即可轻松地向“附件”面板添加附件。 以下是详细步骤。

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

# 创建一个空的PDF文档对象
doc = PdfDocument()

# 从指定文件加载PDF文档
doc.LoadFromFile("团建活动方案.pdf")

# 创建一个PdfAttachment对象,指定要添加的附件文件为"参与人员名单.xlsx"
attachment = PdfAttachment("参与人员名单.xlsx")

# 将附件添加到PDF文档中
doc.Attachments.Add(attachment)

# 将修改后的PDF文档保存到新的文件中
doc.SaveToFile("添加文档附件.pdf")
doc.Close()

Python 添加或删除 PDF 文档中的附件

Python 在 PDF 中的添加注释附件

注释附件将以图标的形式显示在特定页面上。Spire.PDF for Python 提供的 PdfPageBase.AnnotationsWidget.Add() 方法就是向 PDF 中添加注释附件,以下是详细步骤。

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

# 创建一个PdfDocumet对象
doc = PdfDocument()

# 从指定文件加载一个PDF文档
doc.LoadFromFile("团建活动方案.pdf")

# 获取文档的第一页
page = doc.Pages.get_Item(0)

# 定义画刷为红色
brush = PdfBrushes.get_Red()

# 创建PdfTrueTypeFont字体对象,字体名称为"宋体",大小为18.0,加粗,启用unicode
font = PdfTrueTypeFont("宋体", 18.0, PdfFontStyle.Bold, True)

# 设置绘制文本的起始点坐标xP和yP
xP = float(40)
yP = float(page.Canvas.ClientSize.Height - 80)

# 创建字符串格式对象,设置文本对齐方式为左对齐
format1 = PdfStringFormat(PdfTextAlignment.Left)

# 要绘制的文本内容
label = "在此附上详细安排的附件:"

# 在页面上绘制文本
page.Canvas.DrawString(label, font, brush, xP, yP, format1)

# 计算绘制文本所占宽度
textWidth = font.MeasureString(label).Width

# 创建矩形对象bounds,指定注释图标的位置和大小
bounds = RectangleF(float(xP + textWidth + 5), yP, float(20), float(15))

# 创建流对象data,读取附件文件"详细安排.pptx"
data = Stream("详细安排.pptx")

# 创建PDF附件注释对象annotation,指定图标位置、附件文件名和数据
annotation = PdfAttachmentAnnotation(bounds, "详细安排.pptx", data)

# 设置注释的颜色为橙色
annotation.Color = PdfRGBColor(Color.get_Orange())

# 设置注释为只读
annotation.Flags = PdfAnnotationFlags.ReadOnly

# 设置注释的图标为图表类型
annotation.Icon = PdfAttachmentIcon.Graph

# 设置注释的文本内容
annotation.Text = "双击以打开附件。"

# 将注释对象添加到页面的注释集合中
page.AnnotationsWidget.Add(annotation)

# 将修改后的PDF文档保存到新的文件中
doc.SaveToFile("添加注释附件.pdf")
doc.Close()

Python 添加或删除 PDF 文档中的附件

Python 删除 PDF 中的文档附件

PDF 中的文档附件可以通过 PdfDocument.Attachments 来访问,并且可以使用 PdfAttachmentCollection 的 RemoveAt(attachmentIndex) 方法来删除特定的附件或 Clear() 方法来删除全部附件。以下步骤详细介绍了如何从 PDF 中删除文档附件:

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

# 创建一个PdfDocument对象
doc = PdfDocument()

# 从指定文件加载一个PDF文档
doc.LoadFromFile("文档附件.pdf")

# 获取PDF文档中的附件对象集合
attachments = doc.Attachments

# 删除PDF文件的第一个附件(这里索引从0开始)
attachments.RemoveAt(0)

# 删除所有附件
# attachments.Clear()

# 将修改后的PDF文档保存到新的文件中
doc.SaveToFile("删除一个附件.pdf")
doc.Close()

Python 删除 PDF 中的注释附件

注释是基于页面的元素。要获取文档中的所有注释,我们必须先遍历文档的所有页面并获取每一个页面中的所有注释,然后判断某个注释是否是注释附件。最后,使用 Remove() 方法从注释集合中删除注释附件。以下步骤详细介绍了如何从 PDF 中删除注释附件:

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

# 创建一个PdfDocument对象
doc = PdfDocument()

# 从指定文件加载一个PDF文档
doc.LoadFromFile("注释附件.pdf")

# 遍历PDF文档中的每一页
for i in range(doc.Pages.Count):
    # 获取当前页
    pageBase = doc.Pages[i]

    # 遍历当前页的注释
    for j in range(pageBase.AnnotationsWidget.Count):
        # 获取当前注释
        annotationWidget = pageBase.AnnotationsWidget[j]

        # 检查注释是否属于PdfAttachmentAnnotationWidget类型
        if isinstance(annotationWidget, PdfAttachmentAnnotationWidget):
            # 从当前页移除该注释
            pageBase.AnnotationsWidget.Remove(annotationWidget)

# 将修改后的PDF文档保存到新的文件中
doc.SaveToFile("删除注释附件.pdf")
doc.Close()

申请临时 License

如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。

Microsoft Excel 中的超链接是一种在电子表格中创建可点击的链接的实用功能。通过添加超链接,你可以在不同的工作表、工作簿、网站,甚至同一工作簿中的特定单元格之间进行导航。无论是需要引用外部资源、链接相关数据还是创建交互式报表,超链接都能帮助您轻松实现目的。本文将演示如何使用 Spire.XLS for Python 在 Python 中为 Excel 添加超链接。

安装 Spire.XLS for Python

此教程需要 Spire.XLS for Python 和 plum-dispatch v1.7.4。您可以通过以下 pip 命令将它们轻松安装到 Windows 中。

pip install Spire.XLS

如果您不确定如何安装,请参考教程: 如何在 Windows 中安装 Spire.XLS for Python

Python 在 Excel 中添加文本超链接

Excel 中的文本超链接是可点击的词组或短句,可将用户导向 Excel 文件的指定位置、外部资源或电子邮件地址。以下是使用 Python 在 Excel 文件中添加文本超链接的详细步骤:

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

# 创建Workbook类的对象
workbook = Workbook()

# 获取第一张工作表
sheet = workbook.Worksheets[0]

# 添加一个链接到网页的文本超链接
cell1 = sheet.Range["B3"]
urlLink = sheet.HyperLinks.Add(cell1)
urlLink.Type = HyperLinkType.Url
urlLink.TextToDisplay = "链接到网页"
urlLink.Address = "https://www.e-iceblue.cn/"

# 添加一个链接到邮箱的文本超链接
cell2 = sheet.Range["E3"]
mailLink = sheet.HyperLinks.Add(cell2)
mailLink.Type = HyperLinkType.Url
mailLink.TextToDisplay = "链接到邮箱"
mailLink.Address = "mailto:example @outlook.com"

# 添加一个链接到外部文件的文本超链接
cell3 = sheet.Range["B7"]
fileLink = sheet.HyperLinks.Add(cell3)
fileLink.Type = HyperLinkType.File
fileLink.TextToDisplay = "链接到外部文件"
fileLink.Address = "C:\\Users\\Administrator\\Desktop\\报告.xlsx"

# 添加一个链接到指定单元格的文本超链接
cell4 = sheet.Range["E7"]
linkToSheet = sheet.HyperLinks.Add(cell4)
linkToSheet.Type = HyperLinkType.Workbook
linkToSheet.TextToDisplay = "链接到sheet2中的指定单元格"
linkToSheet.Address = "Sheet2!B5"

# 添加一个链接到UNC地址的文本超链接
cell5 = sheet.Range["B11"]
uncLink = sheet.HyperLinks.Add(cell5)
uncLink.Type = HyperLinkType.Unc
uncLink.TextToDisplay = "链接到 UNC 地址"
uncLink.Address = "\\\\192.168.0.121"

# 自适应列宽
sheet.AutoFitColumn(2)
sheet.AutoFitColumn(5)

# 保存结果文件
workbook.SaveToFile("添加文本超链接.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Python 在 Excel 中添加超链接

Python 在 Excel 中添加图片超链接

图片超链接即使用图片作为可点击元素,提供了一种更具有视觉吸引力的展示方式,可用于在 Excel 中导航或访问外部资源。以下是使用 Python 在 Excel 文件中添加图片超链接的详细步骤:

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

# 创建Workbook类的对象
workbook = Workbook()

# 获取第一张工作表
sheet = workbook.Worksheets[0]

# 在指定单元格添加文本
sheet.Range["B1"].Text = "图片超链接"
# 设置第二行的行宽
sheet.Columns[1].ColumnWidth = 15

# 插入图片
picture = sheet.Pictures.Add(3, 2, "logo1.jpg")

# 为图片添加超链接
picture.SetHyperLink("https://www.e-iceblue.cn/", True)
            
# 保存结果文件
workbook.SaveToFile("添加图片超链接.xlsx", ExcelVersion.Version2016)
workbook.Dispose()

Python 在 Excel 中添加超链接

申请临时 License

如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。

Spire.Office for Java 8.12.0已发布。在该版本中,Spire.XLS for Java 新增worksheet.getCellImages()方法来获取用WPS工具添加的内嵌图片;Spire.PDF for Java增强了 PDF 到 SVG、PDF/A1B 和 PDF/A2A 的转换功能 。此外,一些已知问题也在该版本中得到修复。详情请阅读以下内容。

获取 Spire.Office for Java 8.12.0请点击:

https://www.e-iceblue.cn/Downloads/Spire-Office-JAVA.html


Spire.XLS for Java

新功能:

问题修复:


Spire.PDF for Java

问题修复:

超链接在 Word 文档中起到了提供交互性和导航功能的作用,使读者能够方便地浏览相关内容,并且促进了文档的易读性和互动性。本文将介绍如何使用 Spire.Doc for Python 在 Python 中添加和删除 Word 文档中的超链接。

安装 Spire.Doc for Python

本教程需要使用 Spire.Doc for Python 和 plum-dispatch v1.7.4。您可以通过以下 pip 命令将它们轻松安装到 Windows 中。

pip install Spire.Doc

如果您不确定如何安装,请参考此教程:如何在 Windows 中安装 Spire.Doc for Python

Python 添加超链接到 Word 文档

Spire.Doc for Python 提供了Paragraph.AppendHyperlink() 方法,可以将网页链接、电子邮件链接、文件链接或书签链接添加到段落内的文本或图像中。下面是详细的步骤:

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

# 创建一个文档对象
doc = Document()

# 添加一个章节
section = doc.AddSection()

# 创建字符格式对象
characterFormat = CharacterFormat(doc)

# 设置字体为宋体
characterFormat.FontName = "宋体"

# 设置字号为12
characterFormat.FontSize = 12

# 添加段落
paragraph = section.AddParagraph()

# 在段落中添加网页链接
field = paragraph.AppendHyperlink("https://www.e-iceblue.cn/", "网站主页", HyperlinkType.WebLink)
# 应用字符格式到超链接
field.ApplyCharacterFormat(characterFormat)

# 在段落中添加换行符
paragraph.AppendBreak(BreakType.LineBreak)
paragraph.AppendBreak(BreakType.LineBreak)

# 在段落中添加邮件链接
field = paragraph.AppendHyperlink("mailto:support @e-iceblue.com", "发邮件给我们", HyperlinkType.EMailLink)
# 应用字符格式到超链接
field.ApplyCharacterFormat(characterFormat)

paragraph.AppendBreak(BreakType.LineBreak)
paragraph.AppendBreak(BreakType.LineBreak)

# 定义文件路径
filePath = "report.xlsx"
# 在段落中添加文件链接
field = paragraph.AppendHyperlink(filePath, "单击来打开一个Excel报告", HyperlinkType.FileLink)
# 应用字符格式到超链接
field.ApplyCharacterFormat(characterFormat)

# 在段落中添加换行符
paragraph.AppendBreak(BreakType.LineBreak)
paragraph.AppendBreak(BreakType.LineBreak)

# 添加第二个章节
section2 = doc.AddSection()

# 添加段落并插入书签
bookmarkParagrapg = section2.AddParagraph()
bookmarkParagrapg.AppendText("一个书签")
start = bookmarkParagrapg.AppendBookmarkStart("myBookmark")
bookmarkParagrapg.Items.Insert(0, start)
bookmarkParagrapg.AppendBookmarkEnd("myBookmark")

# 在段落中添加链接,跳转到文档内的书签位置
field = paragraph.AppendHyperlink("myBookmark", "跳转到该文档中的一个书签位置", HyperlinkType.Bookmark)
# 应用字符格式到超链接
field.ApplyCharacterFormat(characterFormat)

# 在段落中添加换行符
paragraph.AppendBreak(BreakType.LineBreak)
paragraph.AppendBreak(BreakType.LineBreak)

# 定义图片路径
image = "logo.png"
# 在段落中插入图片
picture = paragraph.AppendPicture(image)
# 在段落中添加图片的网页链接
field = paragraph.AppendHyperlink("https://www.e-iceblue.cn/", picture, HyperlinkType.WebLink)
# 应用字符格式到超链接
field.ApplyCharacterFormat(characterFormat)

# 保存文档
doc.SaveToFile("添加超链接.docx", FileFormat.Docx2016)

# 关闭文档
doc.Close()

# 释放资源
doc.Dispose()

Python 添加和删除 Word 中的超链接

Python 从 Word 文档中删除超链接

要一次性删除 Word 文档中的所有超链接,您需要找到文档中的所有超链接,然后创建一个名为 FlattenHyperlinks() 的自定义方法来依次删除。以下是详细步骤:

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

# 定义函数 FindAllHyperlinks,查找文档中的所有超链接
def FindAllHyperlinks(document):
    # 存储超链接列表的变量
    hyperlinks = []
    for i in range(document.Sections.Count):
        # 获取当前节
        section = document.Sections.get_Item(i)
        for j in range(section.Body.ChildObjects.Count):
            # 获取当前节中的子对象
            sec = section.Body.ChildObjects.get_Item(j)
              # 判断子对象是否为段落
            if sec.DocumentObjectType == DocumentObjectType.Paragraph:
                for k in range((sec if isinstance(sec, Paragraph) else None).ChildObjects.Count):
                    # 获取段落中的子对象
                    para = (sec if isinstance(sec, Paragraph)
                            else None).ChildObjects.get_Item(k)
                      # 判断子对象是否为域
                    if para.DocumentObjectType == DocumentObjectType.Field:
                         # 将子对象转换为域类型
                        field = para if isinstance(para, Field) else None
                        # 判断域类型是否为超链接
                        if field.Type == FieldType.FieldHyperlink:
                            # 将超链接对象添加到列表中
                            hyperlinks.append(field)
    # 返回超链接列表
    return hyperlinks

# 定义函数 FlattenHyperlinks,移除超链接
def FlattenHyperlinks(field):
     # 获取超链接所属段落在文本主体中的索引
    ownerParaIndex = field.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(
        field.OwnerParagraph)
     # 获取超链接在所属段落中的索引
    fieldIndex = field.OwnerParagraph.ChildObjects.IndexOf(field)
     # 获取超链接分隔符所在段落
    sepOwnerPara = field.Separator.OwnerParagraph
     # 获取超链接分隔符所在段落在文本主体中的索引
    sepOwnerParaIndex = field.Separator.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(
        field.Separator.OwnerParagraph)
     # 获取超链接分隔符在所在段落中的索引
    sepIndex = field.Separator.OwnerParagraph.ChildObjects.IndexOf(
        field.Separator)
     # 获取超链接结束符在所属段落中的索引
    endIndex = field.End.OwnerParagraph.ChildObjects.IndexOf(field.End)
     # 获取超链接结束符所在段落在文本主体中的索引
    endOwnerParaIndex = field.End.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(
        field.End.OwnerParagraph)

    FormatFieldResultText(field.Separator.OwnerParagraph.OwnerTextBody,
                           sepOwnerParaIndex, endOwnerParaIndex, sepIndex, endIndex)
     # 删除超链接结束符
    field.End.OwnerParagraph.ChildObjects.RemoveAt(endIndex)

    for i in range(sepOwnerParaIndex, ownerParaIndex - 1, -1):
        if i == sepOwnerParaIndex and i == ownerParaIndex:
            for j in range(sepIndex, fieldIndex - 1, -1):
                 # 删除超链接所在段落中的对象
                field.OwnerParagraph.ChildObjects.RemoveAt(j)

        elif i == ownerParaIndex:
            for j in range(field.OwnerParagraph.ChildObjects.Count - 1, fieldIndex - 1, -1):
                 # 删除超链接所在段落中的对象
                field.OwnerParagraph.ChildObjects.RemoveAt(j)

        elif i == sepOwnerParaIndex:
            for j in range(sepIndex, -1, -1):
                 # 删除分隔符所在段落中的对象
                sepOwnerPara.ChildObjects.RemoveAt(j)
        else:
                # 删除超链接所属段落所在文本主体中的对象
            field.OwnerParagraph.OwnerTextBody.ChildObjects.RemoveAt(i)

# 定义函数 FormatFieldResultText,将超链接对象转换为文本并清除文本格式
def FormatFieldResultText(ownerBody, sepOwnerParaIndex, endOwnerParaIndex, sepIndex, endIndex):
    for i in range(sepOwnerParaIndex, endOwnerParaIndex + 1):
        para = ownerBody.ChildObjects[i] if isinstance(
            ownerBody.ChildObjects[i], Paragraph) else None
        if i == sepOwnerParaIndex and i == endOwnerParaIndex:
            for j in range(sepIndex + 1, endIndex):
               if isinstance(para.ChildObjects[j], TextRange):
                 FormatText(para.ChildObjects[j])

        elif i == sepOwnerParaIndex:
            for j in range(sepIndex + 1, para.ChildObjects.Count):
                if isinstance(para.ChildObjects[j], TextRange):
                  FormatText(para.ChildObjects[j])
        elif i == endOwnerParaIndex:
            for j in range(0, endIndex):
               if isinstance(para.ChildObjects[j], TextRange):
                 FormatText(para.ChildObjects[j])
        else:
            for j, unusedItem in enumerate(para.ChildObjects):
                if isinstance(para.ChildObjects[j], TextRange):
                  FormatText(para.ChildObjects[j])

# 格式化文本
def FormatText(tr):
    tr.CharacterFormat.TextColor = Color.get_Black()
    tr.CharacterFormat.UnderlineStyle = UnderlineStyle.none

# 创建一个文档对象
doc = Document()

# 加载一个Word文档
doc.LoadFromFile("示例文档.docx")

# 获取所有的超链接
hyperlinks = FindAllHyperlinks(doc)

# 删除所有的超链接
for i in range(len(hyperlinks) - 1, -1, -1):
    FlattenHyperlinks(hyperlinks[i])

# 保存到一个新Word文档
doc.SaveToFile("删除超链接.docx", FileFormat.Docx2016)

# 关闭文档
doc.Close()

# 释放资源
doc.Dispose()

Python 添加和删除 Word 中的超链接

申请临时 License

如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。

在处理 PDF 文件时,设置密码或从加密的PDF文档中移除密码的功能对于确保敏感信息的安全性,并同时保持使用 PDF 文件的灵活性和便利性至关重要。通过为 PDF 文档设置密码,个人可以控制对其文件的访问权限,防止未经授权的查看、编辑或复制。相反,解除保护 PDF 文档可以使文档重新可访问或可编辑。在本文中,您将学习如何使用 Spire.PDF for Python 来对 PDF 文档进行密码保护,以及如何从加密的 PDF 文档中移除密码。

安装 Spire.PDF for Python

本教程需要 Spire.PDF for Python 和 plum-dispatch v1.7.4。您可以通过以下 pip 命令将它们轻松安装到 Windows 中。

pip install Spire.PDF

如果您不确定如何安装,请参考此教程: 如何在 Windows 中安装 Spire.PDF for Python

Python 对 PDF 文档进行密码保护

有两种用于安全目的的密码类型可供选择: "打开密码" 和 "权限密码"。打开密码,也称为用户密码,用于限制未经授权访问 PDF 文件。而权限密码,也被称为主密码或所有者密码,允许您对其他人能够在 PDF 文件中执行的操作设置各种限制。如果一个 PDF 文件同时使用这两种密码进行保护,那么可以使用任意一种密码来打开该文件。

Spire.PDF for Python 提供了一个 PdfDocument.Security.Encrypt(String openPassword, String permissionPassword, PdfPermissionsFlags permissions, PdfEncryptionKeySize keySize) 方法,使您可以使用打开密码和/或权限密码来保护 PDF 文件。其中,PdfPermissionsFlags 参数用于指定用户对文档的操作权限。

以下是使用 Spire.PDF for Python 实现 PDF 密码保护的步骤:

  • Python
from spire.pdf import *

# 创建一个 PdfDocument 对象
doc = PdfDocument()

# 从指定路径加载示例 PDF 文件
doc.LoadFromFile("示例.pdf")

# 使用打开密码 ("openPsd")、权限密码 ("permissionPsd") 和允许打印权限对 PDF 文件进行加密
doc.Security.Encrypt("openPsd", "permissionPsd", PdfPermissionsFlags.Print, PdfEncryptionKeySize.Key128Bit)

# 将加密后的 PDF 文件保存到指定的文件路径
doc.SaveToFile("加密文档.pdf", FileFormat.PDF)

# 关闭文档
doc.Close()

Python 加密或解密 PDF 文档

Python 从加密的 PDF 文档中移除密码

要从 PDF 文件中移除密码,可以调用 PdfDocument.Security.Encrypt() 方法,并将打开密码和权限密码设为空字符串。以下是详细步骤:

  • Python
from spire.pdf import *

# 创建一个 PdfDocument 对象
doc = PdfDocument()

# 使用 "openPsd" 打开密码加载加密的 PDF 文件
doc.LoadFromFile("加密文档.pdf", "openPsd")

# 通过将打开密码和权限密码设为空字符串
doc.Security.Encrypt(str(), str(), PdfPermissionsFlags.Default, PdfEncryptionKeySize.Key128Bit, "permissionPsd")

# 将移除密码后的 PDF 文件保存到指定的文件路径
doc.SaveToFile("移除密码.pdf", FileFormat.PDF)

# 关闭文档
doc.Close()

Python 加密或解密 PDF 文档

申请临时 License

如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。

Spire.Office 8.12.2 已发布。在该版本中,Spire.Doc 支持转换 Word 到 PCL 和 PostScript 的文本整形功能;Spire.Presentation 支持将母版页转换为图片; Spire.PDFViewer 支持在WinForm 项目中用Ctrl+滚轮来实现界面缩放的效果。此外,大量已知问题也在该版本中得到修复。详情请阅读以下内容。

该版本涵盖了最新版的 Spire.Doc,Spire.PDF,Spire.XLS,Spire.Email,Spire.DocViewer,Spire.PDFViewer,Spire.Presentation,Spire.Spreadsheet,Spire.OfficeViewer,Spire.Barcode,Spire.DataExport。

版本信息如下:

获取Spire.Office 8.12.2请点击:

https://www.e-iceblue.cn/Downloads/Spire-Office-NET.html


Spire.Doc

新功能:

问题修复:


Spire.Presentation

新功能:

问题修复:


Spire.PDFViewer

新功能:

问题修复:


Spire.PDF

问题修复:


Spire.XLS

问题修复:

表格是 Word 文档中的强大工具,可让使用者以结构化的方式组织和呈现信息。它由行和列组成,形成网格状结构。表通常用于各种目的,例如创建计划、比较数据或以整洁有序的格式显示数据。本文将介绍如何使用 Spire.Doc for Python 在 Python 中创建 Word 文档中的表格。

安装 Spire.Doc for Python

本教程需要使用 Spire.Doc for Python 和 plum-dispatch v1.7.4。您可以通过以下 pip 命令将它们轻松安装到 Windows 中。

pip install Spire.Doc

如果您不确定如何安装,请参考此教程:如何在 Windows 中安装 Spire.Doc for Python

Python 在 Word 文档中创建表格

Spire.Doc for Python 提供了 Section.AddTable() 方法,支持在 Word 文档中创建表格。下面是详细的步骤:

  • Python
from spire.doc import *
from spire.doc.common import *
# 创建文档对象
doc = Document()

# 添加一个节
section = doc.AddSection()

# 创建一个表格对象
table = Table(doc, True)

# 设置表格宽度为100%
table.PreferredWidth = PreferredWidth(WidthType.Percentage, int(100))

# 设置表格边框样式为单线,颜色为黑色
table.TableFormat.Borders.BorderType = BorderStyle.Single
table.TableFormat.Borders.Color = Color.get_Black()

# 添加一行,包含3个单元格
row = table.AddRow(False, 3)

# 设置行高为20.0
row.Height = 20.0

# 获取第一个单元格
cell = row.Cells.get_Item(0)

# 设置单元格垂直居中对齐
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle

# 在单元格中添加段落
paragraph = cell.AddParagraph()

# 设置段落水平居中对齐
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center

# 向段落中添加文本
paragraph.AppendText("Row 1, Col 1")

# 获取第二个单元格
cell = row.Cells[1]

# 设置单元格垂直居中对齐
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle

# 在单元格中添加段落
paragraph = cell.AddParagraph()

# 设置段落水平居中对齐
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
# 向段落中添加文本
paragraph.AppendText("Row 1, Col 2")

# 获取第三个单元格
cell = row.Cells[2]

# 设置单元格垂直居中对齐
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle

# 在单元格中添加段落
paragraph = cell.AddParagraph()

# 设置段落水平居中对齐
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center

# 向段落中添加文本
paragraph.AppendText("Row 1, Col 3")

# 添加另一行,包含3个单元格
row = table.AddRow(False, 3)

# 设置行高为20.0
row.Height = 20.0

# 获取第一个单元格
cell = row.Cells[0]

# 设置单元格垂直居中对齐
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle

# 在单元格中添加段落
paragraph = cell.AddParagraph()

# 设置段落水平居中对齐
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center

# 向段落中添加文本
paragraph.AppendText("Row 2, Col 1")

# 获取第二个单元格
cell = row.Cells[1]

# 设置单元格垂直居中对齐
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle

# 在单元格中添加段落
paragraph = cell.AddParagraph()

# 设置段落水平居中对齐
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center

# 向段落中添加文本
paragraph.AppendText("Row 2, Col 2")

# 获取第三个单元格
cell = row.Cells[2]

# 设置单元格垂直居中对齐
cell.CellFormat.VerticalAlignment = VerticalAlignment.Middle

# 在单元格中添加段落
paragraph = cell.AddParagraph()

# 设置段落水平居中对齐
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center

# 向段落中添加文本
paragraph.AppendText("Row 2, Col 3")

# 将表格添加到节中
section.Tables.Add(table)

# 保存文档到指定路径
doc.SaveToFile("output/CreateTable.docx", FileFormat.Docx2013)

# 关闭文档对象
doc.Close()

Python 在 Word 中创建表格

Python 通过 HTML 字符串创建表格

Spire.Doc for Python 提供了 Paragraph.AppendHTML() 方法,支持在 Word 文档中通过 HTML 字符串创建表格。以下是详细步骤:

  • Python
# 导入 Spire.Doc 库
from spire.doc import *

# 导入 Spire.Doc.Common 库
from spire.doc.common import *

# 创建一个新的文档对象
document = Document()

# 在文档中添加一个节
section = document.AddSection()

# 定义一个 HTML 表格字符串
HTML = "" + "" + "" + "" + \n    "" + "" + "" + \n    "" + "" + "
Row 1, Cell 1Row 1, Cell 2
Row 2, Cell 2Row 2, Cell 2
" # 在节中添加一个段落 paragraph = section.AddParagraph() # 将 HTML 表格添加到段落中 paragraph.AppendHTML(HTML) # 将文档保存为 output/HtmlTable.docx 文件,格式为 Docx2013 document.SaveToFile("output/HtmlTable.docx", FileFormat.Docx2013) # 关闭文档对象 document.Close()

Python 在 Word 中创建表格

Python 合并或拆分表格中单元格

使用表格时,合并或拆分单元格的功能提供了一种强大的方法来自定义和格式化数据。此示例说明如何将相邻单元格合并为单个单元格,以及如何使用 Spire.Doc for Python 将单个单元格拆分为多个较小的单元格。下面是详细的步骤:

  • Python
# 导入 Spire.Doc 库
from spire.doc import *

# 导入 Spire.Doc.Common 库
from spire.doc.common import *

# 创建一个新的文档对象
document = Document()

# 在文档中添加一个节
section = document.AddSection()

# 在节中添加一个表格
table = section.AddTable(True)

# 重置表格的单元格数量为 4x4
table.ResetCells(4, 4)

# 设置表格的首选宽度为 100%
table.PreferredWidth = PreferredWidth(WidthType.Percentage, int(100))

# 遍历表格的所有行,设置每行的行高为 20.0
for i in range(0, table.Rows.Count):
table.Rows[i].Height = 20.0

# 合并表格的第 1 行第 1 列到第 3 列的单元格
table.ApplyHorizontalMerge(0, 0, 3)

# 合并表格的第 1 行第 1 列到第 3 列的单元格
table.ApplyVerticalMerge(0, 2, 3)

# 获取表格第 2 行第 4 列的单元格
cell = table.Rows[1].Cells[3]

# 将第 2 行第 4 列的单元格拆分为两个单元格
cell.SplitCell(3, 0)

# 设置表格第 1 行第 1 列、第 3 行第 1 列和第 2 行第 1 列的单元格的背景颜色为浅蓝色
table.Rows[0].Cells[0].CellFormat.BackColor = Color.get_LightBlue()
table.Rows[2].Cells[0].CellFormat.BackColor = Color.get_LightBlue()

# 设置表格第 1 行第 4 列、第 1 行第 5 列和第 1 行第 6 列的单元格的背景颜色为浅灰色
table.Rows[1].Cells[3].CellFormat.BackColor = Color.get_LightGray()
table.Rows[1].Cells[4].CellFormat.BackColor = Color.get_LightGray()
table.Rows[1].Cells[5].CellFormat.BackColor = Color.get_LightGray()

# 将文档保存为 output/MergeAndSplit.docx 文件,格式为 Docx2013
document.SaveToFile("output/MergeAndSplit.docx", FileFormat.Docx2013)

# 关闭文档对象
document.Close()

Python 在 Word 中创建表格

Python 用 Word 中数据填充表格

本示例创建一个 5x7 的表,将列表中的数据写入单元格,并对标题行和其他行应用不同的格式。以下是主要步骤:

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

# 创建文档对象
doc = Document()
# 添加一个节
section = doc.AddSection()

# 在节中添加一个表格
table = section.AddTable(True)

# 定义表头数据
header_data = ["日期", "产品名称", "生产国家", "出口国家", "保质期"]

# 定义表格行数据
row_data = [
    ["08/07/2021", "海南椰汁", "中国", "韩国", "1个月"],
    ["08/07/2021", "咸鸭蛋", "中国", "日本", "3个月"],
    ["08/07/2021", "奶粉", "俄罗斯", "美国", "12个月"],
    ["08/08/2021", "面包", "丹麦", "中国", "3个月"],
    ["08/09/2021", "巧克力", "俄罗斯", "美国", "6个月"],
    ["08/10/2021", "金枪鱼", "日本", "美国", "15天"]
]
# 重置表格单元格数量
table.ResetCells(len(row_data) + 1, len(header_data))

# 设置表格的首选宽度为100%
table.PreferredWidth = PreferredWidth(WidthType.Percentage, int(100))

# 获取表头行
headerRow = table.Rows[0]

# 设置表头行为标题行,并设置高度、背景颜色等属性
headerRow.IsHeader = True
headerRow.Height = 23
headerRow.RowFormat.BackColor = Color.get_LightGray()

# 遍历表头数据,设置每个单元格的垂直对齐方式、段落格式等属性
i = 0
while i < len(header_data):
    headerRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle
    paragraph = headerRow.Cells[i].AddParagraph()
    paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
    txtRange = paragraph.AppendText(header_data[i])
    txtRange.CharacterFormat.Bold = True
    txtRange.CharacterFormat.FontSize = 12
i += 1

# 遍历表格行数据,设置每个单元格的垂直对齐方式、段落格式等属性
r = 0
while r < len(row_data):
    dataRow = table.Rows[r + 1]
    dataRow.Height = 20
    dataRow.HeightType = TableRowHeightType.Exactly
    c = 0
    while c < len(row_data[r]):
        dataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle
        paragraph = dataRow.Cells[c].AddParagraph()
        paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
        txtRange = paragraph.AppendText(row_data[r][c])
        txtRange.CharacterFormat.FontSize = 11
        c += 1
r += 1

# 遍历表格行,设置偶数行的背景颜色
for j in range(1, table.Rows.Count):
    if math.fmod(j, 2) == 0:
        row2 = table.Rows[j]
        for f in range(row2.Cells.Count):
            row2.Cells[f].CellFormat.BackColor = Color.get_LightBlue()

# 设置表格边框样式、线宽和颜色
table.TableFormat.Borders.BorderType = BorderStyle.Single
table.TableFormat.Borders.LineWidth = 1.0
table.TableFormat.Borders.Color = Color.get_Black()

# 保存文档到指定路径
doc.SaveToFile("output/Table.docx", FileFormat.Docx2013)

Python 在 Word 中创建表格

申请临时 License

如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。

PDF 文件格式能够保留原始文档的格式和布局,非常适合共享和打印。然而,通常情况下,PDF文件是不可编辑的,除非使用专门的软件或工具。通过将 PDF 文档转换为 Word 格式,你可以轻松利用 Word 的功能对文档进行进一步的编辑,例如修改、添加或删除文本,插入图片,添加批注和调整格式等。这篇文章将介绍如何使用 Spire.PDF for Python 在 Python 中将 PDF 文档转换为 Word DOC 或 DOCX 格式。

安装 Spire.PDF for Python

本教程需要用到 Spire.PDF for Python 和 plum-dispatch v1.7.4。可以通过以下 pip 命令将它们轻松安装到 Windows 中。

pip install Spire.PDF

如果您不清楚如何安装,请参考此教程: 如何在 Windows 中安装 Spire.PDF for Python

Python 将 PDF 转换为 Word DOC 或 DOCX

Spire.PDF for Python 提供的 PdfDocument.SaveToFile(filename:str, fileFormat:FileFormat) 方法,可将 PDF 文档转换为 Word DOC 和 DOCX 格式。详细步骤如下:

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

# 创建PdfDocument类的对象
doc = PdfDocument()
# 加载PDF文档
doc.LoadFromFile("示例.pdf")

# 将该PDF文档转换为Word DOCX格式
doc.SaveToFile("Pdf转Docx.docx", FileFormat.DOCX)
# 或将该PDF文档转换为Word DOC格式
doc.SaveToFile("Pdf转Doc.doc", FileFormat.DOC)
# 关闭PdfDocument对象
doc.Close()

Python 将 PDF 转换为 Word DOC 或 DOCX

Python 将 PDF 转换为 Word 时设置文档属性

文档属性是与文档相关的属性或信息,用于提供文件的详细信息,例如文档的作者、标题、主题、版本、关键词、类别等等。通过这些属性,用户可以更全面地了解文档的内容和特征。

Spire.PDF for Python 提供的 PdfToDocConverter 类,允许开发人员将 PDF 文档转换为 Word DOCX 文件并为文件设置文档属性。具体步骤如下。

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

#创建PdfToDocConverter类的对象
converter = PdfToDocConverter("示例.pdf")

# 为转换后的DOCX文件设置文档属性,如标题、主题、作者和关键词等
converter.DocxOptions.Title = "Spire.PDF for Python"
converter.DocxOptions.Subject = "该文档提供了Spire.PDF for Python产品的概述。"
converter.DocxOptions.Tags = "PDF, Python"
converter.DocxOptions.Categories = " PDF处理库"
converter.DocxOptions.Commments = " Spire.PDF是一个多平台的通用库,支持.NET、Java、Python和C++等多种平台。"
converter.DocxOptions.Authors = "肖恩"
converter.DocxOptions.LastSavedBy = "亚楠"
converter.DocxOptions.Revision = 8
converter.DocxOptions.Version = "4.0"
converter.DocxOptions.ProgramName = "Spire.PDF for Python"
converter.DocxOptions.Company = "E-iceblue"
converter.DocxOptions.Manager = "E-iceblue"

# 将PDF文档转换为Word DOCX文件
converter.SaveToDocx("转Word并设置文档属性.docx")

Python 将 PDF 转换为 Word DOC 或 DOCX

申请临时 License

如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。

处理大量的 Word 文档可能是非常具有挑战性的。不论是编辑还是审核大量的文档,都需要花费很多时间打开和关闭文件。此外,分享和接收大量分散的 Word 文档也是很麻烦的事情,因为这可能需要分享者和接收者进行大量重复的发送和接收操作。为了提高工作效率并节省时间,我们可以将相关的多个 Word 文档合并成一个单一的文件,从而可以减少打开和关闭文档的时间浪费,同时也避免了分享和接收大量分散的文档所带来的繁琐操作。本文将介绍如何使用 Spire.Doc for Python 通过 Python 程序轻松合并 Word 文档。

安装 Spire.Doc for Python

本教程需要用到 Spire.Doc for Python 和 plum-dispatch v1.7.4。可以通过以下 pip 命令将它们轻松安装到 Windows 中。

pip install Spire.Doc

如果您不确定如何安装,请参考:如何在 Windows 中安装 Spire.Doc for Python

用 Python 通过插入文件合并 Word 文档

Spire.Doc for Python 提供的 Document.insertTextFromFile() 方法可以用于将其他 Word 文档插入到当前文档中,插入的内容将从新页面开始。通过插入合并 Word 文档的详细步骤如下:

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

# 创建一个 Document 类的对象并加载一个 Word 文档
doc = Document()
doc.LoadFromFile("示例1.docx")

# 将另一个 Word 文档的内容插入到当前文档中
doc.InsertTextFromFile("示例2.docx", FileFormat.Auto)

# 保存文档
doc.SaveToFile("output/插入文件合并Word文档.docx")
doc.Close()

Python 合并 Word 文档

用 Python 通过复制内容合并 Word 文档

合并 Word 文档还可以通过将内容从一个 Word 文档复制到另一个 Word 文档来实现。这种方法可以保持原始文档的格式,且从另一个文档复制的内容会在当前文档的末尾开始,而无需重新开始新的页面。具体步骤如下:

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

# 创建两个 Document 类的对象并加载两个 Word 文档
doc1 = Document()
doc1.LoadFromFile("示例1.docx")
doc2 = Document()
doc2.LoadFromFile("示例2.docx")

# 获取第一个文档的最后一个节
lastSection = doc1.Sections.get_Item(doc1.Sections.Count - 1)

# 遍历第二个文档中的各个节
for i in range(doc2.Sections.Count):
    section = doc2.Sections.get_Item(i)
    # 遍历各个节中的子对象
    for j in range(section.Body.ChildObjects.Count):
        obj = section.Body.ChildObjects.get_Item(j)
        # 将第二个文档中的子对象复制并添加到第一个文档的最后一个节中
        lastSection.Body.ChildObjects.Add(obj.Clone())

# 保存合并后的文档
doc1.SaveToFile("output/复制内容合并Word文档.docx")
doc1.Close()
doc2.Close()

Python 合并 Word 文档

申请临时 License

如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。

通过从 Word 文档中提取文本,用户可以轻松获取文档中包含的文字信息,对文本进行处理、分析和组织等操作,从而完成文本挖掘、情感分析和自然语言处理等任务。另一方面,提取图像可以获取 Word 文档中嵌入的视觉元素,并用于完成图像识别、内容提取或创建图像数据库等任务。本文将介绍如何使用 Spire.Doc for Python 通过 Python 程序提取 Word 文档中的文本和图像。

安装 Spire.Doc for Python

本教程需要用到 Spire.Doc for Python 和 plum-dispatch v1.7.4。可以通过以下 pip 命令将它们轻松安装到 Windows 中。

pip install Spire.Doc

如果您不确定如何安装,请参考:如何在 Windows 中安装 Spire.Doc for Python

用 Python 提取 Word 文档指定段落中的文本

可以使用 Section.Paragraphs[index] 属性从特定节中获取特定段落,接着通过 Paragraph.Text 属性提取该段落的文本内容。具体操作步骤如下:

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

# 创建一个Document对象
doc = Document()

# 加载一个Word文档
doc.LoadFromFile("示例.docx")

# 获取指定的节(section)
section = doc.Sections.get_Item(0)

# 获取指定的段落(paragraph)
paragraph = section.Paragraphs.get_Item(0)

# 从段落获取文本
text = paragraph.Text

# 保存提取的段落为TXT文件
with open("output/提取段落.txt", "w", encoding="utf-8") as file:
    file.write(text)

Python 提取 Word 文档中的文本和图片

用 Python 提取 Word 文档中的所有文本

如果需要获取 Word 文档中的所有文本,可以使用 Document.GetText() 方法直接提取。具体操作步骤如下:

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

# 创建一个Document对象
doc = Document()

# 加载一个Word文档
doc.LoadFromFile("示例.docx")

# 获取文档所有文本
text = doc.GetText()

# 保存获取的文本为TXT文件
with open("output/提取文本.txt", "w", encoding="utf-8") as file:
    file.write(text)

Python 提取 Word 文档中的文本和图片

用 Python 提取 Word 文档中的所有图像

Spire.Doc for Python 还支持提取 Word 文档中的所有图像,只需要遍历文档中的子对象,并保存其中为 DocPicture 类的实例的子对象即可。详细操作步骤如下:

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

# 创建一个Document对象
doc = Document()

# 加载一个Word文件
doc.LoadFromFile("示例.docx")

# 创建一个队列对象
nodes = queue.Queue()
nodes.put(doc)

# 创建一个列表
images = []

while nodes.qsize() > 0:
    node = nodes.get()

    # 遍历文档中的子对象
    for i in range(node.ChildObjects.Count):
        child = node.ChildObjects.get_Item(i)

        # 判断子对象是否为图片
        if child.DocumentObjectType == DocumentObjectType.Picture:
            picture = child if isinstance(child, DocPicture) else None
            dataBytes = picture.ImageBytes

            # 将图片数据添加到列表中
            images.append(dataBytes)
         
        elif isinstance(child, ICompositeObject):
            nodes.put(child if isinstance(child, ICompositeObject) else None)

# 遍历列表中的图片
for i, item in enumerate(images):
    fileName = "图片-{}.png".format(i)
    with open("output/Images/"+fileName,'wb') as imageFile:

        # 将图片写入指定路径
        imageFile.write(item)
doc.Close()

Python 提取 Word 文档中的文本和图片

申请临时 License

如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。