Spire.PDF for Python 12.6.0 现已正式发布。该版本主要开放 PdfTable 与 PdfGrid 的 DataSource 属性,支持结构化数据的直接绑定。详情请查阅以下内容。
新功能:
- 开放 PdfTable 与 PdfGrid 的 DataSource 属性,支持结构化数据的直接绑定。
# Create a PDF document
doc = PdfDocument()
# Get the first page
page = doc.Pages.Add()
# Set initial Y position
y = 320.0
# Draw title
brush1 = PdfBrushes.get_Black()
font1 = PdfTrueTypeFont("Arial", 16.0, PdfFontStyle.Bold, True)
format1 = PdfStringFormat(PdfTextAlignment.Center)
page.Canvas.DrawString("Country List", font1, brush1, page.Canvas.ClientSize.Width / 2, y, format1)
# Update Y position after title
y = y + font1.MeasureString("Country List", format1).Height
y = y + 5.0
# Prepare raw data
data = [
"Name;Capital;Continent;Area;Population",
"Argentina€;Buenos Aires;South America;2777815;32300003",
"Bolivia;La Paz;South America;1098575;7300000",
"Brazil;Brasilia;South America;8511196;150400000",
"Canada;Ottawa;North America;9976147;26500000",
"Chile;Santiago;South America;756943;13200000"
]
# Convert to 2D array
dataSource = [row.split(";") for row in data]
# Create table
table = PdfTable()
table.Style.CellPadding = 2
# Set alternate row font
font = PdfTrueTypeFont("Arial", 8.0, PdfFontStyle.Regular, True)
table.Style.AlternateStyle.Font = font
# Configure header
table.Style.HeaderSource = PdfHeaderSource.Rows
table.Style.HeaderRowCount = 1
table.Style.ShowHeader = True
# Bind data source
table.DataSource = data
# Draw table (Uncomment to enable)
result = table.Draw(page, PointF(60.0, y))
y = y + result.Bounds.Height + 5
# Draw footer note
brush2 = PdfBrushes.get_Gray()
font2 = PdfTrueTypeFont("Arial", 9.0, PdfFontStyle.Regular, True)
page.Canvas.DrawString(f"* {len(data) - 1} countries in the list.",
font2, brush2, 65.0, y)
# Save and close document
doc.SaveToFile(outputFile)
doc.Close()
# Create a PDF document
doc = PdfDocument()
# Add an A4 page with custom margins
page = doc.Pages.Add(PdfPageSize.A4(), PdfMargins(5.0))
# Initialize the grid and set cell padding
grid = PdfGrid()
grid.Style.CellPadding = PdfPaddings(10.0, 10.0, 10.0, 10.0)
# Prepare raw data
data = ["Name;Capital;Continent;Area;Population",
"Argentina;Buenos Aires;South America;2777815;32300003",
"Bolivia;La Paz;South America;1098575;7300000",
"Brazil;Brasilia;South America;8511196;150400000",
"Canada;Ottawa;North America;9976147;26500000",
"Chile;Santiago;South America;756943;13200000"
]
# Bind data source to the grid
grid.DataSource = data
# Center align text in all cells horizontally and vertically
for j in range(grid.Rows.Count):
cells = grid.Rows.get_Item(j).Cells
for k in range(cells.Count):
cells.get_Item(k).StringFormat = PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)
# Draw the grid on the page
grid.Draw(page, PointF(0.0, 0.0));
# Save the document as a PDF
doc.SaveToFile(outputFile)
# Close the document
doc.Close()
获取 Spire.PDF for Python 12.6.0 请点击:







