gofpdi

package module
v1.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2022 License: MIT Imports: 14 Imported by: 1

README

gofpdi

MIT licensed Report GoDoc

Go Free PDF Document Importer

gofpdi allows you to import an existing PDF into a new PDF. The following PDF generation libraries are supported:

Acknowledgments

This package’s code is derived from the fpdi library created by Jan Slabon. mrtsbt added support for reading a PDF from an io.ReadSeeker stream and also added support for using gofpdi concurrently. Asher Tuggle added support for reading PDFs that have split xref tables.

Examples

gopdf example
package main

import (
        "github.com/signintech/gopdf"
        "io"
        "net/http"
        "os"
)

func main() {
        var err error

        // Download a Font
        fontUrl := "https://github.com/google/fonts/raw/master/ofl/daysone/DaysOne-Regular.ttf"
        if err = DownloadFile("example-font.ttf", fontUrl); err != nil {
                panic(err)
        }

        // Download a PDF
        fileUrl := "https://tcpdf.org/files/examples/example_012.pdf"
        if err = DownloadFile("example-pdf.pdf", fileUrl); err != nil {
                panic(err)
        }

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

        pdf.AddPage()

        err = pdf.AddTTFFont("daysone", "example-font.ttf")
        if err != nil {
                panic(err)
        }

        err = pdf.SetFont("daysone", "", 20)
        if err != nil {
                panic(err)
        }

        // Color the page
        pdf.SetLineWidth(0.1)
        pdf.SetFillColor(124, 252, 0) //setup fill color
        pdf.RectFromUpperLeftWithStyle(50, 100, 400, 600, "FD")
        pdf.SetFillColor(0, 0, 0)

        pdf.SetX(50)
        pdf.SetY(50)
        pdf.Cell(nil, "Import existing PDF into GoPDF Document")

        // Import page 1
        tpl1 := pdf.ImportPage("example-pdf.pdf", 1, "/MediaBox")

        // Draw pdf onto page
        pdf.UseImportedTemplate(tpl1, 50, 100, 400, 0)

        pdf.WritePdf("example.pdf")

}

// DownloadFile will download a url to a local file. It's efficient because it will
// write as it downloads and not load the whole file into memory.
func DownloadFile(filepath string, url string) error {
        // Get the data
        resp, err := http.Get(url)
        if err != nil {
                return err
        }
        defer resp.Body.Close()

        // Create the file
        out, err := os.Create(filepath)
        if err != nil {
                return err
        }
        defer out.Close()

        // Write the body to file
        _, err = io.Copy(out, resp.Body)
        return err
}

Generated PDF: example.pdf

Screenshot of PDF:

example

gofpdf example #1 - import PDF from file
package main

import (
	"github.com/phpdave11/gofpdf"
	"github.com/phpdave11/gofpdf/contrib/gofpdi"
	"io"
	"net/http"
	"os"
)

func main() {
	var err error

	pdf := gofpdf.New("P", "mm", "A4", "")

	// Download a PDF
	fileUrl := "https://tcpdf.org/files/examples/example_026.pdf"
	if err = DownloadFile("example-pdf.pdf", fileUrl); err != nil {
		panic(err)
	}

	// Import example-pdf.pdf with gofpdi free pdf document importer
	tpl1 := gofpdi.ImportPage(pdf, "example-pdf.pdf", 1, "/MediaBox")

	pdf.AddPage()

	pdf.SetFillColor(200, 700, 220)
	pdf.Rect(20, 50, 150, 215, "F")

	// Draw imported template onto page
	gofpdi.UseImportedTemplate(pdf, tpl1, 20, 50, 150, 0)

	pdf.SetFont("Helvetica", "", 20)
	pdf.Cell(0, 0, "Import existing PDF into gofpdf document with gofpdi")

	err = pdf.OutputFileAndClose("example.pdf")
	if err != nil {
		panic(err)
	}
}

// DownloadFile will download a url to a local file. It's efficient because it will
// write as it downloads and not load the whole file into memory.
func DownloadFile(filepath string, url string) error {
	// Get the data
	resp, err := http.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	// Create the file
	out, err := os.Create(filepath)
	if err != nil {
		return err
	}
	defer out.Close()

	// Write the body to file
	_, err = io.Copy(out, resp.Body)
	return err
}

Generated PDF: example.pdf

Screenshot of PDF: example

gofpdf example #2 - import PDF from stream
package main

import (
    "bytes"
    "github.com/phpdave11/gofpdf"
    "github.com/phpdave11/gofpdf/contrib/gofpdi"
    "io"
    "io/ioutil"
    "net/http"
)

func main() {
    var err error

    pdf := gofpdf.New("P", "mm", "A4", "")

    // Download a PDF into memory                                                                                                                     
    res, err := http.Get("https://tcpdf.org/files/examples/example_038.pdf")
    if err != nil {
        panic(err)
    }
    pdfBytes, err := ioutil.ReadAll(res.Body)
    res.Body.Close()
    if err != nil {
        panic(err)
    }

    // convert []byte to io.ReadSeeker                                                                                                                
    rs := io.ReadSeeker(bytes.NewReader(pdfBytes))

    // Import in-memory PDF stream with gofpdi free pdf document importer                                                                             
    tpl1 := gofpdi.ImportPageFromStream(pdf, &rs, 1, "/TrimBox")

    pdf.AddPage()

    pdf.SetFillColor(200, 700, 220)
    pdf.Rect(20, 50, 150, 215, "F")

    // Draw imported template onto page                                                                                                               
    gofpdi.UseImportedTemplate(pdf, tpl1, 20, 50, 150, 0)

    pdf.SetFont("Helvetica", "", 20)
    pdf.Cell(0, 0, "Import PDF stream into gofpdf document with gofpdi")

    err = pdf.OutputFileAndClose("example.pdf")
    if err != nil {
        panic(err)
    }
}

Generated PDF:

example.pdf

Screenshot of PDF:

example.jpg

Documentation

Index

Constants

