Attaching a File
This guide will show you how to attach files into a PDF document.
Sample Input
As you can see here in the screenshot below, the attachment button is not shown on the right side of the window which means that the document does not have any attachments.
Before you begin
You should get your API key from your UniCloud account.
If this is your first time using UniPDF SDK, follow this guide to set up a local development environment.
Clone the project repository
In your terminal, clone the examples repository. It contains the Go code we will be using for this guide.
git clone https://github.com/unidoc/unipdf-examples.git
Navigate to the render
folder in the unipdf-examples directory.
cd unipdf-examples/attachment
How it works
Lines 7-14
import the UniPDF packages and other required dependencies.
The init
function in lines 16-23
authenticates your request with your UNIDOC_LICENSE_API_KEY
.
The main function in lines 25-38
defines which PDF file used as a base and which file will be attached into it.
There are two function provided by UniPDF to attach files to a PDF file, one would accept the file path and the other would accept the file contents in bytes array.
The use of those two functions are available in the code example. The function that use a file path is used in function addAttachment
in line 40-77
and the function that attach file contents into a PDF file is used in function addAttachmentFromContent
in line 79-122
.
To attach a file into a PDF document using a file path, first we’ll need to open the base PDF file and get the PDFReader
object and create an instance of PDFWriter
.
1. Attaching file using a file path
To attach a file to a PDF document by using a file path, we’ll need to construct an EmbeddedFile
object and assign some info for that file such as name, description, and the relationship of the attached file with the PDF file (line 59-68
).
After that we’ll pass the EmbeddedFile
object to AttachFile
function of a PDFWriter
object (line 70-72
).
2. Attaching file using it’s content
To attach a file to a PDF document by using a file path, we’ll need to construct an EmbeddedFile
object from the file content and assign some info for that file such as name, description, and the relationship of the attached file with the PDF file (line 104-113
).
After that we’ll pass the EmbeddedFile
object to AttachFile
function of a PDFWriter
object (line 115-118
).
Run the code
Run this command to attach multiple copies of file into an existing PDF file. This will also get all the required dependencies to run the program.
go run pdf_add_attachment.go
Sample output
Now as you can see here in the screenshot below, the attachment button is now shown on the right side of the window which means that the document has attachments and by clicking that button will open a drawer that shows all the attached file.