Git Product home page Git Product logo

gofpdf's Introduction

GoFPDF document generator

No Maintenance Intended MIT licensed GoDoc

Package gofpdf implements a PDF document generator with high level support for text, drawing and images.

Features

  • UTF-8 support
  • Choice of measurement unit, page format and margins
  • Page header and footer management
  • Automatic page breaks, line breaks, and text justification
  • Inclusion of JPEG, PNG, GIF, TIFF and basic path-only SVG images
  • Colors, gradients and alpha channel transparency
  • Outline bookmarks
  • Internal and external links
  • TrueType, Type1 and encoding support
  • Page compression
  • Lines, Bézier curves, arcs, and ellipses
  • Rotation, scaling, skewing, translation, and mirroring
  • Clipping
  • Document protection
  • Layers
  • Templates
  • Barcodes
  • Charting facility
  • Import PDFs as templates

gofpdf has no dependencies other than the Go standard library. All tests pass on Linux, Mac and Windows platforms.

gofpdf supports UTF-8 TrueType fonts and “right-to-left” languages. Note that Chinese, Japanese, and Korean characters may not be included in many general purpose fonts. For these languages, a specialized font (for example, NotoSansSC for simplified Chinese) can be used.

Also, support is provided to automatically translate UTF-8 runes to code page encodings for languages that have fewer than 256 glyphs.

We Are Closed

This repository will not be maintained, at least for some unknown duration. But it is hoped that gofpdf has a bright future in the open source world. Due to Go’s promise of compatibility, gofpdf should continue to function without modification for a longer time than would be the case with many other languages.

Forks should be based on the last viable commit. Tools such as active-forks can be used to select a fork that looks promising for your needs. If a particular fork looks like it has taken the lead in attracting followers, this README will be updated to point people in that direction.

The efforts of all contributors to this project have been deeply appreciated. Best wishes to all of you.

Installation

To install the package on your system, run

go get github.com/jung-kurt/gofpdf

Later, to receive updates, run

go get -u -v github.com/jung-kurt/gofpdf/...

Quick Start

The following Go code generates a simple PDF file.

pdf := gofpdf.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.SetFont("Arial", "B", 16)
pdf.Cell(40, 10, "Hello, world")
err := pdf.OutputFileAndClose("hello.pdf")

See the functions in the fpdf_test.go file (shown as examples in this documentation) for more advanced PDF examples.

Errors

If an error occurs in an Fpdf method, an internal error field is set. After this occurs, Fpdf method calls typically return without performing any operations and the error state is retained. This error management scheme facilitates PDF generation since individual method calls do not need to be examined for failure; it is generally sufficient to wait until after Output() is called. For the same reason, if an error occurs in the calling application during PDF generation, it may be desirable for the application to transfer the error to the Fpdf instance by calling the SetError() method or the SetErrorf() method. At any time during the life cycle of the Fpdf instance, the error state can be determined with a call to Ok() or Err(). The error itself can be retrieved with a call to Error().

Conversion Notes

This package is a relatively straightforward translation from the original FPDF library written in PHP (despite the caveat in the introduction to Effective Go). The API names have been retained even though the Go idiom would suggest otherwise (for example, pdf.GetX() is used rather than simply pdf.X()). The similarity of the two libraries makes the original FPDF website a good source of information. It includes a forum and FAQ.

However, some internal changes have been made. Page content is built up using buffers (of type bytes.Buffer) rather than repeated string concatenation. Errors are handled as explained above rather than panicking. Output is generated through an interface of type io.Writer or io.WriteCloser. A number of the original PHP methods behave differently based on the type of the arguments that are passed to them; in these cases additional methods have been exported to provide similar functionality. Font definition files are produced in JSON rather than PHP.

Example PDFs

A side effect of running go test ./... is the production of a number of example PDFs. These can be found in the gofpdf/pdf directory after the tests complete.

Please note that these examples run in the context of a test. In order run an example as a standalone application, you’ll need to examine fpdf_test.go for some helper routines, for example exampleFilename() and summary().

