HTML to PDF API - Go

Learn how to convert web pages and HTML documents 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.NewHtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d")

    // run the conversion and write the result to a file
    err := client.ConvertUrlToFile("http://www.example.com", "example.pdf")

    // check for the 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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewHtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d")

    // run the conversion and store the result into the "pdf" variable
    pdf, err := client.ConvertUrl("http://www.example.com")

    // check for the conversion error
    handleError(err)

    // at this point the "pdf" variable contains PDF raw data and
    // can be sent in an HTTP response, saved to a file, etc.
}

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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewHtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d")

    // create an output stream for the conversion result
    outputStream, err := os.Create("example.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://www.example.com", outputStream)

    // check for the 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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewHtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d")

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

    // check for the 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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewHtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d")

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

    // check for the conversion error
    handleError(err)

    // at this point the "pdf" variable contains PDF raw data and
    // can be sent in an HTTP response, saved to a file, etc.
}

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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewHtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d")

    // create an output stream for the conversion result
    outputStream, err := os.Create("MyLayout.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/MyLayout.html", outputStream)

    // check for the 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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewHtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d")

    // run the conversion and write the result to a file
    err := client.ConvertStringToFile("<html><body><h1>Hello World!</h1></body></html>", "HelloWorld.pdf")

    // check for the 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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewHtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d")

    // run the conversion and store the result into the "pdf" variable
    pdf, err := client.ConvertString("<html><body><h1>Hello World!</h1></body></html>")

    // check for the conversion error
    handleError(err)

    // at this point the "pdf" variable contains PDF raw data and
    // can be sent in an HTTP response, saved to a file, etc.
}

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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewHtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d")

    // create an output stream for the conversion result
    outputStream, err := os.Create("HelloWorld.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.ConvertStringToStream("<html><body><h1>Hello World!</h1></body></html>", outputStream)

    // check for the 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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewHtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d")

    // configure the conversion
    client.SetDebugLog(true)

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

    // check for the 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 total number of pages in the output document
    fmt.Println("Page count:", client.GetPageCount())
    
    // 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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}

Advanced Examples

package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewHtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d")

    // configure the conversion
    client.SetPageSize("Letter")
    client.SetOrientation("landscape")
    client.SetNoMargins(true)

    // run the conversion and write the result to a file
    err := client.ConvertUrlToFile("http://www.example.com", "letter_landscape.pdf")

    // check for the 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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewHtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d")

    // configure the conversion
    client.SetHeaderHeight("15mm")
    client.SetFooterHeight("10mm")
    client.SetHeaderHtml("<a class='pdfcrowd-source-url' data-pdfcrowd-placement='href-and-content'></a>")
    client.SetFooterHtml("<center><span class='pdfcrowd-page-number'></span></center>")
    client.SetMarginTop("0")
    client.SetMarginBottom("0")

    // run the conversion and write the result to a file
    err := client.ConvertUrlToFile("http://www.example.com", "header_footer.pdf")

    // check for the 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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewHtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d")

    // configure the conversion
    client.SetScaleFactor(300)

    // run the conversion and write the result to a file
    err := client.ConvertUrlToFile("http://www.example.com", "zoom_300.pdf")

    // check for the 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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewHtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d")

    // configure the conversion
    client.SetAuthor("Pdfcrowd")
    client.SetTitle("Hello World")
    client.SetSubject("Demo")
    client.SetKeywords("Pdfcrowd,demo")

    // run the conversion and write the result to a file
    err := client.ConvertUrlToFile("http://www.example.com", "with_metadata.pdf")

    // check for the 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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewHtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d")

    // configure the conversion
    client.SetPageLayout("single-page")
    client.SetPageMode("full-screen")
    client.SetInitialZoomType("fit-page")
    client.SetOrientation("landscape")
    client.SetNoMargins(true)

    // run the conversion and write the result to a file
    err := client.ConvertUrlToFile("https://pdfcrowd.com/doc/api/", "slide_show.pdf")

    // check for the 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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewHtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d")

    // configure the conversion
    client.SetElementToConvert("#main")

    // run the conversion and write the result to a file
    err := client.ConvertUrlToFile("https://pdfcrowd.com/doc/api/", "html_part.pdf")

    // check for the 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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewHtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d")

    // configure the conversion
    client.SetCustomJavascript("el=document.createElement('h2'); el.textContent='Hello from Pdfcrowd API'; el.style.color='red'; el_before=document.getElementsByTagName('h1')[0]; el_before.parentNode.insertBefore(el, el_before.nextSibling)")

    // run the conversion and write the result to a file
    err := client.ConvertUrlToFile("http://www.example.com", "html_inject.pdf")

    // check for the 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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewHtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d")

    // configure the conversion
    client.SetViewportWidth(992)
    client.SetRenderingMode("viewport")
    client.SetSmartScalingMode("viewport-fit")
    client.SetNoMargins(true)

    // run the conversion and write the result to a file
    err := client.ConvertUrlToFile("https://getbootstrap.com/", "bootstrap.pdf")

    // check for the 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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}
package main

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

func addFileToArchive(fName string, fPath string, writer *zip.Writer) {
    fStream, err := os.Open(fPath)
    handleError(err)

    var body []byte
    body, err = ioutil.ReadAll(fStream)
    handleError(err)

    var ioWriter io.Writer
    ioWriter, err = writer.Create(fName)
    handleError(err)

    _, err = ioWriter.Write(body)
    handleError(err)
}

func main() {
    // create the API client instance
    client := pdfcrowd.NewHtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d")

    // create ZIP archive
    var buffer bytes.Buffer
    archive := zip.NewWriter(&buffer)

    // add HTML content to the archive
    ioWriter, errHtml := archive.Create("index.html")
    handleError(errHtml)

    _, errHtml = ioWriter.Write([]byte(`<html>
        <head>
            <style>
             @font-face
             {
                 font-family: 'OpenSans';
                 src: url(fonts/OpenSans.ttf) format('truetype');
             }
    
             h1
             {
                 font-family: OpenSans;
             }
            </style>
        </head>
        <body>
            <h1>Hello World</h1>
            <img src='images/logo.png'>
        </body>
    </html>`))
    handleError(errHtml)

    // add required local files to the archive
    addFileToArchive("fonts/OpenSans.ttf", "/your-path-to/fonts/OpenSans.ttf", archive)
    addFileToArchive("images/logo.png", "/your-path-to/images/logo.png", archive)

    handleError(archive.Flush())
    handleError(archive.Close())

    inStream := bytes.NewReader(buffer.Bytes())

    // create an output stream for the conversion result
    outputStream, err := os.Create("HelloFromZip.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.ConvertStreamToStream(inStream, outputStream)

    // check for the 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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewHtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d")

    // configure the conversion
    client.SetCustomJavascript("libPdfcrowd.highlightHtmlElements({backgroundColor: 'rgba(255, 191, 0, 0.1)', borderColor:null})")

    // run the conversion and write the result to a file
    err := client.ConvertUrlToFile("http://www.example.com", "highlight_background.pdf")

    // check for the 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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewHtmlToPdfClient("demo", "ce544b6ea52a5621fb9d55f8b542d14d")

    // configure the conversion
    client.SetCustomJavascript("libPdfcrowd.highlightHtmlElements({borderColor: 'orange', backgroundColor: null, padding: '4px', margin: '4px'})")

    // run the conversion and write the result to a file
    err := client.ConvertUrlToFile("http://www.example.com", "highlight_borders.pdf")

    // check for the 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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}

Integration Examples

The API can be easily integrated into your environment. You can have our interactive API Playground autogenerate the integration code for you:

Common Customizations

The API lets you convert a web page, a local HTML file, or a string containing HTML. The result of the conversion can be stored to a local file, to a stream object or to a variable. See the conversion input section for more details.

The best way to start with the API is to choose one of the examples and once you get it working, you can further customize the code. You can find the most common customizations in the table below.

Page size Change the page size with SetPageSize or SetPageDimensions. Pass -1 to SetPageHeight to get a single page PDF containing the whole document.
Page orientation Change the page orientation to landscape with SetOrientation.
Page margins Adjust the page margins with SetPageMargins.
Headers and footers Add headers and footers with SetHeaderHtml and SetFooterHtml. Set the height with SetFooterHeight and SetHeaderHeight.
Zoom Scale the HTML contents with SetScaleFactor.
Hide or remove elements You can use the following classes in your HTML code to hide or remove elements from the output:
  • pdfcrowd-remove - sets display:none!important on the element
  • pdfcrowd-hide - sets visibility:hidden!important on the element
Use @media print You can switch to the print version of the page (if it exists) with SetUsePrintMedia.
Force page break You can force a page break with
<div style="page-break-before:always"></div>
Avoid page break You can avoid a page break inside an element with the following CSS
th, td, img { page-break-inside:avoid }
Run custom JavaScript You can use SetOnLoadJavascript or SetCustomJavascript to alter the HTML contents with a custom JavaScript. In addition to the standard browser APIs, the custom JavaScript code can use helper functions from our JavaScript library.
Custom CSS styling You can alter CSS styling used during conversion with a custom JavaScript or using the pdfcrowd-body CSS class, which is automatically set on the HTML element. You can, for example, set the H1 height to 48px by adding the following line to your CSS:
.pdfcrowd-body h1 { font-size: 48px; }

Template Rendering

The API enables rendering of HTML templates. The template syntax is based on the Jinja template rendering engine.

The most common constructs are:

  • Data rendering: Invoice: {{ invoice.number }}
  • For loop: {% for invoice in invoices %} ... {% endfor %}
  • If statement: {% if invoice.total > 100 %} ... {% endif %}
  • Data filter: {{ invoice.to.first_name|capitalize }}

The supported input data formats are JSON, XML, CSV and YAML. The data can be uploaded from a file or from a string variable.

Supported template filters: capitalize, center, default, escape, first, forceescape, format, indent, join, last, length, list, lower, replace, reverse, safe, slice, sort, string, striptags, title, trim, truncate, unique, upper, wordcount, wordwrap.

Template Rendering Examples

package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewHtmlToPdfClient("{{ user_name }}", "{{ api_key }}")

    // configure the conversion
    client.SetDataString(`{
            "name": "World",
            "product": "Pdfcrowd API"
        }`)

    // run the conversion and write the result to a file
    err := client.ConvertStringToFile("Hello {{ name }} from {{ product }}", "output.pdf")

    // check for the 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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewHtmlToPdfClient("{{ user_name }}", "{{ api_key }}")

    // configure the conversion
    client.SetDataString(`<?xml version="1.0" encoding="UTF-8"?>
        <data>
          <name>World</name>
          <product>Pdfcrowd API</product>
        </data>`)

    // run the conversion and write the result to a file
    err := client.ConvertStringToFile("Hello {{ data.name }} from {{ data.product }}", "output.pdf")

    // check for the 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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewHtmlToPdfClient("{{ user_name }}", "{{ api_key }}")

    // configure the conversion
    client.SetDataString(`name: World
product: Pdfcrowd API`)

    // run the conversion and write the result to a file
    err := client.ConvertStringToFile("Hello {{ name }} from {{ product }}", "output.pdf")

    // check for the 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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}
package main

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

func main() {
    // create the API client instance
    client := pdfcrowd.NewHtmlToPdfClient("{{ user_name }}", "{{ api_key }}")

    // configure the conversion
    client.SetDataString(`name,product
World,Pdfcrowd API`)

    // run the conversion and write the result to a file
    err := client.ConvertStringToFile("Hello {{ name }} from {{ product }}", "output.pdf")

    // check for the 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))
        }

        // rethrow or handle the exception
        panic(err.Error())
    }
}

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

  • Check API Status Codes in case of the error code is returned.
  • You can use SetDebugLog and GetDebugLogUrl to get detailed info about the conversion, such as conversion errors, time, console output.
  • You can use our JavaScript library to resolve rendering problems, such as missing content or blank pages.
    Just use SetCustomJavascript with libPdfcrowd.highlightHtmlElements method call to visualize all HTML elements. See the example and helper JavaScript library documentation.
  • Take a look at the FAQ section.

API Reference - class HtmlToPdfClient

Conversion from HTML to PDF. All setter methods return HtmlToPdfClient object unless otherwise specified.

Constructor

func NewHtmlToPdfClient(userName string, apiKey string) HtmlToPdfClient
Constructor for the Pdfcrowd API client.
userName
Your username at Pdfcrowd.
apiKey
Your API key.

 

Conversion Input

func (client *HtmlToPdfClient) ConvertUrl(url string) ([]byte, error)
Convert a web page.
url
The address of the web page to convert.
The supported protocols are http:// and https://.
Returns
  • []byte - Byte array containing the conversion output.
func (client *HtmlToPdfClient) ConvertUrlToStream(url string, outStream io.Writer) error
Convert a web page and write the result to an output stream.
url
The address of the web page to convert.
The supported protocols are http:// and https://.
outStream
The output stream that will contain the conversion output.
func (client *HtmlToPdfClient) ConvertUrlToFile(url string, filePath string) error
Convert a web page and write the result to a local file.
url
The address of the web page to convert.
The supported protocols are http:// and https://.
filePath
The output file path.
The string must not be empty.
func (client *HtmlToPdfClient) ConvertFile(file string) ([]byte, error)
Convert a local file.
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).
If the HTML document refers to local external assets (images, style sheets, javascript), zip the document together with the assets.
The file must exist and not be empty.
The file name must have a valid extension.
Returns
  • []byte - Byte array containing the conversion output.
