How to Merge & Split PDF Files in Golang Using UniPDF
How to Merge & Split PDF in Golang Using UniPDF
PDFs are one of the most widely used document formats. They’re versatile, secure, and compatible with various platforms. Whether you’re working with PDFs for personal or professional use, you may need to manipulate them differently. In this blog post, we’ll show you how to merge and split PDFs in Golang using UniPDF, a popular library for working with PDF files.
We’ll cover the following topics:
1. Why UniPDF?
UniPDF is a powerful Golang library that offers various features for working with PDF files, such as:
- Merging and splitting PDFs
- Converting images to PDF (e.g., jpg 2 pdf)
- Optimizing PDFs by reducing their size (e.g., 1000mb to kb)
- Extracting text, images, and metadata from PDFs
- Adding annotations and highlights (e.g., highlight pdf for free)
- Editing PDFs (e.g., pdf editor with a highlighter)
UniPDF offers a comprehensive set of features and functionalities that go beyond what is available in pdfcpu. These additional capabilities can be crucial in scenarios where you need to manipulate, extract, or generate PDFs with advanced formatting, encryption, digital signatures, or interactive forms. Its versatility and user-friendly design make it the perfect choice for handling PDF-related tasks.
2. How to Merge PDFs with UniPDF
Merging multiple PDFs into a single file can be useful for various reasons, such as combining related documents or reducing the number of files to manage. In this guide, we’ll provide a simple snapshot of merging two PDFs using UniPDF, but you can merge any number of files, perform more advanced merging including merging document properties like Forms, or add page numbers to each page in the merged output. Here’s how to merge PDFs using UniPDF:
Install UniPDF: First, install the UniPDF library using the following command:
go get -u github.com/unidoc/unipdf/v3
Import UniPDF: In your Golang script, import the necessary packages:
import (
"github.com/unidoc/unipdf/v3/common/license"
"github.com/unidoc/unipdf/v3/model"
)
Load PDF files: Load the PDF files you want to merge using the model.NewPdfReaderFromFile function:
reader1, err := model.NewPdfReaderFromFile("file1.pdf", nil)
reader2, err := model.NewPdfReaderFromFile("file2.pdf", nil)
Create a new PDF writer: Create a new PDF writer using the model.NewPdfWriter function:
writer := model.NewPdfWriter()
Merge PDFs: Iterate through the pages of each PDF file and add them to the new PDF writer:
for _, reader := range []*model.PdfReader{reader1, reader2} {
numPages := reader.GetNumPages()
for i := 1; i <= numPages; i++ {
page, err := reader.GetPage(i)
}
}
if err != nil {
log.Fatalf("Error getting page %d: %v", i, err)
}
err = writer.AddPage(page)
if err != nil {
log.Fatalf("Error adding page %d: %v", i, err)
}
Write the merged PDF to a file: Write the merged PDF to a new file using the writer.WriteToFile function:
err = writer.WriteToFile("merged.pdf")
if err != nil {
log.Fatalf("Error writing merged file: %v", err)
}
That’s it! With these simple steps, you can merge multiple PDF files into a single document using UniPDF.
For more advanced merging scenarios, consider looking into the basic merger, advanced merger, or merger with page numbers examples from the UniPDF GitHub repository. These examples illustrate how to merge any number of files, merge documents with properties like Forms, and add page numbers to each page in the merged output.
3. How to Split PDFs with UniPDF
Splitting a PDF into separate files can be helpful for various reasons, such as extracting specific sections or reducing the file size for easier sharing. Here’s how to split PDFs using UniPDF:
Install and import UniPDF: If you haven’t already, install and import the UniPDF library as described in the previous section.
Load the PDF file: Load the PDF file you want to split using the model.NewPdfReaderFromFile function:
reader, err := model.NewPdfReaderFromFile("input.pdf", nil)
- Determine the number of pages: Get the total number of pages in the PDF file:
numPages := reader.GetNumPages()
- Split the PDF: For each page in the PDF file, create a new PDF writer, add the page to the writer, and save it as a separate file:
for i := 1; i <= numPages; i++ {
// Create a new PDF writer
writer := model.NewPdfWriter()
// Get the page from the input PDF
page, err := reader.GetPage(i)
if err != nil {
log.Fatalf("Error getting page %d: %v", i, err)
}
// Add the page to the new PDF writer
err = writer.AddPage(page)
if err != nil {
log.Fatalf("Error adding page %d: %v", i, err)
}
// Write the split PDF to a new file
outputFilename := fmt.Sprintf("split_page_%d.pdf", i)
err = writer.WriteToFile(outputFilename)
if err != nil {
log.Fatalf("Error writing split PDF: %v", err)
}
}
4. Optimizing PDF Size with UniPDF
Merging or splitting PDF files is a common task, but it often results in large PDF files that can be cumbersome to share or upload. The output file size is especially a concern when merging multiple documents into one, or when extracting specific sections of a larger document in the splitting process. Therefore, after merging or splitting PDFs, it’s critical to consider the final file size.
Fortunately, UniPDF provides an efficient feature to address this issue. It allows you to optimize and reduce the size of the resultant PDF files, making them more manageable and suitable for sharing or uploading.
Here’s how to optimize a PDF’s size using UniPDF:
Install and import UniPDF: If you haven’t already, install and import the UniPDF library as described in the previous sections.
Load the PDF file: Load the PDF file you want to optimize using the model.NewPdfReaderFromFile function:
reader, err := model.NewPdfReaderFromFile("input.pdf", nil)
Create a new PDF writer: Create a new PDF writer using the model.NewPdfWriter function:
writer := model.NewPdfWriter()
Configure optimization settings: Set the desired optimization settings in the PDF writer:
writer.SetOptimizer(model.NewDefaultOptimizer())
Transfer content from input to output PDF: Iterate through the pages of the input PDF and add them to the output PDF writer:
numPages := reader.GetNumPages()
for i := 1; i <= numPages; i++ {
page, err := reader.GetPage(i)
if err != nil {
log.Fatalf("Error getting page %d: %v", i, err)
}
err = writer.AddPage(page)
if err != nil {
log.Fatalf("Error adding page %d: %v", i, err)
}
}
5. Examples and Use Cases
Here are some examples of how merging and splitting PDFs with UniPDF can be beneficial:
Combining lecture notes: As a student, you might have lecture notes saved as separate PDFs for each class session. Merging them into a single document makes reviewing and searching for information easier.
Organizing scanned documents: If you’ve scanned multiple pages of a document into individual PDFs, merging them can help keep everything organized and easily accessible.
Extracting specific chapters from eBooks: If you’re interested in only a few chapters of an eBook, you can split the PDF to extract those sections and save them as separate files.
Creating a custom PDF from multiple sources: If you’re working on a project that requires information from different sources, you can merge PDFs from various files to create a custom document tailored to your needs.
Conclusion
UniPDF is a powerful and versatile Golang library that simplifies working with PDF files. With its user-friendly API and wide range of features, you can easily merge and split PDFs and perform various other operations such as converting images to PDFs, extracting text, editing, and annotating documents.
In this blog post, we’ve shown you how to merge and split PDFs using UniPDF in Golang. By following the step-by-step instructions provided, you can easily manipulate PDF files to suit your needs, whether for personal or professional use.
Now that you have a solid understanding of merging and splitting PDFs with UniPDF, you can explore other library features and further enhance your Golang applications.
Remember, UniPDF is constantly being updated and improved to provide users with the best possible experience. So, watch the UniPDF documentation and their official blog for the latest news, tutorials, and feature updates.