signintech / gopdf

A simple library for generating PDF written in Go lang
MIT License
2.45k stars 269 forks source link

Create paragraph #75

Open amanbolat opened 6 years ago

amanbolat commented 6 years ago

Any idea how to create paragraphs? Or should i use my own algorithm to write text line by line?

charleswklau commented 6 years ago

I have same issue towards the paragraph. I have used CellWithOption, with fixed width & height "Rect", and the CellOption. If the required text is very long, the result "text" keeps in same line, and the remaining text displays outside the Rectangle area. Are there any paragraphs approach?

eprovst commented 6 years ago

As far as I know there is no build in functionality for paragraphs in GoPdf (you're usually better of writing your own algorithm anyway). However here's something you could use to have something working to kick start development 🙂 (do note that this example ignores all, potential, errors...)

package main

import (
    "strings"

    findfont "github.com/flopp/go-findfont"
    wordwrap "github.com/mitchellh/go-wordwrap"
    "github.com/signintech/gopdf"
)

const fontHeight = 11
const lineHeight = fontHeight * 1.2

func writeParagraph(pdf *gopdf.GoPdf, text string, width uint) error {
    wrappedtext := wordwrap.WrapString(text, width)
    lines := strings.Split(wrappedtext, "\n")

    for _, line := range lines {
        err := (*pdf).Cell(nil, line)

        if err != nil {
            return err
        }

        (*pdf).Br(lineHeight)
    }

    return nil
}

func main() {
    pdf := gopdf.GoPdf{}
    pdf.Start(gopdf.Config{
        PageSize: gopdf.Rect{W: 595.28, H: 841.89},
    })

    pathToFont, _ := findfont.Find("Courier Prime")
    pdf.AddTTFFont("courierprime", pathToFont)
    pdf.SetFont("courierprime", "", fontHeight)

    pdf.AddPage()
    writeParagraph(&pdf, "This is a rather long text about nothing in particular...", 15)

    pdf.WritePdf("test.pdf")
}
renjunok commented 4 years ago

use pdf.SplitText method.

https://github.com/signintech/gopdf/pull/121

vantaboard commented 3 weeks ago

@oneplus1000 can you close this issue if it has been resolved?