github.com/phpdave11/gofpdf@v1.4.2/contrib/gofpdi/gofpdi_test.go (about)

     1  package gofpdi
     2  
     3  import (
     4  	"bytes"
     5  	"github.com/phpdave11/gofpdf"
     6  	"github.com/phpdave11/gofpdf/internal/example"
     7  	"io"
     8  	"sync"
     9  	"testing"
    10  )
    11  
    12  func ExampleNewImporter() {
    13  	// create new pdf
    14  	pdf := gofpdf.New("P", "pt", "A4", "")
    15  
    16  	// for testing purposes, get an arbitrary template pdf as stream
    17  	rs, _ := getTemplatePdf()
    18  
    19  	// create a new Importer instance
    20  	imp := NewImporter()
    21  
    22  	// import first page and determine page sizes
    23  	tpl := imp.ImportPageFromStream(pdf, &rs, 1, "/MediaBox")
    24  	pageSizes := imp.GetPageSizes()
    25  	nrPages := len(imp.GetPageSizes())
    26  
    27  	// add all pages from template pdf
    28  	for i := 1; i <= nrPages; i++ {
    29  		pdf.AddPage()
    30  		if i > 1 {
    31  			tpl = imp.ImportPageFromStream(pdf, &rs, i, "/MediaBox")
    32  		}
    33  		imp.UseImportedTemplate(pdf, tpl, 0, 0, pageSizes[i]["/MediaBox"]["w"], pageSizes[i]["/MediaBox"]["h"])
    34  	}
    35  
    36  	// output
    37  	fileStr := example.Filename("contrib_gofpdi_Importer")
    38  	err := pdf.OutputFileAndClose(fileStr)
    39  	example.Summary(err, fileStr)
    40  	// Output:
    41  	// Successfully generated ../../pdf/contrib_gofpdi_Importer.pdf
    42  }
    43  
    44  func TestGofpdiConcurrent(t *testing.T) {
    45  	wg := sync.WaitGroup{}
    46  	for i := 0; i < 100; i++ {
    47  		wg.Add(1)
    48  		go func() {
    49  			defer wg.Done()
    50  			pdf := gofpdf.New("P", "mm", "A4", "")
    51  			pdf.AddPage()
    52  			rs, _ := getTemplatePdf()
    53  			imp := NewImporter()
    54  			tpl := imp.ImportPageFromStream(pdf, &rs, 1, "/MediaBox")
    55  			imp.UseImportedTemplate(pdf, tpl, 0, 0, 210.0, 297.0)
    56  			// write to bytes buffer
    57  			buf := bytes.Buffer{}
    58  			if err := pdf.Output(&buf); err != nil {
    59  				t.Fail()
    60  			}
    61  		}()
    62  	}
    63  	wg.Wait()
    64  }
    65  
    66  func getTemplatePdf() (io.ReadSeeker, error) {
    67  	tpdf := gofpdf.New("P", "pt", "A4", "")
    68  	tpdf.AddPage()
    69  	tpdf.SetFont("Arial", "", 12)
    70  	tpdf.Text(20, 20, "Example Page 1")
    71  	tpdf.AddPage()
    72  	tpdf.Text(20, 20, "Example Page 2")
    73  	tbuf := bytes.Buffer{}
    74  	err := tpdf.Output(&tbuf)
    75  	return bytes.NewReader(tbuf.Bytes()), err
    76  }