View Source
const (
	PDF_TYPE_NULL = iota
	PDF_TYPE_NUMERIC
	PDF_TYPE_TOKEN
	PDF_TYPE_HEX
	PDF_TYPE_STRING
	PDF_TYPE_DICTIONARY
	PDF_TYPE_ARRAY
	PDF_TYPE_OBJDEC
	PDF_TYPE_OBJREF
	PDF_TYPE_OBJECT
	PDF_TYPE_STREAM
	PDF_TYPE_BOOLEAN
	PDF_TYPE_REAL
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Importer

type Importer struct {
	// contains filtered or unexported fields
}

The Importer class to be used by a pdf generation library

func NewImporter

func NewImporter() *Importer

func (*Importer) GetImportedObjHashPos

func (this *Importer) GetImportedObjHashPos() map[string]map[int]string

Get the positions of the hashes (sha1 - 40 characters) within each object, to be replaced with actual objects ids by the pdf generator library

func (*Importer) GetImportedObjects

func (this *Importer) GetImportedObjects() map[int]string

Get object ids (int) and their contents (string)

func (*Importer) GetImportedObjectsUnordered

func (this *Importer) GetImportedObjectsUnordered() map[string][]byte

Get object ids (sha1 hash) and their contents ([]byte) The contents may have references to other object hashes which will need to be replaced by the pdf generator library The positions of the hashes (sha1 - 40 characters) can be obtained by calling GetImportedObjHashPos()

func (*Importer) GetNumPages

func (this *Importer) GetNumPages() int

func (*Importer) GetPageSizes

func (this *Importer) GetPageSizes() map[int]map[string]map[string]float64

func (*Importer) GetReader

func (this *Importer) GetReader() *PdfReader

func (*Importer) GetReaderForFile

func (this *Importer) GetReaderForFile(file string) *PdfReader

func (*Importer) GetWriter

func (this *Importer) GetWriter() *PdfWriter

func (*Importer) GetWriterForFile

func (this *Importer) GetWriterForFile(file string) *PdfWriter

func (*Importer) ImportPage

func (this *Importer) ImportPage(pageno int, box string) int

func (*Importer) PutFormXobjects

func (this *Importer) PutFormXobjects() map[string]int

Put form xobjects and get back a map of template names (e.g. /GOFPDITPL1) and their object ids (int)

func (*Importer) PutFormXobjectsUnordered

func (this *Importer) PutFormXobjectsUnordered() map[string]string

Put form xobjects and get back a map of template names (e.g. /GOFPDITPL1) and their object ids (sha1 hash)

func (*Importer) SetNextObjectID

func (this *Importer) SetNextObjectID(objId int)

func (*Importer) SetSourceFile

func (this *Importer) SetSourceFile(f string)

func (*Importer) SetSourceStream

func (this *Importer) SetSourceStream(rs *io.ReadSeeker)

func (*Importer) UseTemplate

func (this *Importer) UseTemplate(tplid int, _x float64, _y float64, _w float64, _h float64) (string, float64, float64, float64, float64)

For a given template id (returned from ImportPage), get the template name (e.g. /GOFPDITPL1) and the 4 float64 values necessary to draw the template a x,y for a given width and height.

type PdfObject

type PdfObject struct {
	// contains filtered or unexported fields
}

type PdfObjectId

type PdfObjectId struct {
	// contains filtered or unexported fields
}

type PdfReader

type PdfReader struct {
	// contains filtered or unexported fields
}

func NewPdfReader

func NewPdfReader(filename string) (*PdfReader, error)

func NewPdfReaderFromStream

func NewPdfReaderFromStream(rs io.ReadSeeker) (*PdfReader, error)

type PdfTemplate

type PdfTemplate struct {
	Id        int
	Reader    *PdfReader
	Resources *PdfValue
	Buffer    string
	Box       map[string]float64
	Boxes     map[string]map[string]float64
	X         float64
	Y         float64
	W         float64
	H         float64
	Rotation  int
	N         int
}

Done with parsing. Now, create templates.

type PdfValue

type PdfValue struct {
	Type       int
	String     string
	Token      string
	Int        int
	Real       float64
	Bool       bool
	Dictionary map[string]*PdfValue
	Array      []*PdfValue
	Id         int
	NewId      int
	Gen        int
	Value      *PdfValue
	Stream     *PdfValue
	Bytes      []byte
}

type PdfWriter

type PdfWriter struct {
	// contains filtered or unexported fields
}

func NewPdfWriter

func NewPdfWriter(filename string) (*PdfWriter, error)

func (*PdfWriter) ClearImportedObjects

func (this *PdfWriter) ClearImportedObjects()

func (*PdfWriter) CloseWriter added in v1.0.2

func (this *PdfWriter) CloseWriter()

func (*PdfWriter) GetImportedObjHashPos

func (this *PdfWriter) GetImportedObjHashPos() map[*PdfObjectId]map[int]string

For each object (uniquely identified by a sha1 hash), return the positions of each hash within the object, to be replaced with pdf object ids (integers)

func (*PdfWriter) GetImportedObjects

func (this *PdfWriter) GetImportedObjects() map[*PdfObjectId][]byte

func (*PdfWriter) ImportPage

func (this *PdfWriter) ImportPage(reader *PdfReader, pageno int, boxName string) (int, error)

Create a PdfTemplate object from a page number (e.g. 1) and a boxName (e.g. MediaBox)

func (*PdfWriter) Init

func (this *PdfWriter) Init()

func (*PdfWriter) PutFormXobjects

func (this *PdfWriter) PutFormXobjects(reader *PdfReader) (map[string]*PdfObjectId, error)

Output Form XObjects (1 for each template) returns a map of template names (e.g. /GOFPDITPL1) to PdfObjectId

func (*PdfWriter) SetNextObjectID

func (this *PdfWriter) SetNextObjectID(id int)

func (*PdfWriter) SetTplIdOffset

func (this *PdfWriter) SetTplIdOffset(n int)

func (*PdfWriter) SetUseHash

func (this *PdfWriter) SetUseHash(b bool)

func (*PdfWriter) UseTemplate

func (this *PdfWriter) UseTemplate(tplid int, _x float64, _y float64, _w float64, _h float64) (string, float64, float64, float64, float64)

type TplInfo

type TplInfo struct {
	SourceFile string
	Writer     *PdfWriter
	TemplateId int
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL