PDF to Image in Go
Overview
Convert PDF pages to images with the PDFCrowd Go client. The client handles communication with the API, while conversions run on PDFCrowd's servers.
Installation
Add the Go client to your module with go get, or see
other installation options.
go get github.com/pdfcrowd/pdfcrowd-go
Quick Start
The examples below use your API credentials. The examples use demo credentials, so you can try the API before getting your own API key. Update the input URLs and filenames as needed.
Convert a PDF URL
Convert a PDF URL to PNG images and save them locally in invoice.zip:
package main import ( "log" "github.com/pdfcrowd/pdfcrowd-go" ) func main() { client := pdfcrowd.NewPdfToImageClient("demo", "demo") client.SetForceZip(true) client.SetOutputFormat("png") err := client.ConvertUrlToFile( "https://your-server.com/invoice.pdf", "invoice.zip", ) if err != nil { log.Print(err) return } }
The URL must return a PDF and be reachable from PDFCrowd's servers. Conversion methods return an error if the input or settings are invalid, or if the conversion fails. See Handle Errors.
Convert a PDF File
Convert invoice.pdf to PNG images and save them locally in invoice.zip:
package main import ( "log" "github.com/pdfcrowd/pdfcrowd-go" ) func main() { client := pdfcrowd.NewPdfToImageClient("demo", "demo") client.SetForceZip(true) client.SetOutputFormat("png") err := client.ConvertFileToFile("invoice.pdf", "invoice.zip") if err != nil { log.Print(err) return } }
Configure a Conversion
Authentication
Pass your PDFCrowd username and API key to
NewPdfToImageClient.
Find your credentials on the API Keys page.
Choose an Input
Send a PDF URL, upload a local file, or pass PDF bytes or a readable binary stream.
| Input | Method |
|---|---|
| URL | ConvertUrlToFile() |
| Local file | ConvertFileToFile() |
| Bytes in memory | ConvertRawDataToFile() |
| Readable binary stream | ConvertStreamToFile() |
Add Conversion Settings
Set conversion options on the client before calling a conversion method.
For example, client.SetDpi(150) renders PDF pages at 150 DPI.
Common settings are listed below. See the method reference for all available options or browse Go examples.
| Purpose | Methods |
|---|---|
| Pages to convert | SetPrintPageRange() |
| Password-protected input | SetPdfPassword() |
| Image format and resolution | SetOutputFormat(), SetDpi() |
| Consistent ZIP output | SetForceZip() |
| Crop area | SetUseCropbox(), SetCropArea() |
| Grayscale | SetUseGrayscale() |
Higher DPI produces larger images and files. PNG is the default image format.
The PDF password unlocks the input document; it is separate from your PDFCrowd API key.
Handle the Result
Choose an Output
A single converted page produces an image; multiple pages produce a ZIP archive containing an image for each page.
The examples use SetForceZip() to always return a ZIP archive, including for a single page.
The methods below use URL input; local files, bytes, and input streams have corresponding methods.
| Output | Method |
|---|---|
| Local file | ConvertUrlToFile() |
| Byte slice | ConvertUrl() |
io.Writer | ConvertUrlToStream() |
File-output methods overwrite an existing destination file.
This example converts PDF pages to PNG images in a ZIP archive, receives the result as a
[]byte and saves it as invoice.zip:
package main import ( "log" "os" "github.com/pdfcrowd/pdfcrowd-go" ) func main() { client := pdfcrowd.NewPdfToImageClient("demo", "demo") client.SetOutputFormat("png") client.SetForceZip(true) result, err := client.ConvertUrl("https://your-server.com/invoice.pdf") if err != nil { log.Print(err) return } if err := os.WriteFile("invoice.zip", result, 0644); err != nil { log.Print(err) return } }
After conversion, IsZippedOutput() indicates whether the result is a ZIP archive.
Match the output filename and content type to the result: .zip and application/zip for archives,
or .png and image/png for a single PNG.
Handle Errors
Conversion methods return an error. API and validation errors have the
type pdfcrowd.Error; local file and
connection failures can return other error types.
This example converts PDF pages to PNG images in a ZIP archive, logs any error,
and uses errors.As to read the HTTP status and reason code when available:
package main import ( "errors" "log" "github.com/pdfcrowd/pdfcrowd-go" ) func main() { client := pdfcrowd.NewPdfToImageClient("demo", "demo") client.SetOutputFormat("png") client.SetForceZip(true) err := client.ConvertUrlToFile( "https://your-server.com/invoice.pdf", "invoice.zip", ) if err != nil { log.Print(err) var apiError pdfcrowd.Error if errors.As(err, &apiError) { log.Printf("Status: %d; reason: %d", apiError.GetStatusCode(), apiError.GetReasonCode()) } return } }
pdfcrowd.Error provides these methods:
| Method | Returns |
|---|---|
GetStatusCode() | The HTTP status code, when available. |
GetReasonCode() | The reason code identifying the specific error, or -1 if unavailable. |
GetMessage() | The error message. |
GetDocumentationLink() | A link to relevant documentation, when available. |
Error() returns the complete error message, including available status and reason codes.
Common Status Codes
| Status | What it means | What to do |
|---|---|---|
400 | Invalid input, settings, or conversion failure | Read the reason code and correct the input or settings. |
401 | Missing credentials or an inactive license | Check your username, API key, and license status. |
403 | Suspended service or no credits remaining | Check your account and available credits. |
413 | Upload exceeds the 300 MB limit | Reduce the upload size. |
429 | Request rate limit reached | Wait and reduce the rate of new requests. |
430 | Concurrent request limit reached | Allow active requests to finish before starting more. |
503 | Temporary network issue | Check your retry policy before submitting another request. |
See all status and reason codes for specific explanations and Limits and Retries for retry behavior.
Read Conversion Information
This information is available after a conversion and describes the client's last conversion.
| Method | Use |
|---|---|
GetJobId() | Identify the conversion in logs and support requests. |
GetDebugLogUrl() | The URL of the conversion debug log when logging is enabled. |
GetPageCount() | Read the page count reported for the conversion. |
GetOutputSize() | Read the output size in bytes. |
GetConsumedCreditCount() | Read the credits consumed by the conversion. |
GetRemainingCreditCount() | Read the remaining credit count reported with the conversion. |
Limits and Retries
Request rate and concurrency limits depend on your license. Control how quickly
your application submits conversions and how many it runs at once. A
429 response concerns request rate; a 430 response
concerns requests already in progress. The maximum upload size is 300 MB.
The Go client automatically retries a request once when it receives HTTP
502 or 503. Use
SetRetryCount()
to change that count, or set it to 0 to disable automatic retries.
Account for these retries when adding an application-level retry policy.
Troubleshooting
Inspect a Conversion
This example converts PDF pages to PNG images in a ZIP archive with debug logging enabled and logs the debug log URL when available. Use the input and settings from the conversion you are investigating.
package main import ( "log" "github.com/pdfcrowd/pdfcrowd-go" ) func main() { client := pdfcrowd.NewPdfToImageClient("demo", "demo") client.SetDebugLog(true) defer func() { if debugLogURL := client.GetDebugLogUrl(); debugLogURL != "" { log.Printf("Debug log: %s", debugLogURL) } }() client.SetOutputFormat("png") client.SetForceZip(true) err := client.ConvertUrlToFile( "https://your-server.com/invoice.pdf", "invoice.zip", ) if err != nil { log.Print(err) return } }
The debug log contains conversion settings and processing details. You can also find logs in your conversion history. A local or connection failure may occur before a conversion log is available.
Common Problems
| Problem | Check |
|---|---|
| The PDF cannot be loaded | Check that the URL returns a PDF, rather than HTML or a login page, and is reachable from PDFCrowd's servers. For local files, check the path and read permissions. |
| The PDF requires a password | Set the input document's password with SetPdfPassword(). |
| The result cannot be opened as an image | Multiple pages produce a ZIP archive. Check IsZippedOutput() and extract the images. |
| Images look blurry or are too large | Adjust SetDpi(). Enlarging raster content cannot recover detail missing from the source. |
For help, contact support and include any available diagnostics, the client version, and enough detail to reproduce the problem.