Image to PDF in Go

Overview

Convert images to PDF documents 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

Update the input URLs and filenames as needed.

Convert an Image URL

Convert a PNG image to PDF and save it locally as logo.pdf:

package main

import (
    "log"
    "github.com/pdfcrowd/pdfcrowd-go"
)

func main() {
    client := pdfcrowd.NewImageToPdfClient("demo", "demo")

    err := client.ConvertUrlToFile(
        "https://your-server.com/logo.png", "logo.pdf",
    )
    if err != nil {
        log.Print(err)
        return
    }
}

The URL must return the image itself 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 an Image File

Convert logo.png to PDF and save it locally as logo.pdf:

package main

import (
    "log"
    "github.com/pdfcrowd/pdfcrowd-go"
)

func main() {
    client := pdfcrowd.NewImageToPdfClient("demo", "demo")

    err := client.ConvertFileToFile("logo.png", "logo.pdf")
    if err != nil {
        log.Print(err)
        return
    }
}

Configure a Conversion

Authentication

Pass your PDFCrowd username and API key to NewImageToPdfClient. Find your credentials on the API Keys page.

Choose an Input

The source image format is detected automatically. Each conversion accepts one image.

InputMethod
URLConvertUrlToFile()
Local fileConvertFileToFile()
Bytes in memoryConvertRawDataToFile()
Readable binary streamConvertStreamToFile()

For a local image or a URL on localhost, upload the file, bytes, or an open binary stream. Remote URLs must be reachable from PDFCrowd's servers.

Send Image Bytes

Read logo.png as bytes, convert it to PDF, and save logo.pdf:

package main

import (
    "log"
    "os"
    "github.com/pdfcrowd/pdfcrowd-go"
)

func main() {
    client := pdfcrowd.NewImageToPdfClient("demo", "demo")

    image, err := os.ReadFile("logo.png")
    if err != nil {
        log.Print(err)
        return
    }

    err = client.ConvertRawDataToFile(image, "logo.pdf")
    if err != nil {
        log.Print(err)
        return
    }
}

Add Conversion Settings

Set conversion options on the client before calling a conversion method. For example, client.SetPageSize("A4") selects A4 paper.

Common settings are listed below. See the method reference for all available options or browse Go examples.

Image operations change the source image; page settings control the output area and image placement.

PurposeMethods
Resize or rotateSetResize(), SetRotate()
Crop or remove solid-color bordersSetCropArea(), SetRemoveBorders()
Image resolution for layoutSetDpi()
PDF page dimensions and marginsSetPageSize(), SetPageDimensions(), SetPageMargins(), SetOrientation()
Image placementSetPrintPageMode(), SetPosition(), SetPageBackgroundColor()
PDF passwords and permissionsSetUserPassword(), SetOwnerPassword(), SetNoPrint(), SetNoCopy()

With an explicit page size, use SetPrintPageMode() with "fit" to preserve the aspect ratio and fit the image inside the margins. The "stretch" mode fills the area and can distort the image. The default mode does not scale the image to fit and can crop it. Without an explicit size, margins add a border around the image.

Handle the Result

Choose an Output

The PDF contains the source image. Making text in a scan searchable requires a separate OCR step.

The methods below use URL input; local files, bytes, and input streams have corresponding methods.

OutputMethod
Local fileConvertUrlToFile()
Byte sliceConvertUrl()
io.WriterConvertUrlToStream()

File-output methods overwrite an existing destination file.

This example converts an image, receives the result as a []byte and saves it as logo.pdf:

package main

import (
    "log"
    "os"
    "github.com/pdfcrowd/pdfcrowd-go"
)

func main() {
    client := pdfcrowd.NewImageToPdfClient("demo", "demo")

    result, err := client.ConvertUrl("https://your-server.com/logo.png")
    if err != nil {
        log.Print(err)
        return
    }
    if err := os.WriteFile("logo.pdf", result, 0644); err != nil {
        log.Print(err)
        return
    }
}

When serving the result from a web application, use Content-Type: application/pdf.

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 an image, 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.NewImageToPdfClient("demo", "demo")

    err := client.ConvertUrlToFile(
        "https://your-server.com/logo.png", "logo.pdf",
    )
    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:

MethodReturns
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

StatusWhat it meansWhat to do
400Invalid input, settings, or conversion failureRead the reason code and correct the input or settings.
401Missing credentials or an inactive licenseCheck your username, API key, and license status.
403Suspended service or no credits remainingCheck your account and available credits.
413Upload exceeds the 300 MB limitReduce the upload size.
429Request rate limit reachedWait and reduce the rate of new requests.
430Concurrent request limit reachedAllow active requests to finish before starting more.
503Temporary network issueCheck 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.

MethodUse
GetJobId()Identify the conversion in logs and support requests.
GetDebugLogUrl()The URL of the conversion debug log when logging is enabled.
GetOutputSize()Read the PDF 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 an image 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.NewImageToPdfClient("demo", "demo")

    client.SetDebugLog(true)
    defer func() {
        if debugLogURL := client.GetDebugLogUrl(); debugLogURL != "" {
            log.Printf("Debug log: %s", debugLogURL)
        }
    }()

    err := client.ConvertUrlToFile(
        "https://your-server.com/logo.png", "logo.pdf",
    )
    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

ProblemCheck
The image cannot be loadedCheck that the URL returns an image, rather than HTML or a login page, and is reachable from PDFCrowd's servers. For local files, check the path and read permissions.
The image is distorted or croppedCheck dimensions, crop settings and margins. Use "fit" with SetPrintPageMode() when setting an explicit output size.
The result looks blurryCheck the source image's pixel dimensions and how much it is enlarged. Increasing DPI cannot recover missing detail.
Text cannot be selected or searchedThe PDF retains the source image. Recognizing text from a scan requires a separate OCR step.

For help, contact support and include any available diagnostics, the client version, and enough detail to reproduce the problem.