Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a Go PDF library that supports page extraction, pass the pages as 1-based integers, check the returned error, and write the resulting document to a new file. The documented GoPDF2 flow is:

newPDF, err := gopdf.ExtractPages("input.pdf", []int{1, 3, 5}, nil)
if err != nil {
    return err
}
return newPDF.WritePdf("selected-pages.pdf")

This creates a separate PDF containing the first, third, and fifth pages. The example follows the package documentation; confirm the import path, package version, option type, and WritePdf signature for the release you install.

What the extraction call does

ExtractPages reads an existing PDF, selects the requested pages, and returns a new PDF object. Calling WritePdf saves that object as another file, leaving the source unchanged. Page numbers in the documented API are 1-based: page 1 is the first page, page 3 is the third, and so on.

The function accepts a file path in the documented example. The package also documents extraction from bytes, which is useful when a PDF arrives from an upload, database, or HTTP response rather than the local filesystem.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
PDF Extra 2024| Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Lifetime License | 1 Windows PC | 1 User [PC Online code]
  • EDIT text, images & designs in PDF documents. ORGANIZE PDFs. Convert PDFs to Word, Excel & ePub.
  • READ and Comment PDFs – Intuitive reading modes & document commenting and mark up.
  • CREATE, COMBINE, SCAN and COMPRESS PDFs
  • FILL forms & Digitally Sign PDFs. PROTECT and Encrypt PDFs
  • LIFETIME License for 1 Windows PC or Laptop. 5GB MobiDrive Cloud Storage Included.

Complete Go workflow

Because package import paths and option types can change, use the import path shown by the exact GoPDF2 version you select. The following program illustrates the complete control flow and assumes that version exposes the package under the name gopdf.

package main

import (
    "fmt"
    "os"

    gopdf "your-installed-gopdf2-package"
)

func exportPages(input, output string, pages []int) error {
    if len(pages) == 0 {
        return fmt.Errorf("at least one page is required")
    }
    for _, page := range pages {
        if page < 1 {
            return fmt.Errorf("page numbers are 1-based; got %d", page)
        }
    }

    selected, err := gopdf.ExtractPages(input, pages, nil)
    if err != nil {
        return fmt.Errorf("extract pages: %w", err)
    }
    if err := selected.WritePdf(output); err != nil {
        return fmt.Errorf("write output: %w", err)
    }
    return nil
}

func main() {
    if len(os.Args) != 3 {
        fmt.Fprintf(os.Stderr, "usage: %s input.pdf selected-pages.pdfn", os.Args[0])
        os.Exit(2)
    }
    if err := exportPages(os.Args[1], os.Args[2], []int{1, 3, 5}); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
    fmt.Printf("wrote %sn", os.Args[2])
}

After adding the library with the version’s documented module path, run the program with an input and output path:

go run . input.pdf selected-pages.pdf

The output is a new PDF. If any requested page is outside the source document’s range, extraction may fail; validate the page count when your application can do so and treat the extraction error as a failed operation rather than writing a partial result.

Choosing pages correctly

Use one-based page numbers

Do not pass zero for the first page. A user-facing page label printed on a document can differ from its physical index—for example, a Roman-numeral cover may be labelled “i” while still being physical page 1. The extraction API uses physical, 1-based positions.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Preserve or change order deliberately

The documented selection slice is ordered. A slice such as []int{5, 2, 5} asks for page 5, then page 2, then page 5 again. Whether duplicate pages, duplicate resources, or unusual ordering are retained exactly is library behavior, so test those cases with your chosen release before relying on them.

Build the selection from user input safely

Convert strings to integers, reject values below 1, cap the number of requested pages if an endpoint is public, and report malformed values before opening the PDF. If users enter ranges such as 2-4, expand them to 2, 3, 4 yourself and enforce a maximum range length.

func parsePages(values []int) ([]int, error) {
    if len(values) == 0 {
        return nil, fmt.Errorf("no pages selected")
    }
    for _, n := range values {
        if n < 1 {
            return nil, fmt.Errorf("invalid page %d", n)
        }
    }
    return values, nil
}

File paths, bytes, and web requests

Local files

For a local workflow, pass the input path exactly as documented and write to a different output path. Writing over the source makes recovery harder if the process is interrupted. Write to a temporary destination in the same directory, close or finalize it successfully, then rename it if you need an atomic replacement.