func (client *HtmlToPdfClient) ConvertFileToStream(file string, outStream io.Writer) error
Convert a local file and write the result to an output stream.
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).
If the HTML document refers to local external assets (images, style sheets, javascript), zip the document together with the assets.
The file must exist and not be empty.
The file name must have a valid extension.
outStream
The output stream that will contain the conversion output.
func (client *HtmlToPdfClient) ConvertFileToFile(file string, filePath string) error
Convert a local file and write the result to a local file.
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).
If the HTML document refers to local external assets (images, style sheets, javascript), zip the document together with the assets.
The file must exist and not be empty.
The file name must have a valid extension.
filePath
The output file path.
The string must not be empty.
func (client *HtmlToPdfClient) ConvertString(text string) ([]byte, error)
Convert a string.
text
The string content to convert.
The string must not be empty.
Returns
  • []byte - Byte array containing the conversion output.
func (client *HtmlToPdfClient) ConvertStringToStream(text string, outStream io.Writer) error
Convert a string and write the output to an output stream.
text
The string content to convert.
The string must not be empty.
outStream
The output stream that will contain the conversion output.
func (client *HtmlToPdfClient) ConvertStringToFile(text string, filePath string) error
Convert a string and write the output to a file.
text
The string content to convert.
The string must not be empty.
filePath
The output file path.
The string must not be empty.
func (client *HtmlToPdfClient) ConvertStream(inStream io.Reader) ([]byte, error)
Convert the contents of an input stream.
inStream
The input stream with source data.
The stream can contain either HTML code or an archive (.zip, .tar.gz, .tar.bz2).
The archive can contain HTML code and its external assets (images, style sheets, javascript).
Returns
  • []byte - Byte array containing the conversion output.
