Editing pages and documents
Merge, split, insert, delete, rotate, reorder and crop pages, set page backgrounds, and edit text and images with NexPDF for Go.
License module
Page and content editing needs the editor module (Startup tier and above). Inserting pictures as
pages needs no module.
Page indices start at 0. Save with doc.Save(path, false), or doc.Save(path, true) for a
"Fast Web View" file. SaveBytes() and SaveLinearized() return the bytes instead.
Merge and split
a, err := nexpdf.Open("a.pdf")
if err != nil {
log.Fatal(err)
}
defer a.Close()
b, err := nexpdf.Open("b.pdf")
if err != nil {
log.Fatal(err)
}
defer b.Close()
a.AppendDocument(b) // a now has the pages of a, then b
a.Save("merged.pdf", false)
firstThree, err := a.ExtractPages([]uint32{0, 1, 2})
if err != nil {
log.Fatal(err)
}
defer firstThree.Close()
firstThree.Save("part1.pdf", false)Insert, duplicate, delete and reorder
doc.AddBlankPage() // appends a blank page
doc.DuplicatePage(0) // inserts a copy of page 0 after it
doc.MovePage(3, 0) // moves page 3 to the front
doc.DeletePage(5)
doc.ReversePages()
scan, _ := os.ReadFile("scan.jpg")
doc.InsertImagePages(2, scan) // one page per picture, before page 2Rotate and crop
doc.RotatePage(0, 90) // multiples of 90 degrees
doc.CropPage(1, 36, 36, 576, 756) // new crop box in PDF pointsPage backgrounds
doc.SetPageBackground(`{"color":"#fbf4e2","pages":[]}`, nil, 0, 0) // every page
doc.RemovePageBackground("")Pass RGB pixels (width x height x 3 bytes) with their size to use a picture, and "fit" (cover,
stretch or center), "scale" and "opacity" in the options.
Edit page text and images
PageContentJSON(page) lists the text lines and images of a page with an id for each:
type Item struct {
ID string `json:"id"`
Kind string `json:"kind"`
Text string `json:"text"`
}
s, _ := doc.PageContentJSON(0)
var items []Item
json.Unmarshal([]byte(s), &items)
for _, it := range items {
if it.Kind == "text" && strings.Contains(it.Text, "Draft") {
doc.EditText(0, it.ID, `{"text":"Final","color":"#111827"}`)
break
}
}
doc.AddPageText(0, `{"text":"Approved","x":72,"y":60,"size":14,"color":"#16A34A","bold":true}`)Ids stay valid until the next edit of that page, so read the content again after each change. For
images use TransformImage(page, id, llx, lly, urx, ury) to move or resize,
ReplaceImage(page, id, rgb, width, height) to swap the picture and DeleteContent(page, id) to
remove it.
Related
- Document structure: metadata, bookmarks, page labels and attachments
- Compare and optimise: compare versions and make files smaller