unidoc / unipdf-examples

Examples for creating and processing PDF files with UniPDF https://github.com/unidoc/unipdf
https://unidoc.io
272 stars 101 forks source link

[Question] Modifying a Link #158

Closed polderudo closed 3 years ago

polderudo commented 3 years ago

Is it somehow possible to modify links inside a PDF? We have some PDFs where we need to replace a specific part of a Link e.g. https://server.com//ap/ and change the to a specific value. There might be a lot of links inside the PDF but the part to replace is always the same.

gunnsth commented 3 years ago

@polderudo Links are typically just Link Annotations with a URI action which points to an external URL.

One can update the link annotation targets like:

annotations, err := page.GetAnnotations()
if err != nil {
    return err
}
for _, annotation := range annotations {
    switch t := annotation.GetContext().(type) {
    case *model.PdfAnnotationLink:
        dict, ok := core.GetDict(t.A)
        if !ok {
            continue
        }

        url, ok := dict.GetString("URI")
        if !ok {
            continue
        }

        fmt.Printf("URL: %s -> https://unidoc.io\n", url)
        // Change the url to https://unidoc.io
        dict.Set("URI", core.MakeString(`https://unidoc.io`))
    }
}

See a full example at our Playground here: https://play.unidoc.io/p/4840ed82b743f068

Note that the actual text that appears in the PDF is kept separately than the external link in the Link Annotation. So if you want to change the text that appears on the page that needs to be done separately.

polderudo commented 3 years ago

works like a charm. Thanks Gun