func (client *HtmlToPdfClient) ConvertStreamToStream(inStream io.Reader, outStream io.Writer) error
Convert the contents of an input stream and write the result to an output stream.
inStream
The input stream with source data.
The stream can contain either HTML code or an archive (.zip, .tar.gz, .tar.bz2).
The archive can contain HTML code and its external assets (images, style sheets, javascript).
outStream
The output stream that will contain the conversion output.
func (client *HtmlToPdfClient) ConvertStreamToFile(inStream io.Reader, filePath string) error
Convert the contents of an input stream and write the result to a local file.
inStream
The input stream with source data.
The stream can contain either HTML code or an archive (.zip, .tar.gz, .tar.bz2).
The archive can contain HTML code and its external assets (images, style sheets, javascript).
filePath
The output file path.
The string must not be empty.

 

Page Setup

func (client *HtmlToPdfClient) SetPageSize(size string) *HtmlToPdfClient
Set the output page size.
size
Allowed values:
  • A0
  • A1
  • A2
  • A3
  • A4
  • A5
  • A6
  • Letter
Default: A4
func (client *HtmlToPdfClient) SetPageWidth(width string) *HtmlToPdfClient
Set the output page width. The safe maximum is 200in otherwise some PDF viewers may be unable to open the PDF.
width
Can be specified in inches (in), millimeters (mm), centimeters (cm), or points (pt).
Default: 8.27in
Examples:
  • SetPageWidth("300mm")
  • SetPageWidth("9.5in")
func (client *HtmlToPdfClient) SetPageHeight(height string) *HtmlToPdfClient
Set the output page height. Use -1 for a single page PDF. The safe maximum is 200in otherwise some PDF viewers may be unable to open the PDF.
height
Can be -1 or specified in inches (in), millimeters (mm), centimeters (cm), or points (pt).
Default: 11.7in
Examples:
  • SetPageHeight("350mm")
  • SetPageHeight("15.25in")
  • The height of the page is calculated automatically so that the whole document fits into it.
    SetPageHeight("-1")
func (client *HtmlToPdfClient) SetPageDimensions(width string, height string) *HtmlToPdfClient
Set the output page dimensions.
width
Set the output page width. The safe maximum is 200in otherwise some PDF viewers may be unable to open the PDF.
Can be specified in inches (in), millimeters (mm), centimeters (cm), or points (pt).
Default: 8.27in
height
Set the output page height. Use -1 for a single page PDF. The safe maximum is 200in otherwise some PDF viewers may be unable to open the PDF.
Can be -1 or specified in inches (in), millimeters (mm), centimeters (cm), or points (pt).
Default: 11.7in
Examples:
  • SetPageDimensions("300mm", "350mm")
  • SetPageDimensions("9.5in", "15.25in")
  • SetPageDimensions("372mm", "520pt")
func (client *HtmlToPdfClient) SetOrientation(orientation string) *HtmlToPdfClient
Set the output page orientation.
orientation
Allowed values:
  • landscape
  • portrait
Default: portrait
func (client *HtmlToPdfClient) SetMarginTop(top string) *HtmlToPdfClient
Set the output page top margin.
top
Can be specified in inches (in), millimeters (mm), centimeters (cm), or points (pt).
Default: 0.4in
Examples:
  • SetMarginTop("1in")
  • SetMarginTop("2.5cm")
func (client *HtmlToPdfClient) SetMarginRight(right string) *HtmlToPdfClient
Set the output page right margin.
right
Can be specified in inches (in), millimeters (mm), centimeters (cm), or points (pt).
Default: 0.4in
Examples:
  • SetMarginRight("1in")
  • SetMarginRight("2.5cm")
func (client *HtmlToPdfClient) SetMarginBottom(bottom string) *HtmlToPdfClient
Set the output page bottom margin.
bottom
Can be specified in inches (in), millimeters (mm), centimeters (cm), or points (pt).
Default: 0.4in
Examples:
  • SetMarginBottom("1in")
  • SetMarginBottom("2.5cm")
func (client *HtmlToPdfClient) SetMarginLeft(left string) *HtmlToPdfClient
Set the output page left margin.
left
Can be specified in inches (in), millimeters (mm), centimeters (cm), or points (pt).
Default: 0.4in
Examples:
  • SetMarginLeft("1in")
  • SetMarginLeft("2.5cm")
func (client *HtmlToPdfClient) SetNoMargins(value bool) *HtmlToPdfClient
Disable page margins.
value
Set to true to disable margins.
Default: false
func (client *HtmlToPdfClient) SetPageMargins(top string, right string, bottom string, left string) *HtmlToPdfClient
Set the output page margins.
top
Set the output page top margin.
Can be specified in inches (in), millimeters (mm), centimeters (cm), or points (pt).
Default: 0.4in
right
Set the output page right margin.
Can be specified in inches (in), millimeters (mm), centimeters (cm), or points (pt).
Default: 0.4in
bottom
Set the output page bottom margin.
Can be specified in inches (in), millimeters (mm), centimeters (cm), or points (pt).
Default: 0.4in
left
Set the output page left margin.
Can be specified in inches (in), millimeters (mm), centimeters (cm), or points (pt).
Default: 0.4in
func (client *HtmlToPdfClient) SetPrintPageRange(pages string) *HtmlToPdfClient
Set the page range to print.
pages
A comma separated list of page numbers or ranges.
Examples:
  • Just the second page is printed.
    SetPrintPageRange("2")
  • The first and the third page are printed.
    SetPrintPageRange("1,3")
  • Everything except the first page is printed.
    SetPrintPageRange("2-")
  • Just first 3 pages are printed.
    SetPrintPageRange("-3")
  • Pages 3, 6, 7, 8 and 9 are printed.
    SetPrintPageRange("3,6-9")
func (client *HtmlToPdfClient) SetPageNumberingOffset(offset int) *HtmlToPdfClient
Set an offset between physical and logical page numbers.
offset
Integer specifying page offset.
Default: 0
Examples:
  • The page numbering will start with 0.
    SetPageNumberingOffset(1)
  • The page numbering will start with 11 on the first page. It can be useful for joining documents.
    SetPageNumberingOffset(-10)
func (client *HtmlToPdfClient) SetContentAreaX(x string) *HtmlToPdfClient
Set the top left X coordinate of the content area. It is relative to the top left X coordinate of the print area.
x
Can be specified in inches (in), millimeters (mm), centimeters (cm), or points (pt). It may contain a negative value.
Default: 0in
Examples:
  • SetContentAreaX("-1in")
  • SetContentAreaX("2.5cm")
func (client *HtmlToPdfClient) SetContentAreaY(y string) *HtmlToPdfClient
Set the top left Y coordinate of the content area. It is relative to the top left Y coordinate of the print area.
y
Can be specified in inches (in), millimeters (mm), centimeters (cm), or points (pt). It may contain a negative value.
Default: 0in
Examples:
  • SetContentAreaY("-1in")
  • SetContentAreaY("2.5cm")
func (client *HtmlToPdfClient) SetContentAreaWidth(width string) *HtmlToPdfClient
Set the width of the content area. It should be at least 1 inch.
width
Can be specified in inches (in), millimeters (mm), centimeters (cm), or points (pt).
Default: The width of the print area.
Examples:
  • SetContentAreaWidth("8in")
  • SetContentAreaWidth("25cm")
func (client *HtmlToPdfClient) SetContentAreaHeight(height string) *HtmlToPdfClient
Set the height of the content area. It should be at least 1 inch.
height
Can be specified in inches (in), millimeters (mm), centimeters (cm), or points (pt).
Default: The height of the print area.
Examples:
  • SetContentAreaHeight("8in")
  • SetContentAreaHeight("25cm")