In-memory PDFs

When a PDF is already in memory, use the package’s documented byte-input extraction variant instead of writing an unnecessary temporary file. Keep limits on upload size and selected-page count, and release the byte buffer after the output has been persisted.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

HTTP downloads

Download the response to a bounded buffer or temporary file only after checking the HTTP status and content type. A login page or an HTML error document saved with a .pdf extension will produce a confusing parser error. Set a request timeout, restrict redirects according to your security policy, and never let an untrusted URL turn your service into an open proxy.

Rank #2
MobiPDF Lifetime - Professional PDF Editor for Windows | Edit, Sign & Convert PDFs | Best Adobe Acrobat Pro Alternative | Lifetime License
  • Edit PDFs with Ease. Modify text, images, and layouts directly within your PDF documents.
  • Convert & Organize. Export PDFs to Word, Excel, or ePub, and organize files with ease.
  • Read & Annotate. Enjoy intuitive reading modes and powerful tools to comment, highlight, and mark up PDFs.
  • Create & Manage PDFs. Create new PDFs, combine multiple files, scan documents, and compress for easy sharing.
  • Fill & Sign Forms. Complete forms and digitally sign documents with secure e-signature tools.

Library choice: what to verify

GoPDF2 documents direct extraction by path and bytes, page selection, and reordering. The pdfcpu project documents extraction and selected-page collection among broader PDF operations and describes support through PDF 1.7. The gopdf README presents page selection alongside merging and positions pdfcpu as a broader document-operations option. These are project descriptions, not an independent benchmark.

Decision axis Questions to answer before adoption
Task and API fit Does the version expose direct selected-page extraction, reordering, and the input form you need (path or bytes)?
Other operations Will the same service also merge files, optimize PDFs, process forms, or apply encryption?
Deployment What dependencies, platform requirements, memory behavior, and command-line options does the current release require?
Maintenance and license Check the current license, release activity, and support status in the project’s own documentation.
Compatibility Test encrypted, malformed, annotation-heavy, form-heavy, and large PDFs that resemble production input.

No source establishes that extraction preserves every encryption setting, annotation, form field, bookmark, or malformed-file feature. If those properties matter, compare the source and output with representative fixtures and document the result for the exact library version.

Validation and production safeguards

  • Check every error. Handle extraction failure before calling WritePdf, then handle the write error separately.
  • Keep source and destination distinct. Use a temporary output and rename only after a successful write.
  • Limit resource use. Bound input bytes, page-count requests, concurrent jobs, and temporary-storage space.
  • Use stable names. Generate output names that cannot escape the intended directory; never concatenate unchecked user input into a path.
  • Verify the result. Reopen the output with a PDF reader or a validation routine, check its file size, and confirm that the number and order of pages match the request.
  • Log useful context. Record the library version, input identifier, requested pages, elapsed time, and error category without logging sensitive document contents.

Common failures and fixes

“Page not found” or an extraction error

The list may contain zero, a negative number, or a page beyond the source’s physical count. Count pages first when possible, remember that indexing starts at 1, and return a clear client error for invalid input.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The output will not open

Check the write error, ensure the destination is not being read before the writer has finished, and verify that the input was actually a PDF rather than an HTML error response. Test the output with an independent PDF viewer.

Encrypted or password-protected input

The available evidence does not establish how the documented extraction call handles encryption. Determine whether your selected version accepts credentials or requires prior decryption, and test that path with a fixture matching your production policy.

Forms, annotations, bookmarks, or links changed

Page extraction can involve copying indirect objects and document metadata. Preservation of these features is not guaranteed by the cited documentation. If they are contractual requirements, test each feature and select a library/version that demonstrably preserves it.

Large files are slow or memory-intensive

Measure with realistic PDFs, reduce concurrent jobs, stream downloads to disk, and place temporary files on storage with enough capacity. Avoid assuming that selecting only two pages means the parser will read only two pages of the source.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Output order differs from expectations

Confirm the exact order of the selection slice and test duplicates. Do not sort the slice unless sorted output is what your product requires.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Testing strategy

Create fixtures for a one-page file, a multi-page file with distinct headers, a reordered selection, repeated pages, an invalid page, an encrypted file if supported, and PDFs containing forms or annotations. For each successful case, assert that the output opens and that page text or another stable marker appears in the expected order. Keep the fixtures and the library version together so a dependency upgrade reveals compatibility changes.