Example PDFs can be compared with reference copies in order to verify that they have been generated as expected. This comparison will be performed if a PDF with the same name as the example PDF is placed in the gofpdf/pdf/reference directory and if the third argument to ComparePDFFiles() in internal/example/example.go is true. (By default it is false.) The routine that summarizes an example will look for this file and, if found, will call ComparePDFFiles() to check the example PDF for equality with its reference PDF. If differences exist between the two files they will be printed to standard output and the test will fail. If the reference file is missing, the comparison is considered to succeed. In order to successfully compare two PDFs, the placement of internal resources must be consistent and the internal creation timestamps must be the same. To do this, the methods SetCatalogSort() and SetCreationDate() need to be called for both files. This is done automatically for all examples.

Nonstandard Fonts

Nothing special is required to use the standard PDF fonts (courier, helvetica, times, zapfdingbats) in your documents other than calling SetFont().

You should use AddUTF8Font() or AddUTF8FontFromBytes() to add a TrueType UTF-8 encoded font. Use RTL() and LTR() methods switch between “right-to-left” and “left-to-right” mode.

In order to use a different non-UTF-8 TrueType or Type1 font, you will need to generate a font definition file and, if the font will be embedded into PDFs, a compressed version of the font file. This is done by calling the MakeFont function or using the included makefont command line utility. To create the utility, cd into the makefont subdirectory and run “go build”. This will produce a standalone executable named makefont. Select the appropriate encoding file from the font subdirectory and run the command as in the following example.

./makefont --embed --enc=../font/cp1252.map --dst=../font ../font/calligra.ttf

In your PDF generation code, call AddFont() to load the font and, as with the standard fonts, SetFont() to begin using it. Most examples, including the package example, demonstrate this method. Good sources of free, open-source fonts include Google Fonts and DejaVu Fonts.

Related Packages

The draw2d package is a two dimensional vector graphics library that can generate output in different forms. It uses gofpdf for its document production mode.

Contributing Changes

gofpdf is a global community effort and you are invited to make it even better. If you have implemented a new feature or corrected a problem, please consider contributing your change to the project. A contribution that does not directly pertain to the core functionality of gofpdf should be placed in its own directory directly beneath the contrib directory.

Here are guidelines for making submissions. Your change should

  • be compatible with the MIT License
  • be properly documented
  • be formatted with go fmt
  • include an example in fpdf_test.go if appropriate
  • conform to the standards of golint and go vet, that is, golint . and go vet . should not generate any warnings
  • not diminish test coverage

Pull requests are the preferred means of accepting your changes.

License

gofpdf is released under the MIT License. It is copyrighted by Kurt Jung and the contributors acknowledged below.

Acknowledgments

This package’s code and documentation are closely derived from the FPDF library created by Olivier Plathey, and a number of font and image resources are copied directly from it. Bruno Michel has provided valuable assistance with the code. Drawing support is adapted from the FPDF geometric figures script by David Hernández Sanz. Transparency support is adapted from the FPDF transparency script by Martin Hall-May. Support for gradients and clipping is adapted from FPDF scripts by Andreas Würmser. Support for outline bookmarks is adapted from Olivier Plathey by Manuel Cornes. Layer support is adapted from Olivier Plathey. Support for transformations is adapted from the FPDF transformation script by Moritz Wagner and Andreas Würmser. PDF protection is adapted from the work of Klemen Vodopivec for the FPDF product. Lawrence Kesteloot provided code to allow an image’s extent to be determined prior to placement. Support for vertical alignment within a cell was provided by Stefan Schroeder. Ivan Daniluk generalized the font and image loading code to use the Reader interface while maintaining backward compatibility. Anthony Starks provided code for the Polygon function. Robert Lillack provided the Beziergon function and corrected some naming issues with the internal curve function. Claudio Felber provided implementations for dashed line drawing and generalized font loading. Stani Michiels provided support for multi-segment path drawing with smooth line joins, line join styles, enhanced fill modes, and has helped greatly with package presentation and tests. Templating is adapted by Marcus Downing from the FPDF_Tpl library created by Jan Slabon and Setasign. Jelmer Snoeck contributed packages that generate a variety of barcodes and help with registering images on the web. Jelmer Snoek and Guillermo Pascual augmented the basic HTML functionality with aligned text. Kent Quirk implemented backwards-compatible support for reading DPI from images that support it, and for setting DPI manually and then having it properly taken into account when calculating image size. Paulo Coutinho provided support for static embedded fonts. Dan Meyers added support for embedded JavaScript. David Fish added a generic alias-replacement function to enable, among other things, table of contents functionality. Andy Bakun identified and corrected a problem in which the internal catalogs were not sorted stably. Paul Montag added encoding and decoding functionality for templates, including images that are embedded in templates; this allows templates to be stored independently of gofpdf. Paul also added support for page boxes used in printing PDF documents. Wojciech Matusiak added supported for word spacing. Artem Korotkiy added support of UTF-8 fonts. Dave Barnes added support for imported objects and templates. Brigham Thompson added support for rounded rectangles. Joe Westcott added underline functionality and optimized image storage. Benoit KUGLER contributed support for rectangles with corners of unequal radius, modification times, and for file attachments and annotations.