func (client *HtmlToPdfClient) SetContentArea(x string, y string, width string, height string) *HtmlToPdfClient
Set the content area position and size. The content area enables to specify a web page area to be converted.
x
Set the top left X coordinate of the content area. It is relative to the top left X coordinate of the print area.
Can be specified in inches (in), millimeters (mm), centimeters (cm), or points (pt). It may contain a negative value.
Default: 0in
y
Set the top left Y coordinate of the content area. It is relative to the top left Y coordinate of the print area.
Can be specified in inches (in), millimeters (mm), centimeters (cm), or points (pt). It may contain a negative value.
Default: 0in
width
Set the width of the content area. It should be at least 1 inch.
Can be specified in inches (in), millimeters (mm), centimeters (cm), or points (pt).
Default: The width of the print area.
height
Set the height of the content area. It should be at least 1 inch.
Can be specified in inches (in), millimeters (mm), centimeters (cm), or points (pt).
Default: The height of the print area.
func (client *HtmlToPdfClient) SetCssPageRuleMode(mode string) *HtmlToPdfClient
Specifies behavior in presence of CSS @page rules. It may affect the page size, margins and orientation.
Availability: API client >= 5.0.0, converter >= 20.10. See versioning.
mode
The page rule mode.
Allowed values:
  • default
    The Pdfcrowd API page settings are preferred.
  • mode1
    The converter version 18.10 mode.
  • mode2
    CSS @page rule is preferred.
Default: default

 

func (client *HtmlToPdfClient) SetHeaderUrl(url string) *HtmlToPdfClient
Load an HTML code from the specified URL and use it as the page header. The following classes can be used in the HTML. The content of the respective elements will be expanded as follows:
  • pdfcrowd-page-count - the total page count of printed pages
  • pdfcrowd-page-number - the current page number
  • pdfcrowd-source-url - the source URL of a converted document
The following attributes can be used:
  • data-pdfcrowd-number-format - specifies the type of the used numerals. Allowed values:
    • arabic - Arabic numerals, they are used by default
    • roman - Roman numerals
    • eastern-arabic - Eastern Arabic numerals
    • bengali - Bengali numerals
    • devanagari - Devanagari numerals
    • thai - Thai numerals
    • east-asia - Chinese, Vietnamese, Japanese and Korean numerals
    • chinese-formal - Chinese formal numerals
    Please contact us if you need another type of numerals.
    Example:
    <span class='pdfcrowd-page-number' data-pdfcrowd-number-format='roman'></span>
  • data-pdfcrowd-placement - specifies where to place the source URL. Allowed values:
    • The URL is inserted to the content
      • Example: <span class='pdfcrowd-source-url'></span>
        will produce <span>http://example.com</span>
    • href - the URL is set to the href attribute
      • Example: <a class='pdfcrowd-source-url' data-pdfcrowd-placement='href'>Link to source</a>
        will produce <a href='http://example.com'>Link to source</a>
    • href-and-content - the URL is set to the href attribute and to the content
      • Example: <a class='pdfcrowd-source-url' data-pdfcrowd-placement='href-and-content'></a>
        will produce <a href='http://example.com'>http://example.com</a>
url
The supported protocols are http:// and https://.
Example:
  • SetHeaderUrl("http://myserver.com/header.html")
func (client *HtmlToPdfClient) SetHeaderHtml(html string) *HtmlToPdfClient
Use the specified HTML code as the page header. The following classes can be used in the HTML. The content of the respective elements will be expanded as follows:
  • pdfcrowd-page-count - the total page count of printed pages
  • pdfcrowd-page-number - the current page number
  • pdfcrowd-source-url - the source URL of a converted document
The following attributes can be used:
  • data-pdfcrowd-number-format - specifies the type of the used numerals. Allowed values:
    • arabic - Arabic numerals, they are used by default
    • roman - Roman numerals
    • eastern-arabic - Eastern Arabic numerals
    • bengali - Bengali numerals
    • devanagari - Devanagari numerals
    • thai - Thai numerals
    • east-asia - Chinese, Vietnamese, Japanese and Korean numerals
    • chinese-formal - Chinese formal numerals
    Please contact us if you need another type of numerals.
    Example:
    <span class='pdfcrowd-page-number' data-pdfcrowd-number-format='roman'></span>
  • data-pdfcrowd-placement - specifies where to place the source URL. Allowed values:
    • The URL is inserted to the content
      • Example: <span class='pdfcrowd-source-url'></span>
        will produce <span>http://example.com</span>
    • href - the URL is set to the href attribute
      • Example: <a class='pdfcrowd-source-url' data-pdfcrowd-placement='href'>Link to source</a>
        will produce <a href='http://example.com'>Link to source</a>
    • href-and-content - the URL is set to the href attribute and to the content
      • Example: <a class='pdfcrowd-source-url' data-pdfcrowd-placement='href-and-content'></a>
        will produce <a href='http://example.com'>http://example.com</a>
html
The string must not be empty.
Example:
  • It displays the page number and the total page count.
    SetHeaderHtml("Page <span class='pdfcrowd-page-number'></span> of <span class='pdfcrowd-page-count'></span> pages")
func (client *HtmlToPdfClient) SetHeaderHeight(height string) *HtmlToPdfClient
Set the header height.
height
Can be specified in inches (in), millimeters (mm), centimeters (cm), or points (pt).
Default: 0.5in
Examples:
  • SetHeaderHeight("30mm")
  • SetHeaderHeight("1in")
Load an HTML code from the specified URL and use it as the page footer. The following classes can be used in the HTML. The content of the respective elements will be expanded as follows:
  • pdfcrowd-page-count - the total page count of printed pages
  • pdfcrowd-page-number - the current page number
  • pdfcrowd-source-url - the source URL of a converted document
The following attributes can be used:
  • data-pdfcrowd-number-format - specifies the type of the used numerals. Allowed values:
    • arabic - Arabic numerals, they are used by default
    • roman - Roman numerals
    • eastern-arabic - Eastern Arabic numerals
    • bengali - Bengali numerals
    • devanagari - Devanagari numerals
    • thai - Thai numerals
    • east-asia - Chinese, Vietnamese, Japanese and Korean numerals
    • chinese-formal - Chinese formal numerals
    Please contact us if you need another type of numerals.
    Example:
    <span class='pdfcrowd-page-number' data-pdfcrowd-number-format='roman'></span>
  • data-pdfcrowd-placement - specifies where to place the source URL. Allowed values:
    • The URL is inserted to the content
      • Example: <span class='pdfcrowd-source-url'></span>
        will produce <span>http://example.com</span>
    • href - the URL is set to the href attribute
      • Example: <a class='pdfcrowd-source-url' data-pdfcrowd-placement='href'>Link to source</a>
        will produce <a href='http://example.com'>Link to source</a>
    • href-and-content - the URL is set to the href attribute and to the content
      • Example: <a class='pdfcrowd-source-url' data-pdfcrowd-placement='href-and-content'></a>
        will produce <a href='http://example.com'>http://example.com</a>
Example:
  • SetFooterUrl("http://myserver.com/header.html")
Use the specified HTML as the page footer. The following classes can be used in the HTML. The content of the respective elements will be expanded as follows:
  • pdfcrowd-page-count - the total page count of printed pages
  • pdfcrowd-page-number - the current page number
  • pdfcrowd-source-url - the source URL of a converted document
The following attributes can be used:
  • data-pdfcrowd-number-format - specifies the type of the used numerals. Allowed values:
    • arabic - Arabic numerals, they are used by default
    • roman - Roman numerals
    • eastern-arabic - Eastern Arabic numerals
    • bengali - Bengali numerals
    • devanagari - Devanagari numerals
    • thai - Thai numerals
    • east-asia - Chinese, Vietnamese, Japanese and Korean numerals
    • chinese-formal - Chinese formal numerals
    Please contact us if you need another type of numerals.
    Example:
    <span class='pdfcrowd-page-number' data-pdfcrowd-number-format='roman'></span>
  • data-pdfcrowd-placement - specifies where to place the source URL. Allowed values:
    • The URL is inserted to the content
      • Example: <span class='pdfcrowd-source-url'></span>
        will produce <span>http://example.com</span>
    • href - the URL is set to the href attribute
      • Example: <a class='pdfcrowd-source-url' data-pdfcrowd-placement='href'>Link to source</a>
        will produce <a href='http://example.com'>Link to source</a>
    • href-and-content - the URL is set to the href attribute and to the content
      • Example: <a class='pdfcrowd-source-url' data-pdfcrowd-placement='href-and-content'></a>
        will produce <a href='http://example.com'>http://example.com</a>
