dongweihuai5601 2019-05-14 06:49
浏览 157
已采纳

如何通过gopdf将文本数据打印为pdf?

What I tried:

var data string
data = "Line1 <br>
" +
       "Line2 
" +
       "Line3 
" +
       "Line4" // It's got from DB which saved by br data.

pdf.SetFont("wts11", "", 14)
pdf.SetX(100)
pdf.SetY(200)
pdf.Text(data)

Result:

The pdf shows:

enter image description here

And all other printed data disappeared.

Maybe it can't parse <br>.

Even change pdf.Text(data) to pdf.Cell(nil, text), also the same result.

Ref:

https://github.com/signintech/gopdf

Similar issue:

https://github.com/signintech/gopdf/issues/78

  • 写回答

1条回答 默认 最新

  • dongluxin2452 2019-05-14 10:35
    关注

    Do not skip error handling, that's why you don't see what is the reason of failure.

    Please add err check to SetFont, Text, WritePdf functions. In my case I found that error was coming from SetFont since it was not found.

    This code works well if you have open-sans.ttf in your working dir:

    package main
    
    import (
        "log"
    
        "github.com/signintech/gopdf"
    )
    
    func main() {
        pdf := gopdf.GoPdf{}
        pdf.Start(gopdf.Config{PageSize: *gopdf.PageSizeA4})
        pdf.AddPage()
    
        if err := pdf.AddTTFFont("open-sans", "open-sans.ttf"); err != nil {
            log.Print(err.Error())
            return
        }
    
        if err := pdf.SetFont("open-sans", "", 14); err != nil {
            log.Print(err.Error())
            return
        }
    
        pdf.SetX(100)
        pdf.SetY(200)
    
        data := "Line1 <br/>
    " +
            "Line2 
    " +
            "Line3 
    " +
            "Line4"
    
        if err := pdf.Text(data); err != nil {
            log.Print(err.Error())
            return
        }
    
        if err := pdf.WritePdf("hello.pdf"); err != nil {
            log.Print(err.Error())
            return
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 AttributeError: 'EasyDict' object has no attribute 'BACKUP_DB_INFO'
  • ¥15 想用octave解决这个数学问题
  • ¥15 Centos新建的临时ip无法上网,如何解决?
  • ¥15 海康威视如何实现客户端软件对设备语音请求的处理。
  • ¥15 支付宝h5参数如何实现跳转
  • ¥15 MATLAB代码补全插值
  • ¥15 Typegoose 中如何使用 arrayFilters 筛选并更新深度嵌套的子文档数组信息
  • ¥15 前后端分离的学习疑问?
  • ¥15 stata实证代码答疑
  • ¥50 husky+jaco2实现在gazebo与rviz中联合仿真