Roadmap

  • Remove all legacy code page font support; use UTF-8 exclusively
  • Improve test coverage as reported by the coverage tool.

gofpdf's People

Contributors

aleksi avatar benoitkugler avatar claudiofelber avatar d1ngd0 avatar danmeyers avatar darkfreedman avatar darrenmcc avatar divan avatar echa avatar eiskasten avatar flibustenet avatar hypertornado avatar hyzgh avatar jacobalberty avatar jelmersnoeck avatar joewestcott avatar jung-kurt avatar marcus-downing avatar moogle19 avatar mrtsbt avatar nickjwhite avatar olegfx avatar phpdave11 avatar rubenn avatar ruudk avatar sbinet avatar seletskiy avatar slomek avatar stanim avatar wmatusiak avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gofpdf's Issues

Render PDFs to bitmaps?

It doesn't appear that gofpdf includes FPDF's ability to render a PDF file to a bitmap. Am I missing something in that regard? I'm looking for something to open a PDF file, grab the first page, and generate a PNG it (via image.png.Encode()).

Font embedding

I would like to create a Go binary with embedded font files (.json and .z). I will do this by appending a ZIP file containing all the required files to the Go generated binary. So far so good. In order to be able to use these embedded font files with gofpdf I would like to have it accept readers for both .json and .z files. Currently it only supports loading the .json font file from an io.Reader using AddFontFromReader. The actual font data (.z) is then loaded using the file system call. This makes AddFontFromReader effectively useless.

In order to support font files embedded into the executable (or maybe reading them from a ZIP file) I would propose to add a SetFontOpener(opener FontOpener) method to the Fpdf struct where FontOpener is an interface defined as follows:

type FontOpener interface {
    Open(name string) io.Reader, error
}

The Open method could then be called to get readers for both the .json and .z font files. In order to keep the interface as non-restrictive as possible I defined it to return an io.Reader instead of an io.ReaderCloser. Nevertheless you could close closeable readers in your code using the following fragment:

reader, err := f.opener.Open(fontFile)
…

if closer, ok := reader.(io.Closer); ok {
    closer.Close()
}

html basic without any tag

Is it normal that nothing is printed without any tag when I'm calling the html method?

pdf := gofpdf.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.SetFont("Times", "", 13)
_, lineHt := pdf.GetFontSize()
html := pdf.HTMLBasicNew()
html.Write(lineHt, "<>first</>")
html.Write(lineHt, "second")
if e := pdf.OutputFileAndClose("./p.pdf"); e != nil {
    log.Fatal(e)
}

It results in printing first but not second.

Support for variable image dpi needs work

Trying to right-justify an image -- even if you know its dpi -- is a bit of work. The imginfo.Extent() and related functions assume that the image is 72 dpi.

Here's what I had to do:

    imginfo := pdf.RegisterImage(imgname, "")
    imgdpi := float64(288)
    widthInPixels := pdf.UnitToPointConvert(imginfo.Width())
    w := widthInPixels * pdf.PointToUnitConvert(72/imgdpi)
    pgw, _ := pdf.GetPageSize()
    lm, _, rm, _ := pdf.GetMargins()
    imgpos := pgw - lm - rm - w
    pdf.Image(imgname, imgpos, 0, -imgdpi, -imgdpi, true, "", 0, "")

