Putpdf Table - Add Tables To A PDF
Putpdf Table - Add Tables To A PDF
com
putpdf table — Add tables to a PDF file
Description
putpdf table creates a new table in the active PDF file. Tables may be created from several
output types, including the data in memory, matrices, and estimation results.
Quick start
Add a table named tbl1 with three rows and four columns to the document
putpdf table tbl1 = (3,4)
As above, but with the title “Table 1”
putpdf table tbl1 = (3,4), title("Table 1")
Insert the image in myimg.png in the second row and second column of table tbl1
putpdf table tbl1(2,2) = image(myimg.png)
Set the content of the cell on the second row and first column to be “Image 1” and center the text
putpdf table tbl1(2,1) = ("Image 1"), halign(center)
Add a table named tbl2 with regression results after regress
putpdf table tbl2 = etable
Format the content on all rows of columns two through four of tbl2 to have two decimal places
putpdf table tbl2(.,2/4), nformat(%5.2f)
Add a table with the contents matrix mymat, including the row names and column names of the
matrix
putpdf table tbl3= matrix(mymat), rownames colnames
1
2 putpdf table — Add tables to a PDF file
Syntax
Describe table
putpdf describe tablename
tablename specifies the name of a new table. The name must be a valid name according to Stata’s
naming conventions; see [U] 11.3 Naming conventions.
putpdf table — Add tables to a PDF file 3
fspec is
fontname , size , color
fontname may be any supported font installed on the user’s computer. Base 14 fonts, Type 1
fonts, and TrueType fonts with an extension of .ttf and .ttc are supported. TrueType fonts
that cannot be embedded may not used. If fontname includes spaces, then it must be enclosed
in double quotes. The default font is Helvetica.
size is a numeric value that represents font size measured in points. The default is 11.
color sets the text color.
bspec is
bordername , bpattern , bcolor
bordername specifies the location of the border.
bpattern is a keyword specifying the look of the border. Possible patterns are nil and single.
The default is single. To remove an existing border, specify nil as the bpattern.
bcolor specifies the border color.
unit may be in (inch), pt (point), cm (centimeter), or twip (twentieth of a point). An inch is equivalent
to 72 points, 2.54 centimeters, or 1440 twips. The default is in.
color and bcolor may be one of the colors listed in Colors of [RPT] Appendix for putpdf; a valid
RGB value in the form ### ### ###, for example, 171 248 103; or a valid RRGGBB hex value in
the form ######, for example, ABF867.
returnset exports a group of Stata return values to a table in the active document. It is intended
primarily for use by programmers and by those who want to do further processing of their
exported results in the active document. returnset may be one of the following:
returnset Description
escalars all ereturned scalars
rscalars all returned scalars
emacros all ereturned macros
rmacros all returned macros
ematrices all ereturned matrices
rmatrices all returned matrices
e* all ereturned scalars, macros, and matrices
r* all returned scalars, macros, and matrices
The following output types are supported when adding content to an existing table using putpdf
table tablename(i, j):
(exp) writes a valid Stata expression to a cell; see [U] 13 Functions and expressions.
image filename adds a portable network graphics (.png) or JPEG (.jpg) file to the table cell.
filename is the path to the image file. It may be either the full path or the relative path from
the current working directory.
table(mem tablename) adds a previously created table, identified by mem tablename, to the
table cell.
The following combinations of tablename(numlisti , numlistj ) (see [U] 11.1.8 numlist for valid
specifications) can be used to format a cell or range of cells in an existing table:
tablename(i, j) specifies the cell on the ith row and jth column.
tablename(i, .) and tablename(numlisti , .) specify all cells on the ith row or on the rows
identified by numlisti .
tablename(., j) and tablename(., numlistj ) specify all cells in the jth column or in the columns
identified by numlistj .
tablename(., .) specifies the whole table.
Options
Options are presented under the following headings:
table options
cell options
row col options
cell fmt options
6 putpdf table — Add tables to a PDF file
table options
memtable specifies that the table be created and held in memory instead of being added to the active
document. By default, the table is added to the document immediately after it is created. This
option is useful if the table is intended to be added to a cell of another table or to be used multiple
times later.
width(# unit | % ) and width(matname) set the table width. Any two of the types of width
specifications can be combined.
width(# unit | % ) sets the width based on a specified value. # may be an absolute width or a
percentage of the default table width, which is determined by the page width of the document.
For example, width(50%) sets the table width to 50% of the default table width. The default is
width(100%).
width(matname) sets the table width based on the dimensions specified in the Stata matrix
matname, which has contents in the form of (#1 , #2 , . . . , #n ) to denote the percent of the default
table width for each column. n is the number of columns of the table, and the sum of #1 to #n
must be equal to 100.
halign(hvalue) sets the horizontal alignment of the table within the page. hvalue may be left,
right, or center. The default is halign(left).
indent(# unit ) specifies the table indentation from the left margin of the current document.
spacing(position, # unit ) sets the spacing before or after the table. position may be before or
after. before specifies the space before the top of the current table, and after specifies the
space after the bottom of the current table. This option may be specified multiple times in a single
command to account for different space settings.
border(bordername , bpattern , bcolor ) adds a single border in the location specified by
bordername, which may be start, end, top, bottom, insideH (inside horizontal borders),
insideV (inside vertical borders), or all. Optionally, you may change the pattern and color for
the border by specifying bpattern and bcolor.
This option may be specified multiple times in a single command to accommodate different border
settings. If multiple border() options are specified, they are applied in the order specified from
left to right.
varnames specifies that the variable names be included as the first row in the table when the table
is created using the dataset in memory. By default, only the data values are added to the table.
obsno specifies that the observation numbers be included as the first column in the table when the
table is created using the dataset in memory. By default, only the data values are added to the
table.
nformat(% fmt) specifies the numeric format to be applied to the source values when creating the
table from a Stata or Mata matrix. The default is nformat(%12.0g).
rownames specifies that the row names of the Stata matrix be included as the first column in the
table. By default, only the matrix values are added to the table.
colnames specifies that the column names of the Stata matrix be included as the first row in the
table. By default, only the matrix values are added to the table.
title(string) inserts a row without borders above the current table. The added row spans all the
columns of the table and contains string as text. The added row shifts all other table contents down
by one row. You should account for this when referencing table cells in subsequent commands.
putpdf table — Add tables to a PDF file 7
note(string) inserts a row without borders to the bottom of the table. The added row spans all the
columns of the table. This option may be specified multiple times in a single command to add
notes on new lines within the same cell. Note text is inserted in the order it was specified from
left to right.
cell options
append specifies that the new content for the cell be appended to the current content of the cell.
If append is not specified, then the current content of the cell is replaced by the new content.
Unlike with the putdocx command, this option with putpdf is used only for appending a new
string to the cell when the original cell content is also a string.
rowspan(#) sets the specified cell to span vertically # cells downward. If the span exceeds the total
number of rows in the table, the span stops at the last row.
colspan(#) sets the specified cell to span horizontally # cells to the right. If the span exceeds the
total number of columns in the table, the span stops at the last column.
span(#1 , # 2 ) sets the specified cell to span # 1 cells downward and span # 2 cells to the right.
linebreak (#) specifies that one or # line breaks be added after the text within the cell.
This option may be specified multiple times in a single command to accommodate different border
settings. If multiple border() options are specified, they are applied in the order specified from
left to right.
bgcolor(color) sets the background color for the specified cell or for all cells in the specified row,
column, or range.
nformat(% fmt) applies the Stata numeric format % fmt to the text within the specified cell or within
all cells in the specified row, column, or range. This setting only applies when the content of the
cell is a numeric value.
font(fontname , size , color ) sets the font, font size, and font color for the text within the
specified cell or within all cells in the specified row, column, or range. The font size and font
color may be specified individually without specifying fontname. Use font("", size) to specify
font size only. Use font("", "", color) to specify font color only. For both cases, the default
font will be used.
bold applies bold formatting to the text within the specified cell or within all cells in the specified
row, column, or range.
italic applies italic formatting to the text within the specified cell or within all cells in the specified
row, column, or range.
script(sub | super) changes the script style of the text. script(sub) makes the text a subscript.
script(super) makes the text a superscript. script() may only be specified when formatting
a single cell.
strikeout adds a strikeout mark to the current text within the specified cell or within all cells in
the specified row, column, or range.
underline adds an underline to the current text within the specified cell or within all cells in the
specified row, column, or range.
allcaps uses capital letters for all letters of the current text within the specified cell or within all
cells in the specified row, column, or range.
Now we create our table with the necessary dimensions. We are exporting three statistics that will
appear in one column. We need to allot another column to label these statistics. Therefore, we create
a table named mpgstats with three rows and two columns, and we add a title. By default, the table
width is set at 100%, but because our content is rather short, we set the width to 40% of the default.
Otherwise, the table would take up a large portion of our document and look very empty.
. putpdf table mpgstats = (3,2), title(Mpg summary statistics) width(40%)
. putpdf describe mpgstats
When we describe our table, it reports four rows instead of the three we specified. When we add
a title, it is included as the first row of the table without any borders. With our table in place, we
now summarize mpg and view the list of stored results:
. summarize mpg
Variable Obs Mean Std. Dev. Min Max
All the statistics we want are stored in rclass scalars. We can directly refer to stored results
with putpdf table. We begin filling in the table by putting the label for the minimum in the second
row and first column, mpgstats(2,1). Then we add the value of the minimum in the cell next to
it, mpgstats(2,2), by referring to the r(min) scalar shown above. Similarly, we add the mean on
row 3 and the maximum on row 4.
. putpdf table mpgstats(2,1) = ("Min.")
. putpdf table mpgstats(2,2) = (r(min))
. putpdf table mpgstats(3,1) = ("Mean")
. putpdf table mpgstats(3,2) = (r(mean)), nformat(%5.2f)
. putpdf table mpgstats(4,1) = ("Max.")
10 putpdf table — Add tables to a PDF file
We format the mean of mpg to report only two digits after the decimal. After saving our work,
example.pdf contains the following:
We want the variable names to serve as column titles, so we rename foreign to Origin. Then,
we export the data in memory as a table by specifying in data() the variable names Origin, Obs,
Min, Mean, and Max. In this case, we use the table name tbl1. The order of the variable names in
the list determines the column order in the table.
putpdf table — Add tables to a PDF file 11
By default, the exported table includes single borders around all cells. We use the border()
option to remove all vertical borders from the table.
We further customize the table by setting the text for all cells of the table to be right-aligned
instead of the default left-alignment. Because we would like all cells in the table to be right-aligned,
we specify “.” for both the row and column specification.
. putpdf table tbl1(.,.), halign(right)
. putpdf table tbl1(2/3,4), nformat(%5.2f)
. putpdf save example, replace
successfully created "C:/mypath/example.pdf"
We save our work, replacing the existing example.pdf file with the contents of tbl1:
We want to add these regression results to the document. For most estimation commands, we
can use the etable output type to add the elements of the displayed coefficient table. To export all
columns of the default regress output, we need type only
. putpdf table reg = etable
But we need not stop there. In example 3, we select a subset of the results and format them.
12 putpdf table — Add tables to a PDF file
Equivalently, we could have dropped the third column three times, because each time we drop it, the
previous fourth column becomes the third.
Now that we have only the statistics we want, we can format our table by removing the border
on the right side of the first column. To do this, we specify nil as the border pattern for the right
border. We also format all estimates, in what will now be columns two through four, to have three
decimal places by specifying the column indexes as a range. Finally, we erase the text “mpg” from
the header for the first column and save our work.
. putpdf table tbl2(.,1), border(right, nil)
. putpdf table tbl2(.,2/4), nformat(%9.3f)
. putpdf table tbl2(1,1) = ("") // erase the content of first cell "mpg"
. putpdf save example, replace
successfully created "C:/mypath/example.pdf"
In this example, because we wanted to use the same number of decimals for all estimates in our
table and because we are using the etable output type, we could have preemptively set the format
with our regress command. The modified version of the command is
. regress mpg gear_ratio turn foreign, noheader cformat(%9.3f)
The etable output type also works after estimates table, and you may find it easier to build
a table of selected estimates prospectively. See example 3 in [R] estimates table for an illustration.
First, we create the matrix rtable as the transpose of r(table) because we want to see the
variable names in rows. The point estimates and confidence intervals in the regression table can be
extracted from the matrix rtable. We can extract columns 1, 5, and 6 from rtable, combine them,
and assign them to another new matrix, r table.
. matrix rtable = r(table)’
. matrix r_table = rtable[1...,1], rtable[1...,5..6]
Then we create a new active document and export r table as a table with the name tbl3.
. putpdf begin
. putpdf table tbl3 = matrix(r_table), nformat(%9.3f) rownames colnames
> border(start, nil) border(insideH, nil) border(insideV, nil) border(end, nil)
In this table, all values imported from the matrix have been formatted as %9.3f. In addition, the
row and column names of the matrix r table are included as the first column and first row of the
table. We keep only the top and bottom borders of the table by specifying nil for the leading edge
border (start), trailing edge border (end), inside horizontal edges border (insideH), and inside
vertical edges border (insideV).
14 putpdf table — Add tables to a PDF file
The column names (b, ll, and ul) from the matrix may not be exactly what we want; we can
modify them by customizing the corresponding cells. We can reset the contents and the horizontal
alignment of the cells on the first row to give the columns new titles.
. putpdf table tbl3(1,2) = ("Coef."), halign(right)
. putpdf table tbl3(1,3) = ("[95% Conf. Interval]"), halign(right) colspan(2)
Afterward, we add back the bottom border of the first row and right-align the cells on the rest of the
rows by specifying the row range as two through five.
. putpdf table tbl3(1,.), border(bottom)
. putpdf table tbl3(2/5,.), halign(right)
. putpdf save example, replace
successfully created "C:/mypath/example.pdf"
Next we tabulate our variables of interest, storing the frequencies in a matrix named repairs.
We then create a new active document and add the matrix contents as a table, tbl4, adding a column
at the end for the totals.
. tabulate foreign rep78, matcell(repairs)
Repair Record 1978
Car type Poor Fair Average Good Excellent Total
Domestic 2 8 27 9 2 48
Foreign 0 0 3 9 9 21
Total 2 8 30 18 11 69
. putpdf begin
. putpdf table tbl4 = matrix(repairs), rownames colnames
. putpdf table tbl4(.,6), addcols(1)
. putpdf table tbl4(1,7) = ("Total")
We have exported the tabulations, but we still need to label the columns and rows. We begin by
looping over the two values of foreign, 0 and 1. We use the extended macro function label to store
the labels for each category in the macro ‘rlbl’. Within that loop, we also loop over the five columns
for repair records and label the columns similarly. To calculate the row totals, we create a macro
freq‘row’ val that points to the frequency of a given cell. We store the cumulative frequencies in
the macro cumul freq‘row’, which is incremented in each run of the loop.
. forvalues i=0/1 {
2. local rlbl: label (foreign) ‘i’
3. local row = ‘i’ + 2
4. putpdf table tbl4(‘row’,1) = (‘"‘rlbl’"’)
putpdf table — Add tables to a PDF file 15
5.
. forvalues j=1/5 {
6. local clbl: label (rep78) ‘j’
7. local cstart = ‘j’ + 1
8. putpdf table tbl4(1,‘cstart’) = (‘"‘clbl’"’)
9. local freq‘row’_val = repairs[‘i’+1,‘j’]
10. local cumul_freq‘row’ = ‘cumul_freq‘row’’ + ‘freq‘row’_val’
11. putpdf table tbl4(‘row’,7) = ("‘cumul_freq‘row’’")
12. }
13. }
Once all the frequencies have been exported, we insert a row at the top of the table to provide a
title. Additionally, we provide a label for the first column.
. putpdf table tbl4(1,.), addrows(1,before)
. putpdf table tbl4(1,1)= ("1978 repair records"), colspan(7) halign(center)
> border(left,nil) border(top,nil) border(right,nil)
. putpdf table tbl4(2,1)= ("Car type")
. putpdf save example, replace
successfully created "C:/mypath/example.pdf"
In the example above, we exported the cross-tabulation of foreign and rep78 using the matrix
of stored results. To complete our table, we added a column for the totals and a row for the title.
Similarly, in your work you may need to add components to a table after the initial export of results.
In the example below, we demonstrate how to create a table by gradually adding components.
. use https://www.stata-press.com/data/r16/census9
(1980 Census data by state)
. regress drate i.region medage [aw=pop], noheader
(sum of wgt is 225,907,472)
region
N Cntrl .3138738 2.456431 0.13 0.899 -4.633632 5.26138
South -1.438452 2.320244 -0.62 0.538 -6.111663 3.234758
West -10.90629 2.681349 -4.07 0.000 -16.30681 -5.505777
Our goal is to collect the point estimates and confidence intervals and output a table that looks
like the following:
To create our table of point estimates and confidence intervals, we add a 1 × 3 table with no
borders to our new active document and fill the single row with Variable, Coef., and 95% C.I..
We also set the table width to be 4 inches, put the table in the center of the document, and add back
the top and bottom borders.
. putpdf begin
. putpdf table tbl5 = (1,3), border(all,nil) width(4) halign(center)
. putpdf table tbl5(1,1)=("Variable"), border(top) border(bottom)
. putpdf table tbl5(1,2)=("Coef."), halign(center) border(top) border(bottom)
. putpdf table tbl5(1,3)=("95% C.I."), halign(right) border(top) border(bottom)
Afterward, we add one row to the end of the table and fill in the content of the first column in
this row as region.
. putpdf table tbl5(1,.), addrows(1)
. putpdf table tbl5(2,1)=("region")
putpdf table — Add tables to a PDF file 17
In the resulting table, the region variable has four levels, and each level takes up one row. The
medage variable and the constant term take up another two rows. For each row, the first column
contains the variable label, the second column contains the point estimate that is stored in the matrix
b, and the third column contains a formatted string of the lower limit and upper limit of the confidence
intervals. Those two levels are stored in matrix ll and ul, respectively.
Based on the above information, we add those rows one by one at the end of the table and fill
in the content and format for each cell in the corresponding row. Notice that NE is the base level
of region; its point estimate and confidence interval are replaced by Ref. and N/A in the resulting
table. In addition, we reset the top and bottom borders for medage and Intercept.
. local row 2
. local i 1
. foreach name in "NE" "N Cntrl" "South" "West" "medage" "Intercept" {
2. putpdf table tbl5(‘row’,.), addrows(1)
3. local ++row
4. if "‘name’"=="NE" {
5. local coef "Ref."
6. local ci "N/A"
7. }
8. else {
9. local coef : display %5.1f b[‘i’,1]
10. local low : display %5.1f ll[‘i’,1]
11. local upp : display %5.1f ul[‘i’,1]
12. local ci "‘low’ to ‘upp’"
13. }
14. putpdf table tbl5(‘row’, 1) = ("‘name’"), halign(right)
15. putpdf table tbl5(‘row’, 2) = ("‘coef’"), halign(center)
16. putpdf table tbl5(‘row’, 3) = ("‘ci’"), halign(right)
17. if "‘name’"=="medage" | "‘name’"=="Intercept" {
18. putpdf table tbl5(‘row’, 1), halign(left) border(top)
> border(bottom)
19. putpdf table tbl5(‘row’, 2), border(top) border(bottom)
20. putpdf table tbl5(‘row’, 3), border(top) border(bottom)
21. }
22. local ++i
23. }
. putpdf save example, replace
successfully created "C:/mypath/example.pdf"
Aside from estimation results and summary statistics, you may want to export images to a PDF file.
Images can be exported simply by appending them to an active paragraph or by inserting them in a
table. The same formatting options are available regardless of how you export an image. Of course,
when inserting an image in a table, the size is constrained to the dimensions of the given cell.
Now we want to add those four plots into the document, requiring that the margins plots for
bmi=10 and bmi=20 lay side by side on top of the other two side-by-side margins plots for bmi=30
and bmi=40. It is also required that each plot have a subtitle indicating the level of BMI and that the
final figure have a title. This complicated layout can be accomplished using putpdf table.
We create a new active document with a 4 × 2 table and remove all of its borders. We caption
our table by using the note() option. In each cell on the odd rows, we add a plot. We fill each cell
on the even rows with the title corresponding to the plot above it and center-align the text in the cell.
. putpdf begin
. putpdf table tbl6 = (4,2), border(all,nil)
> note(Figure 1: Predictive margins of agegrp)
. putpdf table tbl6(1,1)=image(bmi10.png)
. putpdf table tbl6(2,1)=("(a) bmi=10"), halign(center)
. putpdf table tbl6(1,2)=image(bmi20.png)
. putpdf table tbl6(2,2)=("(b) bmi=20"), halign(center)
. putpdf table tbl6(3,1)=image(bmi30.png)
. putpdf table tbl6(4,1)=("(c) bmi=30"), halign(center)
. putpdf table tbl6(3,2)=image(bmi40.png)
. putpdf table tbl6(4,2)=("(d) bmi=40"), halign(center)
We formatted our table and the cell contents as we added content to the document. However, we
would also like to format the caption. The note() option adds an additional row at the end of the
table that spans all the columns of the table. We can format the text of the note by specifying the
last row (in this case, 5) and either . or 1 as the column index. Here, we center-align and bold the
text of the caption. Because note text is always placed within a single merged cell, it does not matter
how short or long the text is when you identify the cell location.
. putpdf table tbl6(5,.), halign(center) bold
. putpdf save example, replace
successfully created "C:/mypath/example.pdf"
putpdf table — Add tables to a PDF file 19
Stored results
putdpdf describe tablename stores the following in r():
Scalars
r(nrows) number of rows in the table
r(ncols) number of columns in the table
Reference
McDowell, A., A. Engel, J. T. Massey, and K. Maurer. 1981. Plan and operation of the Second National Health and
Nutrition Examination Survey, 1976–1980. Vital and Health Statistics 1(15): 1–144.
20 putpdf table — Add tables to a PDF file
Also see
[RPT] putpdf intro — Introduction to generating PDF files
[RPT] putpdf begin — Create a PDF file
[RPT] putpdf pagebreak — Add breaks to a PDF file
[RPT] putpdf paragraph — Add text or images to a PDF file
[RPT] Appendix for putpdf — Appendix for putpdf entries