Example:
  • It displays the page number and the total page count.
    SetFooterHtml("Page <span class='pdfcrowd-page-number'></span> of <span class='pdfcrowd-page-count'></span> pages")
Set the footer height.
Examples:
  • SetFooterHeight("30mm")
  • SetFooterHeight("1in")
Disable horizontal page margins for header and footer. The header/footer contents width will be equal to the physical page width.
Availability: API client >= 5.0.0, converter >= 20.10. See versioning.
func (client *HtmlToPdfClient) SetExcludeHeaderOnPages(pages string) *HtmlToPdfClient
The page header is not printed on the specified pages.
pages
List of physical page numbers. Negative numbers count backwards from the last page: -1 is the last page, -2 is the last but one page, and so on.
A comma separated list of page numbers.
Examples:
  • The header is not printed on the second page.
    SetExcludeHeaderOnPages("2")
  • The header is not printed on the first and the last page.
    SetExcludeHeaderOnPages("1,-1")
The page footer is not printed on the specified pages.
Examples:
  • The footer is not printed on the second page.
    SetExcludeFooterOnPages("2")
  • The footer is not printed on the first and the last page.
    SetExcludeFooterOnPages("1,-1")
Set the scaling factor (zoom) for the header and footer.

 

Watermark & Background

func (client *HtmlToPdfClient) SetPageWatermark(watermark string) *HtmlToPdfClient
Apply the first page of the watermark PDF to every page of the output PDF.
watermark
The file path to a local watermark PDF file.
The file must exist and not be empty.
func (client *HtmlToPdfClient) SetPageWatermarkUrl(url string) *HtmlToPdfClient
Load a watermark PDF from the specified URL and apply the first page of the watermark PDF to every page of the output PDF.
url
The supported protocols are http:// and https://.
Example:
  • SetPageWatermarkUrl("http://myserver.com/watermark.pdf")
func (client *HtmlToPdfClient) SetMultipageWatermark(watermark string) *HtmlToPdfClient
Apply each page of the specified watermark PDF to the corresponding page of the output PDF.
watermark
The file path to a local watermark PDF file.
The file must exist and not be empty.
func (client *HtmlToPdfClient) SetMultipageWatermarkUrl(url string) *HtmlToPdfClient
Load a watermark PDF from the specified URL and apply each page of the specified watermark PDF to the corresponding page of the output PDF.
url
The supported protocols are http:// and https://.
Example:
  • SetMultipageWatermarkUrl("http://myserver.com/watermark.pdf")
func (client *HtmlToPdfClient) SetPageBackground(background string) *HtmlToPdfClient
Apply the first page of the specified PDF to the background of every page of the output PDF.
background
The file path to a local background PDF file.
The file must exist and not be empty.
func (client *HtmlToPdfClient) SetPageBackgroundUrl(url string) *HtmlToPdfClient
Load a background PDF from the specified URL and apply the first page of the background PDF to every page of the output PDF.
url
The supported protocols are http:// and https://.
Example:
  • SetPageBackgroundUrl("http://myserver.com/background.pdf")
func (client *HtmlToPdfClient) SetMultipageBackground(background string) *HtmlToPdfClient
Apply each page of the specified PDF to the background of the corresponding page of the output PDF.
background
The file path to a local background PDF file.
The file must exist and not be empty.
func (client *HtmlToPdfClient) SetMultipageBackgroundUrl(url string) *HtmlToPdfClient
Load a background PDF from the specified URL and apply each page of the specified background PDF to the corresponding page of the output PDF.
url
The supported protocols are http:// and https://.
Example:
  • SetMultipageBackgroundUrl("http://myserver.com/background.pdf")
func (client *HtmlToPdfClient) SetPageBackgroundColor(color string) *HtmlToPdfClient
The page background color in RGB or RGBA hexadecimal format. The color fills the entire page regardless of the margins.
color
The value must be in RRGGBB or RRGGBBAA hexadecimal format.
Examples:
  • red color
    SetPageBackgroundColor("FF0000")
  • green color
    SetPageBackgroundColor("00ff00")
  • green color with 50% opacity
    SetPageBackgroundColor("00ff0080")

 

General Options

func (client *HtmlToPdfClient) SetUsePrintMedia(value bool) *HtmlToPdfClient
Use the print version of the page if available (@media print).
value
Set to true to use the print version of the page.
Default: false
func (client *HtmlToPdfClient) SetNoBackground(value bool) *HtmlToPdfClient
Do not print the background graphics.
value
Set to true to disable the background graphics.
Default: false
func (client *HtmlToPdfClient) SetDisableJavascript(value bool) *HtmlToPdfClient
Do not execute JavaScript.
value
Set to true to disable JavaScript in web pages.
Default: false
func (client *HtmlToPdfClient) SetDisableImageLoading(value bool) *HtmlToPdfClient
Do not load images.
value
Set to true to disable loading of images.
Default: false
func (client *HtmlToPdfClient) SetDisableRemoteFonts(value bool) *HtmlToPdfClient
Disable loading fonts from remote sources.
value
Set to true disable loading remote fonts.
Default: false
func (client *HtmlToPdfClient) SetLoadIframes(iframes string) *HtmlToPdfClient
Specifies how iframes are handled.
Availability: API client >= 5.0.0, converter >= 20.10. See versioning.
iframes
Allowed values:
  • all
    All iframes are loaded.
  • same-origin
    Only iframes with the same origin as the main page are loaded.
  • none
    Iframe loading is disabled.
Default: all
func (client *HtmlToPdfClient) SetBlockAds(value bool) *HtmlToPdfClient
Try to block ads. Enabling this option can produce smaller output and speed up the conversion.
value
Set to true to block ads in web pages.
Default: false
func (client *HtmlToPdfClient) SetDefaultEncoding(encoding string) *HtmlToPdfClient
Set the default HTML content text encoding.
encoding
The text encoding of the HTML content.
Default: auto detect
func (client *HtmlToPdfClient) SetLocale(locale string) *HtmlToPdfClient
Set the locale for the conversion. This may affect the output format of dates, times and numbers.
Availability: API client >= 5.0.0, converter >= 20.10. See versioning.
locale
The locale code according to ISO 639.
Default: en-US
func (client *HtmlToPdfClient) SetHttpAuth(userName string, password string) *HtmlToPdfClient
Set credentials to access HTTP base authentication protected websites.
userName
Set the HTTP authentication user name.
password
Set the HTTP authentication password.
func (client *HtmlToPdfClient) SetCookies(cookies string) *HtmlToPdfClient
Set cookies that are sent in Pdfcrowd HTTP requests.
cookies
The cookie string.
Example:
  • SetCookies("session=6d7184b3bf35;token=2710")
