Image to PDF API - Go

Convert various image formats to PDF in Go using the Pdfcrowd API v2. The API is easy to use and the integration takes only a couple of lines of code.

Installation

Install the client library from Github
go get github.com/pdfcrowd/pdfcrowd-go

Learn more about other install options.

Authentication

Authentication is needed in order to use the Pdfcrowd API. The credentials used for accessing the API are your Pdfcrowd username and the API key.
Sign up for a Free Trial

Examples

package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewImageToPdfClient("your_username", "your_apikey")

    // run the conversion and write the result to a file
    err := client.ConvertFileToFile("/path/to/logo.png", "logo.pdf")

    // check for a conversion error
    handleError(err)
}

func handleError(err error) {
    if err != nil {
        // report the error
        why, ok := err.(pdfcrowd.Error)
        if ok {
            os.Stderr.WriteString(fmt.Sprintf("Pdfcrowd Error: %s\n", why))
        } else {
            os.Stderr.WriteString(fmt.Sprintf("Generic Error: %s\n", err))
        }

        // handle the exception here or rethrow and handle it at a higher level
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewImageToPdfClient("your_username", "your_apikey")

    // create output file for conversion result
    outputFile, err := os.Create("logo.pdf")

    // check for a file creation error
    handleError(err)

    // close the output file
    defer outputFile.Close()

    // run the conversion and store the result into a pdf variable
    pdf, err := client.ConvertFile("/path/to/logo.png")

    // check for a conversion error
    handleError(err)

    // write the pdf into the output file
    _, err = outputFile.Write(pdf)

    // check for a file write error
    handleError(err)
}

func handleError(err error) {
    if err != nil {
        // report the error
        why, ok := err.(pdfcrowd.Error)
        if ok {
            os.Stderr.WriteString(fmt.Sprintf("Pdfcrowd Error: %s\n", why))
        } else {
            os.Stderr.WriteString(fmt.Sprintf("Generic Error: %s\n", err))
        }

        // handle the exception here or rethrow and handle it at a higher level
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewImageToPdfClient("your_username", "your_apikey")

    // create output stream for conversion result
    outputStream, err := os.Create("logo.pdf")

    // check for a file creation error
    handleError(err)

    // close the output stream
    defer outputStream.Close()

    // run the conversion and write the result into the output stream
    err = client.ConvertFileToStream("/path/to/logo.png", outputStream)

    // check for a conversion error
    handleError(err)
}

func handleError(err error) {
    if err != nil {
        // report the error
        why, ok := err.(pdfcrowd.Error)
        if ok {
            os.Stderr.WriteString(fmt.Sprintf("Pdfcrowd Error: %s\n", why))
        } else {
            os.Stderr.WriteString(fmt.Sprintf("Generic Error: %s\n", err))
        }

        // handle the exception here or rethrow and handle it at a higher level
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewImageToPdfClient("your_username", "your_apikey")

    // run the conversion and write the result to a file
    err := client.ConvertUrlToFile("http://pdfcrowd.com/static/images/logo.png", "logo.pdf")

    // check for a conversion error
    handleError(err)
}

func handleError(err error) {
    if err != nil {
        // report the error
        why, ok := err.(pdfcrowd.Error)
        if ok {
            os.Stderr.WriteString(fmt.Sprintf("Pdfcrowd Error: %s\n", why))
        } else {
            os.Stderr.WriteString(fmt.Sprintf("Generic Error: %s\n", err))
        }

        // handle the exception here or rethrow and handle it at a higher level
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewImageToPdfClient("your_username", "your_apikey")

    // create output file for conversion result
    outputFile, err := os.Create("logo.pdf")

    // check for a file creation error
    handleError(err)

    // close the output file
    defer outputFile.Close()

    // run the conversion and store the result into a pdf variable
    pdf, err := client.ConvertUrl("http://pdfcrowd.com/static/images/logo.png")

    // check for a conversion error
    handleError(err)

    // write the pdf into the output file
    _, err = outputFile.Write(pdf)

    // check for a file write error
    handleError(err)
}

func handleError(err error) {
    if err != nil {
        // report the error
        why, ok := err.(pdfcrowd.Error)
        if ok {
            os.Stderr.WriteString(fmt.Sprintf("Pdfcrowd Error: %s\n", why))
        } else {
            os.Stderr.WriteString(fmt.Sprintf("Generic Error: %s\n", err))
        }

        // handle the exception here or rethrow and handle it at a higher level
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewImageToPdfClient("your_username", "your_apikey")

    // create output stream for conversion result
    outputStream, err := os.Create("logo.pdf")

    // check for a file creation error
    handleError(err)

    // close the output stream
    defer outputStream.Close()

    // run the conversion and write the result into the output stream
    err = client.ConvertUrlToStream("http://pdfcrowd.com/static/images/logo.png", outputStream)

    // check for a conversion error
    handleError(err)
}

func handleError(err error) {
    if err != nil {
        // report the error
        why, ok := err.(pdfcrowd.Error)
        if ok {
            os.Stderr.WriteString(fmt.Sprintf("Pdfcrowd Error: %s\n", why))
        } else {
            os.Stderr.WriteString(fmt.Sprintf("Generic Error: %s\n", err))
        }

        // handle the exception here or rethrow and handle it at a higher level
        panic(err.Error())
    }
}
package main

import (
    "os"
    "fmt"
    "github.com/pdfcrowd/pdfcrowd-go"
    "io/ioutil"
)

func readFile(fileName string) []byte {
    content, err := ioutil.ReadFile(fileName)
    handleError(err)
    return content
}

func main() {
    // create the API client instance
    client := pdfcrowd.NewImageToPdfClient("your_username", "your_apikey")

    // run the conversion and write the result to a file
    err := client.ConvertRawDataToFile(readFile("/path/to/logo.png"), "logo.pdf")

    // check for a conversion error
    handleError(err)
}

func handleError(err error) {
    if err != nil {
        // report the error
        why, ok := err.(pdfcrowd.Error)
        if ok {
            os.Stderr.WriteString(fmt.Sprintf("Pdfcrowd Error: %s\n", why))
        } else {
            os.Stderr.WriteString(fmt.Sprintf("Generic Error: %s\n", err))
        }

        // handle the exception here or rethrow and handle it at a higher level
        panic(err.Error())
    }
}
package main

import (
    "os"
    "fmt"
    "github.com/pdfcrowd/pdfcrowd-go"
    "io/ioutil"
)

func readFile(fileName string) []byte {
    content, err := ioutil.ReadFile(fileName)
    handleError(err)
    return content
}

func main() {
    // create the API client instance
    client := pdfcrowd.NewImageToPdfClient("your_username", "your_apikey")

    // create output file for conversion result
    outputFile, err := os.Create("logo.pdf")

    // check for a file creation error
    handleError(err)

    // close the output file
    defer outputFile.Close()

    // run the conversion and store the result into a pdf variable
    pdf, err := client.ConvertRawData(readFile("/path/to/logo.png"))

    // check for a conversion error
    handleError(err)

    // write the pdf into the output file
    _, err = outputFile.Write(pdf)

    // check for a file write error
    handleError(err)
}

func handleError(err error) {
    if err != nil {
        // report the error
        why, ok := err.(pdfcrowd.Error)
        if ok {
            os.Stderr.WriteString(fmt.Sprintf("Pdfcrowd Error: %s\n", why))
        } else {
            os.Stderr.WriteString(fmt.Sprintf("Generic Error: %s\n", err))
        }

        // handle the exception here or rethrow and handle it at a higher level
        panic(err.Error())
    }
}
package main

import (
    "os"
    "fmt"
    "github.com/pdfcrowd/pdfcrowd-go"
    "io/ioutil"
)

func readFile(fileName string) []byte {
    content, err := ioutil.ReadFile(fileName)
    handleError(err)
    return content
}

func main() {
    // create the API client instance
    client := pdfcrowd.NewImageToPdfClient("your_username", "your_apikey")

    // create output stream for conversion result
    outputStream, err := os.Create("logo.pdf")

    // check for a file creation error
    handleError(err)

    // close the output stream
    defer outputStream.Close()

    // run the conversion and write the result into the output stream
    err = client.ConvertRawDataToStream(readFile("/path/to/logo.png"), outputStream)

    // check for a conversion error
    handleError(err)
}

func handleError(err error) {
    if err != nil {
        // report the error
        why, ok := err.(pdfcrowd.Error)
        if ok {
            os.Stderr.WriteString(fmt.Sprintf("Pdfcrowd Error: %s\n", why))
        } else {
            os.Stderr.WriteString(fmt.Sprintf("Generic Error: %s\n", err))
        }

        // handle the exception here or rethrow and handle it at a higher level
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewImageToPdfClient("your_username", "your_apikey")

    // configure the conversion
    client.SetDebugLog(true)

    // run the conversion and write the result to a file
    err := client.ConvertFileToFile("/path/to/logo.png", "logo.pdf")

    // check for a conversion error
    handleError(err)
    
    // print URL to the debug log
    fmt.Println("Debug log url:", client.GetDebugLogUrl())
    
    // print the number of available conversion credits in your account
    fmt.Println("Remaining credit count:", client.GetRemainingCreditCount())
    
    // print the number of credits consumed by the conversion
    fmt.Println("Consumed credit count:", client.GetConsumedCreditCount())
    
    // print the unique ID of the conversion
    fmt.Println("Job id:", client.GetJobId())
    
    // print the size of the output in bytes
    fmt.Println("Output size:", client.GetOutputSize())
}

func handleError(err error) {
    if err != nil {
        // report the error
        why, ok := err.(pdfcrowd.Error)
        if ok {
            os.Stderr.WriteString(fmt.Sprintf("Pdfcrowd Error: %s\n", why))
        } else {
            os.Stderr.WriteString(fmt.Sprintf("Generic Error: %s\n", err))
        }

        // handle the exception here or rethrow and handle it at a higher level
        panic(err.Error())
    }
}

Tips & Tricks

Error Handling

// call the API 

    // print error
    os.Stderr.WriteString(fmt.Sprintf("Pdfcrowd Error: %s\n", why))

    // print just error code
    os.Stderr.WriteString(fmt.Sprintf("Pdfcrowd Error Code: %v\n", why.getCode()))

    // print just error message
    os.Stderr.WriteString(fmt.Sprintf("Pdfcrowd Error Message: %v\n", why.getMessage()))

    // or handle the error in your way

Troubleshooting

API Reference - class ImageToPdfClient

Conversion from an image to PDF. All setter methods return ImageToPdfClient object unless otherwise specified.

Constructor

func NewImageToPdfClient(userName string, apiKey string) ImageToPdfClient
Constructor for the Pdfcrowd API client.
Parameter Description Default
userName
Your username at Pdfcrowd.
apiKey
Your API key.

 

Conversion Input

func (client *ImageToPdfClient) ConvertUrl(url string) ([]byte, error)
Convert an image.
Parameter Description Default
url
The address of the image to convert.
The supported protocols are http:// and https://.
Returns
  • []byte - Byte array containing the conversion output.
func (client *ImageToPdfClient) ConvertUrlToStream(url string, outStream io.Writer) error
Convert an image and write the result to an output stream.
Parameter Description Default
url
The address of the image to convert.
The supported protocols are http:// and https://.
outStream
The output stream that will contain the conversion output.
func (client *ImageToPdfClient) ConvertUrlToFile(url string, filePath string) error
Convert an image and write the result to a local file.
Parameter Description Default
url
The address of the image to convert.
The supported protocols are http:// and https://.
filePath
The output file path.
The string must not be empty.
func (client *ImageToPdfClient) ConvertFile(file string) ([]byte, error)
Convert a local file.
Parameter Description Default
file
The path to a local file to convert.
The file can be either a single file or an archive (.tar.gz, .tar.bz2, or .zip).
The file must exist and not be empty.
Returns
  • []byte - Byte array containing the conversion output.
func (client *ImageToPdfClient) ConvertFileToStream(file string, outStream io.Writer) error
Convert a local file and write the result to an output stream.
Parameter Description Default
file
The path to a local file to convert.
The file can be either a single file or an archive (.tar.gz, .tar.bz2, or .zip).
The file must exist and not be empty.
outStream
The output stream that will contain the conversion output.
func (client *ImageToPdfClient) ConvertFileToFile(file string, filePath string) error
Convert a local file and write the result to a local file.
Parameter Description Default
file
The path to a local file to convert.
The file can be either a single file or an archive (.tar.gz, .tar.bz2, or .zip).
The file must exist and not be empty.
filePath
The output file path.
The string must not be empty.
func (client *ImageToPdfClient) ConvertRawData(data []byte) ([]byte, error)
Convert raw data.
Parameter Description Default
data
The raw content to be converted.
Returns
  • []byte - Byte array with the output.
func (client *ImageToPdfClient) ConvertRawDataToStream(data []byte, outStream io.Writer) error
Convert raw data and write the result to an output stream.
Parameter Description Default
data
The raw content to be converted.
outStream
The output stream that will contain the conversion output.
func (client *ImageToPdfClient) ConvertRawDataToFile(data []byte, filePath string) error
Convert raw data to a file.
Parameter Description Default
data
The raw content to be converted.
filePath
The output file path.
The string must not be empty.

 

Image operations

Settings used for operations with images.

func (client *ImageToPdfClient) SetResize(resize string) *ImageToPdfClient
Resize the image.
Parameter Description Default
resize
The resize percentage or new image dimensions.
100%
Examples:
  • SetResize("200%")
  • SetResize("1024x768")
func (client *ImageToPdfClient) SetRotate(rotate string) *ImageToPdfClient
Rotate the image.
Parameter Description Default
rotate
The rotation specified in degrees.
0

 

Miscellaneous

func (client *ImageToPdfClient) SetDebugLog(debugLog bool) *ImageToPdfClient
Turn on the debug logging. Details about the conversion are stored in the debug log. The URL of the log can be obtained from the getDebugLogUrl method or available in conversion statistics.
Parameter Description Default
debugLog
Set to true to enable the debug logging.
false
func (client *ImageToPdfClient) GetDebugLogUrl() string
Get the URL of the debug log for the last conversion.
Returns
  • string - The link to the debug log.
func (client *ImageToPdfClient) GetRemainingCreditCount() int
Get the number of conversion credits available in your account.
The returned value can differ from the actual count if you run parallel conversions.
The special value 999999 is returned if the information is not available.
Returns
  • int - The number of credits.
func (client *ImageToPdfClient) GetConsumedCreditCount() int
Get the number of credits consumed by the last conversion.
Returns
  • int - The number of credits.
func (client *ImageToPdfClient) GetJobId() string
Get the job id.
Returns
  • string - The unique job identifier.
func (client *ImageToPdfClient) GetOutputSize() int
Get the size of the output in bytes.
Returns
  • int - The count of bytes.
func (client *ImageToPdfClient) SetTag(tag string) *ImageToPdfClient
Tag the conversion with a custom value. The tag is used in conversion statistics. A value longer than 32 characters is cut off.
Parameter Description Default
tag
A string with the custom tag.
func (client *ImageToPdfClient) SetHttpProxy(httpProxy string) *ImageToPdfClient
A proxy server used by Pdfcrowd conversion process for accessing the source URLs with HTTP scheme. It can help to circumvent regional restrictions or provide limited access to your intranet.
Parameter Description Default
httpProxy
The value must have format DOMAIN_OR_IP_ADDRESS:PORT.
Examples:
  • SetHttpProxy("myproxy.com:8080")
  • SetHttpProxy("113.25.84.10:33333")
func (client *ImageToPdfClient) SetHttpsProxy(httpsProxy string) *ImageToPdfClient
A proxy server used by Pdfcrowd conversion process for accessing the source URLs with HTTPS scheme. It can help to circumvent regional restrictions or provide limited access to your intranet.
Parameter Description Default
httpsProxy
The value must have format DOMAIN_OR_IP_ADDRESS:PORT.
Examples:
  • SetHttpsProxy("myproxy.com:443")
  • SetHttpsProxy("113.25.84.10:44333")

 

API Client Options

func (client *ImageToPdfClient) SetUseHttp(useHttp bool) *ImageToPdfClient
Specifies if the client communicates over HTTP or HTTPS with Pdfcrowd API.
Parameter Description Default
useHttp
Set to true to use HTTP.
false
func (client *ImageToPdfClient) SetUserAgent(userAgent string) *ImageToPdfClient
Set a custom user agent HTTP header. It can be usefull if you are behind some proxy or firewall.
Parameter Description Default
userAgent
The user agent string.
pdfcrowd_go_client/4.4.1 (http://pdfcrowd.com)
func (client *ImageToPdfClient) SetProxy(host string, port int, userName string, password string) *ImageToPdfClient
Specifies an HTTP proxy that the API client library will use to connect to the internet.
Parameter Description Default
host
The proxy hostname.
port
The proxy port.
userName
The username.
password
The password.
func (client *ImageToPdfClient) SetRetryCount(retryCount int) *ImageToPdfClient
Specifies the number of retries when the 502 HTTP status code is received. The 502 status code indicates a temporary network issue. This feature can be disabled by setting to 0.
Parameter Description Default
retryCount
Number of retries wanted.
1