How to Export Specific PDF Pages in Go
Extract selected pages from an existing PDF in Go, understand page numbering, and handle output and compatibility edge cases.

To export specific pages from a PDF in Go, use a PDF library to extract the requested pages into a new document, then write that document to a separate file. GoPDF2 documents this pattern with ExtractPages. Its page numbers are 1-based: []int{1, 3, 5} selects the first, third, and fifth pages. Check the extraction error before writing.
This guide covers extracting pages from an existing PDF file. It does not render a website into a PDF: for website capture, see the ScreenshotNeo option below.
1. Choose a Go PDF library for the job
For a direct extract-by-page workflow, GoPDF2 documents ExtractPages for file paths and bytes, along with page selection and reordering. Its documentation provides the clearest direct example for this task. The documented API is evidence of its supported workflow, not an independent benchmark or a guarantee about how every PDF feature will be preserved.
Other options may fit better when extraction is one operation in a broader document pipeline. The pdfcpu package documentation lists extraction and selected-page collection among its document operations and describes PDF 1.7 support. The gopdf README describes page selection alongside merging and points to pdfcpu as a broader document-operations option. These are project descriptions, not comparative test results.
| Option | What the reviewed documentation says | Check before choosing |
|---|---|---|
| GoPDF2 | Direct page extraction from a path or bytes; page selection and reordering | Import path, version, option type, error signatures, and behavior for your documents |
| pdfcpu | Extraction and selected-page collection among broader document operations | Exact API or CLI workflow, deployment requirements, license, and document compatibility |
| gopdf | README describes page selection alongside merging | Whether its documented workflow covers your specific extraction needs |
Before adopting any library, verify its current release activity, license, dependencies, and platform requirements in its own documentation. For PDFs with encryption, forms, annotations, bookmarks, or unusual structures, test representative files. The sources cited here do not establish preservation guarantees for those features or for malformed inputs.
2. Extract selected pages with GoPDF2
The documented flow is short: pass the source path and selected page numbers to ExtractPages, handle its error, and write the returned PDF. The example uses the API shape in the GoPDF2 documentation. Confirm the exact import path, package version, option type, and WritePdf signature against the version you install; the research source did not run this snippet.

package main
import "fmt"
func exportSelectedPages() error {
// Confirm the package import and API signatures for your chosen GoPDF2 version.
newPDF, err := gopdf.ExtractPages("input.pdf", []int{1, 3, 5}, nil)
if err != nil {
return fmt.Errorf("extract pages: %w", err)
}
if err := newPDF.WritePdf("selected-pages.pdf"); err != nil {
return fmt.Errorf("write selected pages: %w", err)
}
return nil
}
func main() {
if err := exportSelectedPages(); err != nil {
panic(err)
}
}
The snippet makes the control flow explicit, but it intentionally leaves the import unresolved: the source material does not give a verified module path or version, and package paths can change. Use the project’s current installation instructions to add the package and import its actual module path. The function body follows the documented extraction example; do not treat this page as a claim that the code was compiled against a particular release.
Page numbering, ordering, and duplicates
- Use 1-based page numbers. In the documented API, page 1 is the first page, so
[]int{1, 3, 5}is not zero-indexed. - Choose order deliberately. The package documentation describes page selection and reordering. If the output should follow the requested sequence, provide the indices in that sequence and confirm ordering in the version you use.
- Validate input before extraction. Determine the document’s page count using an API supported by your chosen package, then reject page numbers outside the valid range. Do not assume how an out-of-range value or duplicate is handled unless the package documents it.
- Define duplicate behavior. If callers can request the same page more than once, decide whether that means repeated output pages or invalid input. Validate or normalize the list accordingly.
- Handle an empty selection explicitly. Decide whether it is a caller error. Avoid relying on undocumented behavior for an empty page list.
Make it safe for application use
For a command-line tool, validate that the input path is readable and that the output path is distinct from the source. For a service, write to a temporary file in the target directory and rename it after a successful write if you need to avoid exposing a partial result. Use unique output names for concurrent requests. These are application-level safeguards; they are not guarantees supplied by the extraction API.
Keep errors contextual, as in the example, so logs distinguish extraction failures from output failures. If a job can be retried, make sure a retry will not accidentally overwrite an unrelated file. Enforce your own upload size and processing limits when PDFs come from untrusted callers.
3. Reorder pages or use another documented workflow
Page selection and reordering are available in the reviewed Go PDF documentation, but APIs vary. If a task requires a reordered sequence, represent the requested output order directly, then check the result against the exact library version and a sample PDF. If your pipeline also needs merge, forms, encryption, optimization, or command-line processing, compare the relevant documented operations instead of choosing solely on extraction syntax.

