summaryrefslogtreecommitdiff
path: root/pdf.go
diff options
context:
space:
mode:
authorNick White <git@njw.name>2021-08-17 13:39:09 +0100
committerNick White <git@njw.name>2021-08-17 13:39:09 +0100
commit767b60db23311adaf1035e821bc189877d63b7f0 (patch)
tree16f20e400c2c259488622a98b71d199cad4f62e7 /pdf.go
parent48c68cfa7f18992b26765c7b67c52c11687ad74a (diff)
pdf: Stretch words to fit in their boxes, for more perfect embedding
- Words are stretched to fit their boxes, which means the accuracy is now very high indeed. This was done by modifying gofpdf to add the SetCellStretchToFit function, which will hopefully be upstreamed in due course. - Copy pasting from a PDF works well with lines rarely if ever being erroneously broken by the PDF reader. There was quite a bit of trial-and-error to improve this, and the stretched text plus a space being added after the word in CellFormat was the best (plus preserves accuracy of word and character locations).
Diffstat (limited to 'pdf.go')
-rw-r--r--pdf.go15
1 files changed, 11 insertions, 4 deletions
diff --git a/pdf.go b/pdf.go
index be7f8a9..eb5f021 100644
--- a/pdf.go
+++ b/pdf.go
@@ -16,7 +16,8 @@ import (
"io/ioutil"
"os"
- "github.com/phpdave11/gofpdf"
+ //"github.com/phpdave11/gofpdf"
+ "github.com/nickjwhite/gofpdf" // adds SetCellStretchToFit function
"golang.org/x/image/draw"
"rescribe.xyz/utils/pkg/hocr"
)
@@ -112,7 +113,7 @@ func (p *Fpdf) AddPage(imgpath, hocrpath string, smaller bool) error {
if err != nil {
continue
}
- lineheight := linecoords[3] - linecoords[1]
+ lineheight := pxToPt(linecoords[3] - linecoords[1])
for _, w := range l.Words {
coords, err := hocr.BoxCoords(w.Title)
if err != nil {
@@ -120,8 +121,14 @@ func (p *Fpdf) AddPage(imgpath, hocrpath string, smaller bool) error {
}
p.fpdf.SetXY(pxToPt(coords[0]), pxToPt(linecoords[1]))
p.fpdf.SetCellMargin(0)
- p.fpdf.SetFontSize(pxToPt(lineheight))
- p.fpdf.CellFormat(pxToPt(coords[2] - coords[0]), pxToPt(lineheight), html.UnescapeString(w.Text)+" ", "", 0, "T", false, 0, "")
+ p.fpdf.SetFontSize(lineheight)
+ cellW := pxToPt(coords[2] - coords[0])
+ cellText := html.UnescapeString(w.Text)
+ p.fpdf.SetCellStretchToFit(cellW, cellText)
+ // Adding a space after each word causes fewer line breaks to
+ // be erroneously inserted when copy pasting from the PDF, for
+ // some reason.
+ p.fpdf.CellFormat(cellW, lineheight, cellText + " ", "", 0, "T", false, 0, "")
}
}
return p.fpdf.Error()