The easiest fix I can see (since the Go image routines don't provide dpi info) would be to provide an imginfo.DpiExtent function that takes dpi as a parameter.

A better fix would be to allow setting DPI on an image and having it taken into account. Perhaps imginfo could grow a dpi field, it could be set to 72 by default, but if you override it, it would get taken into account.

I'd be willing to submit a PR with a fix, but I'd like to know what sort of fix you'd approve before I do it, please.

Multicell same height on the row

I'm having problems with building a table row.

It can happend that a first column in a row has height of 40, and the second column in the same row gets larger because text is too large.

Because of that i get unaligned borders..
Is it possible to somehow define row border?

Connect tutorials better with methods

As the number of tutorials are growing, it gets hard to quickly look up some example code. Now you first have to find a relevant function, read the tutorial number and scroll back. It would maybe more efficient to have some keywords in the title instead of just a number.

So instead of:

  • ExampleFpdf_tutorial31

it could be:

  • ExampleFpdf_tutorial31_line_caps_join_style (does not give golint error)
  • ExampleFpdf_tutorial31LineCapsJoinStyle
  • ExampleFpdf_31_line_caps_join_style (does not give golint error)
  • ExampleFpdf_31LineCapsJoinStyle

Changing Fonts in mid-line

Am currently handling this this way:
// Current Weight
pdf.SetFont("Helvetica", "B", 11)
pdf.CellFormat(1.8, 0, "4. Current Weight: ", "", 0, "L", false, 0, "")
pdf.SetFont("Helvetica", "", 11)
pdf.CellFormat(PDF_INTERNAL_WIDTH/4, 0, ""+CurrentWeight, "", 1, "LM", false, 0, "")
pdf.Ln(.2)
Is there some thing I am missing that would reduce the amount of code?
Thanks,
Jim

Render PDF

Can I render PDF on server (render stream output) not write to disk, and not forced to download?

Encoding file for fonts

From GoDoc:

encodingFileStr is the name of the encoding file that corresponds to the font

What is an encoding file? If I use a Google Fonts font, how do I find its encoding file?

How to find the baseline of a font?

GetFontSize returns the total height of the text (from Desc to Asc in picture below), but I need to know the baseline. For example in the text "go" I'd like to know how to calculate the bottom of the "o", not of the "g", is this possible (base in picture below)? I have the feeling this info could be parsed somewhere in the getInfoFrom* functions in font.go.

baseline

cyrillic text in pdf

Hello! I need to create cyrillic text in pdf but example found in docs not working. Here is code

package main

import (
    "github.com/jung-kurt/gofpdf"
    "fmt"
    "os"
)

func main() {
    pwd, err := os.Getwd()
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    pdf := gofpdf.New("P", "mm", "A4", "")
    pdf.AddFont("Helvetica", "", pwd + "/font/helvetica_1251.json")
    pdf.AddPage()
    pdf.SetFont("Helvetica", "", 16)
    tr := pdf.UnicodeTranslatorFromDescriptor("cp1251")
    pdf.Cell(15, 50, tr("русский текст"))
    pdf.OutputFileAndClose("test.pdf")
}

I receive only dots.

inlined multiple MultiCell

how to draw MultiCell side by side?
when i set width as 60 for both MultiCell, the second MultiCell is drawn below the first.
help?

Arial or Helvetica

You mention in the docs that Helvetica(aka arial) is this actually true? Have read that Helvetica is a likely ancestor of arial is that what you mean? Have a need to use arial as a requirement.

GetAlpha needed

For draw2d I need to be able to look up the transparency and blend mode. As in svg and bitmap drawing RGBA colors are used instead of RGB colors as in gopdf. I need to be able to check the current state, to decide if a new call to SetAlpha is necessary. This is also necessary to preserve the blendmode, if I only want to adjust the alpha. I will prepare a pull request.

Small Caps

I have a font that supports small caps but can't figure out how to use those small caps in the pdf. I tried hacking in and modifying the .json Flags property to include Small Caps flag (1 << 18) but no effect. Any Idea?

Support for non-ASCII text (Á, é, ê, Ç, ã)

Hi, I would like to know if it is possible to generate portuguese/spanish pdfs by using your library. I was trying to use a google's font that has these characters (Roboto-Regular.ttf), but it did not work

Question: Font Embedding vs. Outlines

It seems now when I use a font, the entire font gets embedded into the document. For me this can lead to large file sizes, espcially if I only use that font for a few characters. Is there an option to only render the given characters as outlines rather than embedding the entire font? Or is it already doing that?

AddFontFromReader loads definition but not font file

Hi,

Thanks for this work.

I was looking for a solution to add a custom font without having to load any files. I thought AddFontFromReader would do that, but it appears to only load the definition from a reader. As far as I can tell the library attempts to load the font itself (font.z) from the file system. As it currently stands, is there a way to supply a custom font in another way?

Problem to générate PDF

Hello,
I used "code.google.com/p/gofpdf" but it is not easy for accent char. Your package is in philosophy of Golang. For generate PDF, all text est in UTF-8.

But I see several problems in this package:

  • When I use accent char in CellFormat like "é", the char don't display correctly.
    For correct this problem I had add this line "txtStr=utf8toutf16(txtStr)" in the "fpdf.go" ( ligne 1712 ). I can't insert this line before because GetStringWidth return 0 in utf16.
  • Then the text don't display correctly:
    I have delete this line "res = append(res, 0xFE, 0xFF)" in the utf8toutf16 function because I don't be in the beginning file.

Can you check if the correction is good for you ?

Increase test coverage

Now we have a test coverage of 82%. It would be good to further increase it. Test coverage is no guarantee, just like golint, go vet, ... but it is just an automated way to increase the quality of the code and to avoid collaboration discussions. Also could we take as a condition for merging that the coverage does not decrease.

Combined words after WriteAligned merge

The example file Fpdf_SVGBasicWrite.pdf, generated by ExampleFpdf_SVGBasicWrite() in fpdf_test.go, shows some words that should be separated by a space but are not. When compression is turned off, it is evident that the spaces have been deleted from the written text so this is not a rendering issue. The example generated by checkout Merge pull request #44 is correct; the example generated from the next checkout, Fpdf: add WriteAligned, is not.

@jelmersnoeck, I have not looked into this. Can you see what might be going on?

Fix for: Templates doesn't view special characters and font's correctly

When using this package I noticed that if you change font in template, the template still uses default font style in output (Atleast when viewed on Acrobat Reader). Also encoding of special characters doesn't work.
I noticed that in output file XObject doesn't have Resource reference to declared Font objects.
(This is only recommended on PDF standard)
Fix:
On templates.go file (line: 113, function putTemplates) I just added Font resource declaration (after line 136):

  f.out("/Font <<")
  {
      var keyList []string
      var font fontDefType
      var key string
      for key = range f.fonts {
          keyList = append(keyList, key)
      }
      if f.catalogSort {
          sort.Strings(keyList)
      }
      for _, key = range keyList {
          font = f.fonts[key]
          f.outf("/F%d %d 0 R", font.I, font.N)
      }
  }
  f.out(">>")

After the "/ProcSet ..." output:

  f.out("/Resources ")
  f.out("<</ProcSet [/PDF /Text /ImageB /ImageC /ImageI]")

16-bit depth not supported in PNG file

i get this error message "16-bit depth not supported in PNG file" when trying to use a png file
any idea how should i fix this?
thank you
the image is created using golang png encoder.

Quick Start example

Not really an issue, but more a critical question. Would it be not better for an outsider to use OutputFileAndClose instead of Output? Are people not more interested in quickly generating a pdf file rather than seeing its raw data stream?

Testing: add file comparison.

At the moment, the tests validate that the code runs. It also provides a lot of examples for the users of gofpdf.

However, it doesn't test if functionality is as expected. This is particularly important when changing functionality or adding new features.

My suggestion for this would be to have a set of pre-defined PDFs (the ones that are generated through the examples now) and compare the same PDF generation instructions to those PDFs. This assures that new/changed code wouldn't change old output (unintentional).

To do this, there needs to be a change to the way the file gets parsed. At the moment, time.Now() is used to put the creation date in place. This makes it tricky to compare the file as this date always changes and thus the output will always be different.

I'm suggesting a simple Clock implementation here to make it possible to mock this out during tests.

I have made a rough version of how this could work here: https://github.com/jung-kurt/gofpdf/compare/master...jelmersnoeck:test-comparison?expand=1

Would you be open to accept this kind of system for testing output? (Note, the version above is a POC, the actual implementation will probably be a bit different)

Any support for a "shrink-to-fit"?

I was just wondering if there was any way to define a text area and a preferred font size with a shrink-to-fit option? ie. If the text doesn't fit in the box, it continues to shrink until it does?

Justify text with different fonts

I'm having problem justfying text with different fonts (some parts of text are bold, some are not)..

Is this possible? :/

Justification with a single font is not a problem

RFE: TIFF Support

is there any planning to incorporate TIFF support (G3, G4 encoding) in your project?

Thank you in advance

is .otf format supported?

tried to run makefont on the otf file
it says 'fonts based on PostScript outlines are not supported'

cell overlap

pdf.Cell(5, 10, "Hello, world")
print "Hello Word"
but i want to print only width size like "Hello "
how can i restrict string to print more then width.

Clarification about custom fonts

I'm not sure how I can add and use custom fonts:

  • why is the font .ttf file not enough?
  • where do I get a .map file for my font?
  • how to export the font so it will be "unicode-compatible"?

I'm interested in using DejaVuSansCondensed.ttf from Dejavu font distribution.

PS: the project is awesome! you've done a great work!

How to use czech language

I am trying to use gofpdf with czech language. First I exported "Arial.json" and "Arial.z" with:

./makefont --embed --enc=../font/cp1250.map --dst=/somepath /Library/Fonts/Arial.ttf

Then i use code to generate pdf:

pdf := gofpdf.New("L", "mm", "A4", "")
pdf.AddPage()
pdf.AddFont("arial", "", "/somepath/Arial.json")


pdf.SetFont("arial", "", 16)
pdf.Cell(10, 10, "Dárkový poukaz v hodnotě")

But instead of text "Dárkový poukaz v hodnotě", I got "DĂĄrkovĂ˝ poukaz v hodnotÄ�". I don't know if czech language is supported. What should I do to have czech text displayed properly?

Expose f.out

I need to write custom complex shapes to fpdf. Unfortunately these are not generally usable and would otherwise bloat the api by adding methods. Also it useful if you want to redraw multiple times a path, which was generated by a cpu intensive and long running algorithm.

So I need to write directly to the stream when fpdf is imported in another package. I'd like to see f.out exposed as e.g. f.Stream/f.Write/... with a disclaimer that is only for low level access in its docstring. If this is not possible I have to fork the package which I would like to avoid.

GetStringWidth

I am creating a tool which outputs labels. I need know the length of the input string, before I can create an appropriately sized page. Currently I am doing something like this:

label := "0123456789 GO FPDF!"
scratchPdf := gofpdf.New("L", "mm", "Legal", "/tmp")
scratchPdf.AddFont("SourceCodePro-Bold", "", "SourceCodePro-Bold.json")
scratchPdf.SetFont("SourceCodePro-Bold", "", 12)
labelWidth := scratchPdf.GetStringWidth(label)

But it seems awkward to need to create a page, just to measure the width of a string. Why is an fpdf instance required to measure a string?

Setting font size in units

SetFontSize is confusing as it uses points, where all other drawing operations use the unit size. Right now it is not straightforward to set the font size in units, as the scale factor f.k is private. It feels quite clumsy to calculate it first with eg. GetFontSize

We can't touch anymore SetFontSize for backwards compatibilty, but we could solve it in these ways:

  1. Expose f.k as a f.Unit2Point field
  2. Define a SetFontUnitSize method
  3. Define a UnitToPoint method (and maybe PointToUnit)
  4. ... (I'm open for better solutions)

I think 1 has my preference as it is more generally useful and has the least impact. I can do a pull request when an agreement is reached.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.