func (client *HtmlToPdfClient) SetVerifySslCertificates(value bool) *HtmlToPdfClient
Do not allow insecure HTTPS connections.
value
Set to true to enable SSL certificate verification.
Default: false
func (client *HtmlToPdfClient) SetFailOnMainUrlError(failOnError bool) *HtmlToPdfClient
Abort the conversion if the main URL HTTP status code is greater than or equal to 400.
failOnError
Set to true to abort the conversion.
Default: false
func (client *HtmlToPdfClient) SetFailOnAnyUrlError(failOnError bool) *HtmlToPdfClient
Abort the conversion if any of the sub-request HTTP status code is greater than or equal to 400 or if some sub-requests are still pending. See details in a debug log.
failOnError
Set to true to abort the conversion.
Default: false
func (client *HtmlToPdfClient) SetNoXpdfcrowdHeader(value bool) *HtmlToPdfClient
Do not send the X-Pdfcrowd HTTP header in Pdfcrowd HTTP requests.
value
Set to true to disable sending X-Pdfcrowd HTTP header.
Default: false
func (client *HtmlToPdfClient) SetCustomJavascript(javascript string) *HtmlToPdfClient
Run a custom JavaScript after the document is loaded and ready to print. The script is intended for post-load DOM manipulation (add/remove elements, update CSS, ...). In addition to the standard browser APIs, the custom JavaScript code can use helper functions from our JavaScript library.
javascript
A string containing a JavaScript code.
The string must not be empty.
func (client *HtmlToPdfClient) SetOnLoadJavascript(javascript string) *HtmlToPdfClient
Run a custom JavaScript right after the document is loaded. The script is intended for early DOM manipulation (add/remove elements, update CSS, ...). In addition to the standard browser APIs, the custom JavaScript code can use helper functions from our JavaScript library.
javascript
A string containing a JavaScript code.
The string must not be empty.
func (client *HtmlToPdfClient) SetCustomHttpHeader(header string) *HtmlToPdfClient
Set a custom HTTP header that is sent in Pdfcrowd HTTP requests.
header
A string containing the header name and value separated by a colon.
Example:
  • SetCustomHttpHeader("X-My-Client-ID:k2017-12345")
func (client *HtmlToPdfClient) SetJavascriptDelay(delay int) *HtmlToPdfClient
Wait the specified number of milliseconds to finish all JavaScript after the document is loaded. Your API license defines the maximum wait time by "Max Delay" parameter.
delay
The number of milliseconds to wait.
Must be a positive integer number or 0.
Default: 200
func (client *HtmlToPdfClient) SetElementToConvert(selectors string) *HtmlToPdfClient
Convert only the specified element from the main document and its children. The element is specified by one or more CSS selectors. If the element is not found, the conversion fails. If multiple elements are found, the first one is used.
selectors
One or more CSS selectors separated by commas.
The string must not be empty.
Examples:
  • The first element with the id main-content is converted.
    SetElementToConvert("#main-content")
  • The first element with the class name main-content is converted.
    SetElementToConvert(".main-content")
  • The first element with the tag name table is converted.
    SetElementToConvert("table")
  • The first element with the tag name table or with the id main-content is converted.
    SetElementToConvert("table, #main-content")
  • The first element <p class="article"> within <div class="user-panel main"> is converted.
    SetElementToConvert("div.user-panel.main p.article")
func (client *HtmlToPdfClient) SetElementToConvertMode(mode string) *HtmlToPdfClient
Specify the DOM handling when only a part of the document is converted. This can affect the CSS rules used.
mode
Allowed values:
  • cut-out
    The element and its children are cut out of the document.
  • remove-siblings
    All element's siblings are removed.
  • hide-siblings
    All element's siblings are hidden.
Default: cut-out
func (client *HtmlToPdfClient) SetWaitForElement(selectors string) *HtmlToPdfClient
Wait for the specified element in a source document. The element is specified by one or more CSS selectors. The element is searched for in the main document and all iframes. If the element is not found, the conversion fails. Your API license defines the maximum wait time by "Max Delay" parameter.
selectors
One or more CSS selectors separated by commas.
The string must not be empty.
Examples:
  • Wait until an element with the id main-content is found.
    SetWaitForElement("#main-content")
  • Wait until an element with the class name main-content is found.
    SetWaitForElement(".main-content")
  • Wait until an element with the tag name table is found.
    SetWaitForElement("table")
  • Wait until an element with the tag name table or with the id main-content is found.
    SetWaitForElement("table, #main-content")
  • Wait until <p class="article"> is found within <div class="user-panel main">.
    SetWaitForElement("div.user-panel.main p.article")

 

func (client *HtmlToPdfClient) SetViewportWidth(width int) *HtmlToPdfClient
Set the viewport width in pixels. The viewport is the user's visible area of the page.
width
The value must be in the range 96-65000.
Default: 1024
func (client *HtmlToPdfClient) SetViewportHeight(height int) *HtmlToPdfClient
Set the viewport height in pixels. The viewport is the user's visible area of the page.
height
Must be a positive integer number.
Default: 768
func (client *HtmlToPdfClient) SetViewport(width int, height int) *HtmlToPdfClient
Set the viewport size. The viewport is the user's visible area of the page.
width
Set the viewport width in pixels. The viewport is the user's visible area of the page.
The value must be in the range 96-65000.
Default: 1024
height
Set the viewport height in pixels. The viewport is the user's visible area of the page.
Must be a positive integer number.
Default: 768
func (client *HtmlToPdfClient) SetRenderingMode(mode string) *HtmlToPdfClient
Set the rendering mode.
mode
The rendering mode.
Allowed values:
  • default
    The mode based on the standard browser print functionality.
  • viewport
    The viewport width affects the @media min-width and max-width CSS properties. This mode can be used to choose a particular version (mobile, desktop, ..) of a responsive page.
Default: default
func (client *HtmlToPdfClient) SetSmartScalingMode(mode string) *HtmlToPdfClient
Specifies the scaling mode used for fitting the HTML contents to the print area.
mode
The smart scaling mode.
Allowed values:
  • default
    The mode based on the standard browser print functionality.
  • disabled
    No smart scaling is performed.
  • viewport-fit
    The viewport width fits the print area width.
  • content-fit
    The HTML contents width fits the print area width.
  • single-page-fit
    The whole HTML contents fits the print area of a single page.
  • mode1
    Scaling mode 1 is applied.
Default: default
func (client *HtmlToPdfClient) SetScaleFactor(factor int) *HtmlToPdfClient
Set the scaling factor (zoom) for the main page area.
factor
The percentage value.
The value must be in the range 10-500.
Default: 100
func (client *HtmlToPdfClient) SetDisableSmartShrinking(value bool) *HtmlToPdfClient
Disable the intelligent shrinking strategy that tries to optimally fit the HTML contents to a PDF page.
Availability: API client < 5.0.0. Smart scaling mode1 can be used instead. See versioning.
value
Set to true to disable the intelligent shrinking strategy.
Default: false
func (client *HtmlToPdfClient) SetJpegQuality(quality int) *HtmlToPdfClient
Set the quality of embedded JPEG images. A lower quality results in a smaller PDF file but can lead to compression artifacts.
quality
The percentage value.
The value must be in the range 1-100.
Default: 100
func (client *HtmlToPdfClient) SetConvertImagesToJpeg(images string) *HtmlToPdfClient
Specify which image types will be converted to JPEG. Converting lossless compression image formats (PNG, GIF, ...) to JPEG may result in a smaller PDF file.
images
The image category.
Allowed values:
  • none
    No image conversion is done.
  • opaque
    Only opaque images are converted to JPEG images.
  • all
    All images are converted to JPEG images. The JPEG format does not support transparency so the transparent color is replaced by a PDF page background color.
Default: none
func (client *HtmlToPdfClient) SetImageDpi(dpi int) *HtmlToPdfClient
Set the DPI of images in PDF. A lower DPI may result in a smaller PDF file. If the specified DPI is higher than the actual image DPI, the original image DPI is retained (no upscaling is performed). Use 0 to leave the images unaltered.
dpi
The DPI value.
Must be a positive integer number or 0.
Default: 0
Examples:
  • No change of the source image is done.
    SetImageDpi(0)
  • Screen-only view lower DPI.
    SetImageDpi(72)
  • Screen-only view recommended DPI.
    SetImageDpi(96)
  • Ebook typical DPI.
    SetImageDpi(150)
  • Printer standard DPI.
    SetImageDpi(300)

 

PDF Format

