From 767b60db23311adaf1035e821bc189877d63b7f0 Mon Sep 17 00:00:00 2001 From: Nick White Date: Tue, 17 Aug 2021 13:39:09 +0100 Subject: 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). --- pdf.go | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) (limited to 'pdf.go') 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() -- cgit v1.2.1-24-ge1ad