pdfcpu / pdfcpu

A PDF processor written in Go.

Home Page:http://pdfcpu.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Help with adding image to form field

vekonylaszlo opened this issue · comments

Hello! Thank you for the great library!

I'm currently experimenting with the API to fill out a form that includes two text fields and one image. I've successfully filled the two text fields named "Distributor" and "Date" in an example.pdf. However, I'm encountering an issue when attempting to fill the field labeled "QR code".

Here's the code snippet I'm using:

        pdfPath := `example.pdf`

	fields, err := api.FormFields(inFile, nil)
	if err != nil {
		log.Fatalf("fields %v", err)
	}

	pdfFile, err := os.ReadFile(pdfPath)
	if err != nil {
		log.Fatalf("opening %v", err)
	}
	barcodePath := `C:\Dev\go\sharepoint-migrator\static\private\temp\barcode.png`
	barcodeBytes, err := os.ReadFile(barcodePath)
	if err != nil {
		log.Fatalf("barcode opening %v", err)
	}

	formData := FormData{
		Forms: []Form{


			{
				Textfield: []TextField{
					{Name: "Distributor", Value: "distributor", Locked: true},
					{Name: "Date", Value: "2024.01.01", Locked: true},
					{Name: "QR code", Value: string(barcodeBytes), Locked: true},
				},
			},
		},
	}

	dataJson, err := json.Marshal(formData)
	if err != nil {
		log.Fatalf("marshal %v", err)
		return
	}

	filledBytes, err := FillForm(pdfFile, dataJson)
	if err != nil {
		log.Fatalf("fill %v", err)
	}

	err = os.WriteFile("filled.pdf", filledBytes, 0644)
	if err != nil {
		log.Fatalf("write %v", err)
	}

In the provided code, I'm successfully filling the "Distributor" and "Date" fields, but when trying to fill the "QR code" field, I encounter an issue.

Thank you for your help!

There is nothing like an image form field defined for PDF forms AFAIK so you have to fake that.

Right now PDF form creation and filling is done via JSON or CSV only.

Checkout samples/form/fill/person.json:

You will need to do smth like:

"pages": {
				"1": {
					"image": [
						{
							"src": "../../testdata/resources/qr.png",
							"pos": [
								40,
								350
							],
							"width": 290,
							"height": 200,
							"bgCol": "#F5F5DC",
							"border": {
								"width": 5,
								"col": "LightGray",
								"style": "round"
							},
							"url": "https://pdfcpu.io"
						}
					]
				}
			}

Basically you are almost there.
In your case you have 2 textfields and 1 image.

Thank you!