基本信息
文件名称:利用golang实现pdf中自动换行的表格.docx
文件大小:17.06 KB
总页数:5 页
更新时间:2025-05-21
总字数:约3.23千字
文档摘要

利用golang实现pdf中自动换行的表格

stylestring//风格F仅填充D仅边框或者DF两个都要

alignStrstring//对其方式LCR为水平的左、中、右,TMBA为垂直的上、中、下、基准线

fontHfloat64//字体高度

cells[]pdfCell//

typepdfCellstruct{

wfloat64//宽度

hfloat64//行高

txtStrstring//文本

linesint//判断文本会占几行

func(s*pdfLine)addLine(stylestring,alignStrstring,cells...pdfCell){

s.style=style

s.alignStr=alignStr

_,s.fontH=s.pdf.GetFontSize()

//记录需要的最高行高

for_,cell:=rangecells{

lines:=s.pdf.SplitText(cell.txtStr,cell.w)

h:=float64(len(lines))*cell.h

ifs.hh{

s.h=h

cell.lines=len(lines)

s.cells=append(s.cells,cell)

_,_,_,mbottom:=s.pdf.GetMargins()//获取当前页面边距

_,pageh:=s.pdf.GetPageSize()//获取当前页面尺寸

x,y:=s.pdf.GetXY()//获取当前位置

//页面剩余行高不够时开启新一页

ifs.pdf.GetY()+s.hpageh-mbottom{

s.pdf.AddPage()

y=s.pdf.GetY()

s.x=x

s.y=y

s.write()

//写入

func(s*pdfLine)write(){

x:=s.x

y:=s.y

//手动记录并移动坐标

for_,c:=ranges.cells{

usedH:=float64(c.lines)*s.fontH

margin:=(s.h-usedH)/2.0

s.pdf.Rect(x,s.y,c.w,s.h,s.style)

s.pdf.SetXY(x,y+margin)//保持单元格内的文字有边距

s.pdf.MultiCell(c.w,s.fontH,c.txtStr,,s.alignStr,false)

x+=c.w

s.pdf.SetXY(x,y)

//坐标重置为下一行的当前位置

s.pdf.SetXY(s.x,s.y+s.h)

//重置变量

s.cells=nil

s.h=0

//使用生成一个每行4列的表格

funcmain(){

pdf:=gofpdf.New(P,mm,A4,)

pdf.AddPage()

pdf.AddUTF8Font(NotoSansSC-Regular,,src/font/NotoSansSC-Regular.ttf)

pdf.SetFont(NotoSansSC-Regular,,12)

myPdf:=pdfLine{pdf:pdf}

width,_:=pdf.GetPageSize()//页面宽度

left,_,right,_:=pdf.GetMargins()//左右边距

usable:=width-left-right//可用的页面宽度

_,h:=pdf.GetFontSize()//字体高度

tableH:=h+2//行高多出2mm的边距

tableWidth:=usable/4//每个单元个的宽度

pdf.SetFillColor(233,233,233)

//表头

myPdf.addLine(FD,CM,[]pdfCell{

{w:tableWidth,h:tableH,txtStr:表头1},

{w:tableWidth,h:tableH