Grids With Row Spans

This guide will show how to use the grid creator to produce pdf pages that have grids layout with row spans.

Before you begin

You should get your API key from your UniCloud account.

If this is your first time using UniPDF SDK, follow this guide to set up a local development environment.

Clone the project repository

In your terminal, clone the examples repository. It contains the Go code we will be using for this guide.

git clone https://github.com/unidoc/unipdf-examples.git

Navigate to the grid folder in the unipdf-examples directory.

cd unipdf-examples/grid`

How it works

The import section and the init function in lines 9-24 import the necessary libraries and set the metered API key respectively.

The main function is defined in lines 26-67. In lines 27-28, a new creator object is instantiated with page margins of 50 on all sides. Then a new creator.Grid object is instantiated using c.NewGrid(3). This method creates the grid object with columns and returns the pointer to it. In line 34, a new row is created using NewRow method of the creator.Grid object.

Lines 37-43 create the cell that spans multiple rows and set the content using:

	cell, err := row.NewMultiCell(1, 3)
	p := c.NewStyledParagraph()
	p.SetText("Rowspan = 3")
	p.SetMargins(5, 5, 5, 5)
	p.SetFontSize(12)
	cell.SetBorder(CellBorderSideAll, CellBorderStyleSingle, 1)
	cell.SetContent(p)

First, a new GridCell object is created to span 1 column and 3 rows as specified by the parameters (1,3). Then a new paragraph is instantiated and its contents set. The properties of the paragraph are then set. The border properties of the GridCell are then set in line 42, the content of the this cell are set to the paragraph created in line 43.

Additional two cells are then added to the row using AddCell helper function as follows:

AddCell("Row: 0 Cell: 1", c, row, true, false)
AddCell("Row: 0 Cell: 2", c, row, true, false)

The first argument here is the cell content. The second and third argument are the creator object and the Grid objects. The last two arguments specify whether to add border and background respectively. The AddCell function is explained in Simple Grid.

In lines 49-56, two rows are added similarly by calling grid.NewRow() and then AddCell is used to populate them. This is done using the following:

// add second row
	row = grid.NewRow()
	AddCell("Row: 1 Cell: 1", c, row, true, false)
	AddCell("Row: 1 Cell: 2", c, row, true, false)

	// add third row
	row = grid.NewRow()
	AddCell("Row: 2 Cell: 1", c, row, true, false)
	AddCell("Row: 2 Cell: 2", c, row, true, false)

In line 58, the Grid object is applied using c.Draw(grid).
Finally, the document is written to file using `c.WriteToFile(“unipdf-grid-rowspan.pdf”).

Run the code

Run the code using this command

go run pdf_grid_rowspan.go

Sample output

output

Got any Questions?

We're here to help you.