pdfcpu / pdfcpu

A PDF processor written in Go.

Home Page:http://pdfcpu.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Calling api.ValidateContext after ctx.AddAttachment removes attachment

vsenko opened this issue · comments

I'm using pdfcpu v0.7.0 on Debian 12 x86-64.

Code to reproduce:

package main

import (
	"bytes"
	"fmt"
	"strings"

	pdfcpuapi "github.com/pdfcpu/pdfcpu/pkg/api"
	"github.com/pdfcpu/pdfcpu/pkg/pdfcpu"
	pdfcpucreate "github.com/pdfcpu/pdfcpu/pkg/pdfcpu/create"
	pdfcpumodel "github.com/pdfcpu/pdfcpu/pkg/pdfcpu/model"
	pdfcputypes "github.com/pdfcpu/pdfcpu/pkg/pdfcpu/types"
)

func main() {
	ctx, err := pdfcpu.CreateContextWithXRefTable(pdfcpumodel.NewDefaultConfiguration(), pdfcputypes.PaperSize["A4"])
	if err != nil {
		panic(err)
	}

	template := `{"pages": { "1": { "content": { "text": [{ "value": "page 1", "anchor": "left", "font": { "name": "Helvetica", "size": 12 } }] } } } }`
	err = pdfcpucreate.FromJSON(ctx, strings.NewReader(template))
	if err != nil {
		panic(err)
	}

	err = ctx.AddAttachment(pdfcpumodel.Attachment{Reader: strings.NewReader("a"), ID: "a", Desc: "a"}, false)
	if err != nil {
		panic(err)
	}

	err = pdfcpuapi.ValidateContext(ctx)
	if err != nil {
		panic(err)
	}

	var b bytes.Buffer
	err = pdfcpuapi.WriteContext(ctx, &b)
	if err != nil {
		panic(err)
	}

	attachements, err := pdfcpuapi.ExtractAttachmentsRaw(bytes.NewReader(b.Bytes()), "", nil, nil)
	if err != nil {
		panic(err)
	}

	for _, a := range attachements {
		fmt.Println(a.ID)
	}
}

Expected output is:

a

But actual output is empty.

Removing the following lines fixes the output:

	err = pdfcpuapi.ValidateContext(ctx)
	if err != nil {
		panic(err)
	}

Fixed with latest commit!

Thank you!