Miscellaneous values for PDF output.

func (client *HtmlToPdfClient) SetLinearize(value bool) *HtmlToPdfClient
Create linearized PDF. This is also known as Fast Web View.
value
Set to true to create linearized PDF.
Default: false
func (client *HtmlToPdfClient) SetEncrypt(value bool) *HtmlToPdfClient
Encrypt the PDF. This prevents search engines from indexing the contents.
value
Set to true to enable PDF encryption.
Default: false
func (client *HtmlToPdfClient) SetUserPassword(password string) *HtmlToPdfClient
Protect the PDF with a user password. When a PDF has a user password, it must be supplied in order to view the document and to perform operations allowed by the access permissions.
password
The user password.
func (client *HtmlToPdfClient) SetOwnerPassword(password string) *HtmlToPdfClient
Protect the PDF with an owner password. Supplying an owner password grants unlimited access to the PDF including changing the passwords and access permissions.
password
The owner password.
func (client *HtmlToPdfClient) SetNoPrint(value bool) *HtmlToPdfClient
Disallow printing of the output PDF.
value
Set to true to set the no-print flag in the output PDF.
Default: false
func (client *HtmlToPdfClient) SetNoModify(value bool) *HtmlToPdfClient
Disallow modification of the output PDF.
value
Set to true to set the read-only only flag in the output PDF.
Default: false
func (client *HtmlToPdfClient) SetNoCopy(value bool) *HtmlToPdfClient
Disallow text and graphics extraction from the output PDF.
value
Set to true to set the no-copy flag in the output PDF.
Default: false
func (client *HtmlToPdfClient) SetTitle(title string) *HtmlToPdfClient
Set the title of the PDF.
title
The title.
func (client *HtmlToPdfClient) SetSubject(subject string) *HtmlToPdfClient
Set the subject of the PDF.
subject
The subject.
func (client *HtmlToPdfClient) SetAuthor(author string) *HtmlToPdfClient
Set the author of the PDF.
author
The author.
func (client *HtmlToPdfClient) SetKeywords(keywords string) *HtmlToPdfClient
Associate keywords with the document.
keywords
The string with the keywords.

 

Viewer Preferences

These preferences specify how a PDF viewer should present the document. The preferences may be ignored by some PDF viewers.

func (client *HtmlToPdfClient) SetPageLayout(layout string) *HtmlToPdfClient
Specify the page layout to be used when the document is opened.
layout
Allowed values:
  • single-page
    Display one page at a time.
  • one-column
    Display the pages in one column.
  • two-column-left
    Display the pages in two columns, with odd-numbered pages on the left.
  • two-column-right
    Display the pages in two columns, with odd-numbered pages on the right.
func (client *HtmlToPdfClient) SetPageMode(mode string) *HtmlToPdfClient
Specify how the document should be displayed when opened.
mode
Allowed values:
  • full-screen
    Full-screen mode.
  • thumbnails
    Thumbnail images are visible.
  • outlines
    Document outline is visible.
func (client *HtmlToPdfClient) SetInitialZoomType(zoomType string) *HtmlToPdfClient
Specify how the page should be displayed when opened.
zoomType
Allowed values:
  • fit-width
    The page content is magnified just enough to fit the entire width of the page within the window.
  • fit-height
    The page content is magnified just enough to fit the entire height of the page within the window.
  • fit-page
    The page content is magnified just enough to fit the entire page within the window both horizontally and vertically. If the required horizontal and vertical magnification factors are different, use the smaller of the two, centering the page within the window in the other dimension.
func (client *HtmlToPdfClient) SetInitialPage(page int) *HtmlToPdfClient
Display the specified page when the document is opened.
page
Must be a positive integer number.
func (client *HtmlToPdfClient) SetInitialZoom(zoom int) *HtmlToPdfClient
Specify the initial page zoom in percents when the document is opened.
zoom
Must be a positive integer number.
func (client *HtmlToPdfClient) SetHideToolbar(value bool) *HtmlToPdfClient
Specify whether to hide the viewer application's tool bars when the document is active.
value
Set to true to hide tool bars.
Default: false
func (client *HtmlToPdfClient) SetHideMenubar(value bool) *HtmlToPdfClient
Specify whether to hide the viewer application's menu bar when the document is active.
value
Set to true to hide the menu bar.
Default: false
func (client *HtmlToPdfClient) SetHideWindowUi(value bool) *HtmlToPdfClient
Specify whether to hide user interface elements in the document's window (such as scroll bars and navigation controls), leaving only the document's contents displayed.
value
Set to true to hide ui elements.
Default: false
func (client *HtmlToPdfClient) SetFitWindow(value bool) *HtmlToPdfClient
Specify whether to resize the document's window to fit the size of the first displayed page.
value
Set to true to resize the window.
Default: false
func (client *HtmlToPdfClient) SetCenterWindow(value bool) *HtmlToPdfClient
Specify whether to position the document's window in the center of the screen.
value
Set to true to center the window.
Default: false
func (client *HtmlToPdfClient) SetDisplayTitle(value bool) *HtmlToPdfClient
Specify whether the window's title bar should display the document title. If false , the title bar should instead display the name of the PDF file containing the document.
value
Set to true to display the title.
Default: false
func (client *HtmlToPdfClient) SetRightToLeft(value bool) *HtmlToPdfClient
Set the predominant reading order for text to right-to-left. This option has no direct effect on the document's contents or page numbering but can be used to determine the relative positioning of pages when displayed side by side or printed n-up
value
Set to true to set right-to-left reading order.
Default: false

 

Data

Methods related to HTML template rendering.

func (client *HtmlToPdfClient) SetDataString(dataString string) *HtmlToPdfClient
Set the input data for template rendering. The data format can be JSON, XML, YAML or CSV.
dataString
The input data string.
func (client *HtmlToPdfClient) SetDataFile(dataFile string) *HtmlToPdfClient
Load the input data for template rendering from the specified file. The data format can be JSON, XML, YAML or CSV.
dataFile
The file path to a local file containing the input data.
func (client *HtmlToPdfClient) SetDataFormat(dataFormat string) *HtmlToPdfClient
Specify the input data format.
dataFormat
The data format.
Allowed values:
  • auto
    the data format is auto detected
  • json
  • xml
  • yaml
  • csv
Default: auto
func (client *HtmlToPdfClient) SetDataEncoding(encoding string) *HtmlToPdfClient
Set the encoding of the data file set by setDataFile.
encoding
The data file encoding.
Default: utf-8
func (client *HtmlToPdfClient) SetDataIgnoreUndefined(value bool) *HtmlToPdfClient
Ignore undefined variables in the HTML template. The default mode is strict so any undefined variable causes the conversion to fail. You can use {% if variable is defined %} to check if the variable is defined.
value
Set to true to ignore undefined variables.
Default: false
func (client *HtmlToPdfClient) SetDataAutoEscape(value bool) *HtmlToPdfClient
Auto escape HTML symbols in the input data before placing them into the output.
value
Set to true to turn auto escaping on.
Default: false
func (client *HtmlToPdfClient) SetDataTrimBlocks(value bool) *HtmlToPdfClient
Auto trim whitespace around each template command block.
value
Set to true to turn auto trimming on.
Default: false
func (client *HtmlToPdfClient) SetDataOptions(options string) *HtmlToPdfClient
Set the advanced data options:
  • csv_delimiter - The CSV data delimiter, the default is ,.
  • xml_remove_root - Remove the root XML element from the input data.
  • data_root - The name of the root element inserted into the input data without a root node (e.g. CSV), the default is data.
options
Comma separated list of options.
Examples:
  • Use semicolon to separate CSV data.
    SetDataOptions("csv_delimiter=;")
  • Name the root of data rows and use the name in the template loop {% for row in rows %}...{% endfor %}.
    SetDataOptions("data_root=rows")
  • Remove XML root so it the HTML template can be more simple.
    SetDataOptions("xml_remove_root=1")

 

