创建复杂的 PDF

Contents
[ ]

Hello, World 示例展示了使用 Python 和 Aspose.PDF 创建 PDF 文档的简易步骤。在本文中,我们将探讨使用 Aspose.PDF for Python 创建更复杂的文档。比如,我们将使用一家虚构的客运渡轮公司文档作为案例。我们的文档将包含一张图像、两个文本片段(标题和段落)以及一个表格。

如果我们从头创建文档,需要遵循以下步骤:

  1. 实例化一个 文档 对象。在此步骤中,我们将创建一个没有页面但带有一些元数据的空 PDF 文档。
  2. 添加一个 页面 添加到文档对象。因此,现在我们的文档将有一页。
  3. 添加一个 图像 到页面。
  4. 创建一个 TextFragment 用于标题。我们将在标题中使用 Arial 字体,字号为 24pt,居中对齐。
  5. 将标题添加到页面 段落.
  6. 创建一个 TextFragment 用于描述。我们将在描述中使用 Arial 字体,字号为 24pt,居中对齐。
  7. 将描述添加到页面段落。
  8. 创建并设置表格样式。设置列宽、边框、内边距和字体。
  9. 在页面上添加表格 段落.
  10. 保存文档 \u0022Complex.pdf\u0022。
from datetime import timedelta
import aspose.pdf as ap


def run_complex(self):

    # Initialize document object
    document = ap.Document()
    # Add page
    page = document.pages.add()

    # Add image
    imageFileName = self.data_dir + "logo.png"
    page.add_image(imageFileName, ap.Rectangle(20, 730, 120, 830, True))

    # Add Header
    header = ap.text.TextFragment("New ferry routes in Fall 2029")
    header.text_state.font = ap.text.FontRepository.find_font("Arial")
    header.text_state.font_size = 24
    header.horizontal_alignment = ap.HorizontalAlignment.CENTER
    header.position = ap.text.Position(130, 720)
    page.paragraphs.add(header)

    # Add description
    descriptionText = "Visitors must buy tickets online and tickets are limited to 5,000 per day. \
    Ferry service is operating at half capacity and on a reduced schedule. Expect lineups."
    description = ap.text.TextFragment(descriptionText)
    description.text_state.font = ap.text.FontRepository.find_font("Times New Roman")
    description.text_state.font_size = 14
    description.horizontal_alignment = ap.HorizontalAlignment.LEFT
    page.paragraphs.add(description)

    # Add table
    table = ap.Table()

    table.column_widths = "200"
    table.border = ap.BorderInfo(ap.BorderSide.BOX, 1.0, ap.Color.dark_slate_gray)
    table.default_cell_border = ap.BorderInfo(ap.BorderSide.BOX, 0.5, ap.Color.black)
    table.default_cell_padding = ap.MarginInfo(4.5, 4.5, 4.5, 4.5)
    table.margin.bottom = 10
    table.default_cell_text_state.font = ap.text.FontRepository.find_font("Helvetica")

    headerRow = table.rows.add()
    headerRow.cells.add("Departs City")
    headerRow.cells.add("Departs Island")

    i = 0
    while i < headerRow.cells.count:
        headerRow.cells[i].background_color = ap.Color.gray
        headerRow.cells[
            i
        ].default_cell_text_state.foreground_color = ap.Color.white_smoke
        i += 1

    time = timedelta(hours=6, minutes=0)
    incTime = timedelta(hours=0, minutes=30)

    i = 0
    while i < 10:
        dataRow = table.rows.add()
        dataRow.cells.add(str(time))
        time = time.__add__(incTime)
        dataRow.cells.add(str(time))
        i += 1

    page.paragraphs.add(table)

    document.save(self.data_dir + "Complex.pdf")