Rank #3
Scrivar PDF Pro - Organize, Edit, Compress, Convert, Merge, eSign, OCR & 30+ tools | Lifetime License
  • EVERY PDF TOOL UNLOCKED - 30+ tools in one app: edit text and images, convert, merge, split, compress, sign, OCR, redact, watermark, batch process, and more. No feature gates, no upsells, nothing held back.
  • PAY ONCE, OWN FOREVER — A one-time purchase, not a subscription. Other apps runs $240/year — Scrivar is yours for life, with free updates included.
  • UNLIMITED eSIGN, BUILT IN — Send contracts and forms for signature and track every step. Recipients sign in their browser with no account or app needed. Replace DocuSign and save hundreds a year.
  • PC, MAC, AND WEB — Install on any Win 10/11 PC or macOS 11+ Mac (Intel or Apple Silicon), or work in your browser at scrivar.com. Same tools, same account, everywhere you work.
  • OCR + FULL OFFICE CONVERSION — Turn scanned documents into searchable, selectable text, and convert PDFs to and from Word, Excel, and PowerPoint with formatting kept intact.

Or skip the browser setup

If your source is a public webpage or hosted document and your real goal is a clean visual capture rather than extracting physical pages, ScreenshotNeo can return a screenshot or PDF through one GET request. It is not a substitute for selecting pages from an existing local PDF; it is an alternative when you need to capture a URL.

For example, the cURL request below captures a URL and writes the response to a file:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

In Go, the same endpoint can be called with the standard HTTP client:

package main

import (
    "io"
    "net/http"
    "net/url"
    "os"
)

func main() {
    q := url.Values{}
    q.Set("access_key", "YOUR_API_KEY")
    q.Set("url", "https://stripe.com")
    resp, err := http.Get("https://api.screenshotneo.com/v1/shot?" + q.Encode())
    if err != nil { panic(err) }
    defer resp.Body.Close()
    if resp.StatusCode < 200 || resp.StatusCode >= 300 { panic(resp.Status) }
    out, err := os.Create("shot.webp")
    if err != nil { panic(err) }
    defer out.Close()
    if _, err := io.Copy(out, resp.Body); err != nil { panic(err) }
}

See the ScreenshotNeo documentation for response formats and options. Before capture it can accept cookie or consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing result in X-Page-Verdict and X-Billed headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

Every plan includes the features. The Free plan includes 1,000 shots per month without a card; paid plans are $5 for 3,000 shots, $15 for 15,000, $39 for 60,000, $99 for 250,000, and $249 for 1,000,000. Yearly billing gives two months free. Sign up for the free 1,000-shot plan.

Frequently Asked Questions

Can I pass page numbers starting at zero?

No. The documented GoPDF2 extraction API uses 1-based physical page numbers, so the first page is 1.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Does extraction modify the original PDF?

The documented flow returns a new PDF object and writes it to a separate output path; keep the paths distinct in production.

Will bookmarks and form fields always survive?

That behavior is not established by the available documentation. Test the exact library version with representative files when preservation matters.

Can ScreenshotNeo extract selected pages from a local PDF?

No. ScreenshotNeo captures URLs and can produce screenshots or PDFs; use a Go PDF library for selecting pages from an existing local document.

Quick Recap

Bestseller No. 1
PDF Extra 2024| Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Lifetime License | 1 Windows PC | 1 User [PC Online code]
PDF Extra 2024| Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Lifetime License | 1 Windows PC | 1 User [PC Online code]
READ and Comment PDFs – Intuitive reading modes & document commenting and mark up.; CREATE, COMBINE, SCAN and COMPRESS PDFs
$99.99
Bestseller No. 2
MobiPDF Lifetime - Professional PDF Editor for Windows | Edit, Sign & Convert PDFs | Best Adobe Acrobat Pro Alternative | Lifetime License
MobiPDF Lifetime - Professional PDF Editor for Windows | Edit, Sign & Convert PDFs | Best Adobe Acrobat Pro Alternative | Lifetime License
Edit PDFs with Ease. Modify text, images, and layouts directly within your PDF documents.; Convert & Organize. Export PDFs to Word, Excel, or ePub, and organize files with ease.
$99.99

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.