For large documents, avoid reading entire files into memory unless the chosen API requires it. GoPDF2 documents both path and byte-oriented extraction; the path interface may be convenient when the source is already on disk, while a byte interface can fit an in-memory pipeline. Check how the actual package version handles memory and temporary files before processing large batches. No performance measurements are established by the sources reviewed here.
4. Troubleshoot common extraction failures
| Symptom | Likely cause | What to check or change |
|---|---|---|
| Page selection is shifted by one | Zero-based numbering was used with a 1-based API | Convert the caller’s numbering deliberately and document whether your own interface is 0-based or 1-based. |
| Extraction returns an error | Unreadable path, unsupported or malformed input, invalid selection, or another package-specific failure | Wrap and log the original error; check path permissions, page indices, and the library’s documented input constraints. |
| Output file is missing or incomplete | Write failure, invalid directory, permissions issue, or process interruption | Check and return the write error, ensure the output directory exists, and consider a temporary-file-and-rename flow. |
| Output order differs from expectation | Selection order semantics differ from the assumption | Use a tiny known PDF to confirm ordering in the installed version; consult its documentation for reordering semantics. |
| Output loses a document feature | The library may not preserve that feature for this input | Test forms, annotations, bookmarks, encryption, and other required structures with representative files; verify support with the package documentation. |
| Build fails after adding the package | Incorrect import path, incompatible version, or dependency/platform constraint | Use the current project installation instructions and verify module path, Go compatibility, and deployment requirements. |
5. Reliability, performance, and cost considerations
Extraction speed and memory use depend on the PDF, the selected library, and whether data is handled from a path or in memory. The reviewed sources provide no benchmark that supports a throughput claim. Measure with documents resembling production inputs if latency, memory ceilings, or batch size matter.
For reliability, handle both extraction and write errors, validate selections before work begins, and test output page count and order. If the source can be encrypted or malformed, decide how your application should report that case. Preservation of annotations, forms, bookmarks, encryption, and malformed-file recovery has not been established by the cited documentation, so treat these as compatibility checks rather than assumptions.
These Go libraries are software dependencies; the research dossier does not establish their current pricing or support terms. Check each project’s current license and deployment needs. For a hosted screenshot API, the economics are different because you are capturing a live page rather than extracting pages from an existing PDF.
6. Or skip the browser setup
If the task is to capture a website as a PDF rather than split pages from an existing PDF, ScreenshotNeo can return a PDF from one API request. See the ScreenshotNeo API documentation for current parameters. This does not replace Go-side extraction of an existing PDF.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
The one-call example uses the supplied ScreenshotNeo request shape; use the documented output-format parameter when you need PDF output instead of the example’s WebP file extension. ScreenshotNeo removes cookie banners, popups, and chat widgets before the shot. Bot checks, blank pages, and failed loads are never billed, and response headers identify page verdict and billing status. Its MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. See ScreenshotNeo for the product and the docs for request options.
Sign up for 1,000 free screenshots a month, with no card.
7. Frequently asked questions
Does page extraction create a separate PDF?
Yes. The documented flow returns a new PDF object and writes it to a new output file.
Can I export pages from bytes instead of a path?
GoPDF2 documentation describes extraction from both file paths and bytes. Confirm the exact byte-oriented function signature in the version you use.
Will extraction preserve every feature in the source PDF?
The reviewed sources do not establish that. Test the specific structures your application depends on against representative inputs and the library’s current documentation.
Is this the right approach for saving a few pages from a website?
No. This workflow extracts pages from an existing PDF. To capture a website, use a browser-based capture workflow or a screenshot API such as ScreenshotNeo.
Sources
- GoPDF2 package documentation — documented extraction example, page numbering, path and byte workflows, selection and reordering.
- pdfcpu package documentation — documented PDF operations including extraction and selected-page collection.
- gopdf README — project description of page selection and related operations.