Miscellaneous

func (client *HtmlToPdfClient) SetDebugLog(value bool) *HtmlToPdfClient
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.
value
Set to true to enable the debug logging.
Default: false
func (client *HtmlToPdfClient) GetDebugLogUrl() string
Get the URL of the debug log for the last conversion.
Returns
  • string - The link to the debug log.
func (client *HtmlToPdfClient) GetRemainingCreditCount() int
Get the number of conversion credits available in your account.
This method can only be called after a call to one of the convertXYZ methods.
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 *HtmlToPdfClient) GetConsumedCreditCount() int
Get the number of credits consumed by the last conversion.
Returns
  • int - The number of credits.
func (client *HtmlToPdfClient) GetJobId() string
Get the job id.
Returns
  • string - The unique job identifier.
func (client *HtmlToPdfClient) GetPageCount() int
Get the total number of pages in the output document.
Returns
  • int - The page count.
func (client *HtmlToPdfClient) GetOutputSize() int
Get the size of the output in bytes.
Returns
  • int - The count of bytes.
func (client *HtmlToPdfClient) GetVersion() string
Get the version details.
Returns
  • string - API version, converter version, and client version.
func (client *HtmlToPdfClient) SetTag(tag string) *HtmlToPdfClient
Tag the conversion with a custom value. The tag is used in conversion statistics. A value longer than 32 characters is cut off.
tag
A string with the custom tag.
func (client *HtmlToPdfClient) SetHttpProxy(proxy string) *HtmlToPdfClient
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.
proxy
The value must have format DOMAIN_OR_IP_ADDRESS:PORT.
Examples:
  • SetHttpProxy("myproxy.com:8080")
  • SetHttpProxy("113.25.84.10:33333")
func (client *HtmlToPdfClient) SetHttpsProxy(proxy string) *HtmlToPdfClient
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.
proxy
The value must have format DOMAIN_OR_IP_ADDRESS:PORT.
Examples:
  • SetHttpsProxy("myproxy.com:443")
  • SetHttpsProxy("113.25.84.10:44333")
func (client *HtmlToPdfClient) SetClientCertificate(certificate string) *HtmlToPdfClient
A client certificate to authenticate Pdfcrowd converter on your web server. The certificate is used for two-way SSL/TLS authentication and adds extra security.
certificate
The file must be in PKCS12 format.
The file must exist and not be empty.
func (client *HtmlToPdfClient) SetClientCertificatePassword(password string) *HtmlToPdfClient
A password for PKCS12 file with a client certificate if it is needed.
password

 

Expert

Expert options for fine-tuning PDF output.

func (client *HtmlToPdfClient) SetLayoutDpi(dpi int) *HtmlToPdfClient
Set the internal DPI resolution used for positioning of PDF contents. It can help in situations when there are small inaccuracies in the PDF. It is recommended to use values that are a multiple of 72, such as 288 or 360.
Availability: API client >= 5.0.0, converter >= 20.10. See versioning.
dpi
The DPI value.
The value must be in the range of 72-600.
Default: 300
func (client *HtmlToPdfClient) SetContentsMatrix(matrix string) *HtmlToPdfClient
A 2D transformation matrix applied to the main contents on each page. The origin [0,0] is located at the top-left corner of the contents. The resolution is 72 dpi.
Availability: API client >= 5.0.0, converter >= 20.10. See versioning.
matrix
A comma separated string of matrix elements: "scaleX,skewX,transX,skewY,scaleY,transY"
Default: 1,0,0,0,1,0
Examples:
  • Fine tune the contents height.
    SetContentsMatrix("1,0,0,0,1.001,0")
  • Translate the contents by -10 points in both directions.
    SetContentsMatrix("1,0,-10,0,1,-10")
func (client *HtmlToPdfClient) SetHeaderMatrix(matrix string) *HtmlToPdfClient
A 2D transformation matrix applied to the page header contents. The origin [0,0] is located at the top-left corner of the header. The resolution is 72 dpi.
Availability: API client >= 5.0.0, converter >= 20.10. See versioning.
matrix
A comma separated string of matrix elements: "scaleX,skewX,transX,skewY,scaleY,transY"
Default: 1,0,0,0,1,0
Examples:
  • Fine tune the header contents height.
    SetHeaderMatrix("1,0,0,0,1.001,0")
  • Translate the header contents by -10 points in both directions.
    SetHeaderMatrix("1,0,-10,0,1,-10")
A 2D transformation matrix applied to the page footer contents. The origin [0,0] is located at the top-left corner of the footer. The resolution is 72 dpi.
Availability: API client >= 5.0.0, converter >= 20.10. See versioning.
Examples:
  • Fine tune the footer contents height.
    SetFooterMatrix("1,0,0,0,1.001,0")
  • Translate the footer contents by -10 points in both directions.
    SetFooterMatrix("1,0,-10,0,1,-10")
func (client *HtmlToPdfClient) SetDisablePageHeightOptimization(value bool) *HtmlToPdfClient
Disable automatic height adjustment that compensates for pixel to point rounding errors.
Availability: API client >= 5.0.0, converter >= 20.10. See versioning.
value
Set to true to disable automatic height scale.
Default: false
func (client *HtmlToPdfClient) SetMainDocumentCssAnnotation(value bool) *HtmlToPdfClient
Add special CSS classes to the main document's body element. This allows applying custom styling based on these classes:
  • pdfcrowd-page-X - where X is the current page number
  • pdfcrowd-page-odd - odd page
  • pdfcrowd-page-even - even page
Availability: API client >= 5.0.0, converter >= 20.10. See versioning.
value
Set to true to add the special CSS classes.
Default: false

Warning

If your custom styling affects the contents area size (e.g. by using different margins, padding, border width), the resulting PDF may contain duplicit contents or some contents may be missing.

Example:
Add special CSS classes to the header/footer's body element. This allows applying custom styling based on these classes:
  • pdfcrowd-page-X - where X is the current page number
  • pdfcrowd-page-count-X - where X is the total page count
  • pdfcrowd-page-first - the first page
  • pdfcrowd-page-last - the last page
  • pdfcrowd-page-odd - odd page
  • pdfcrowd-page-even - even page
Availability: API client >= 5.0.0, converter >= 20.10. See versioning.
Examples:

 

API Client Options

func (client *HtmlToPdfClient) SetConverterVersion(version string) *HtmlToPdfClient
Set the converter version. Different versions may produce different output. Choose which one provides the best output for your case.
Availability: API client >= 5.0.0. See versioning.
version
The version identifier.
Allowed values:
  • latest
    The latest converter version.
  • 20.10
    Version 20.10.
  • 18.10
    Version 18.10.
Default: 20.10
func (client *HtmlToPdfClient) SetUseHttp(value bool) *HtmlToPdfClient
Specifies if the client communicates over HTTP or HTTPS with Pdfcrowd API.
value
Set to true to use HTTP.
Default: false

Warning

Using HTTP is insecure as data sent over HTTP is not encrypted. Enable this option only if you know what you are doing.

func (client *HtmlToPdfClient) SetUserAgent(agent string) *HtmlToPdfClient
Set a custom user agent HTTP header. It can be useful if you are behind some proxy or firewall.
agent
The user agent string.
Default: pdfcrowd_go_client/5.1.1 (https://pdfcrowd.com)
func (client *HtmlToPdfClient) SetProxy(host string, port int, userName string, password string) *HtmlToPdfClient
Specifies an HTTP proxy that the API client library will use to connect to the internet.
host
The proxy hostname.
port
The proxy port.
userName
The username.
password
The password.
func (client *HtmlToPdfClient) SetRetryCount(count int) *HtmlToPdfClient
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.
count
Number of retries wanted.
Default: 1