Skip to content
How to convert MS Word (*.docx) file into PDF using UniOffice?

How to convert MS Word (*.docx) file into PDF using UniOffice?

Open the document, hand it to convert.ConvertToPdf, and write the result. The conversion runs in process, with no Word installation involved.

package main

import (
    "log"
    "os"

    "github.com/unidoc/unioffice/v2/common/license"
    "github.com/unidoc/unioffice/v2/document"
    "github.com/unidoc/unioffice/v2/document/convert"
    unipdflicense "github.com/unidoc/unipdf/v5/common/license"
)

func init() {
    // Conversion uses both libraries, and each checks its own license.
    // The same key satisfies both.
    if err := license.SetMeteredKey(os.Getenv(`UNIDOC_LICENSE_API_KEY`)); err != nil {
        panic(err)
    }
    if err := unipdflicense.SetMeteredKey(os.Getenv(`UNIDOC_LICENSE_API_KEY`)); err != nil {
        panic(err)
    }
}

func main() {
    doc, err := document.Open("document.docx")
    if err != nil {
        log.Fatalf("error opening document: %s", err)
    }
    defer doc.Close()

    c := convert.ConvertToPdf(doc)

    if err := c.WriteToFile("document.pdf"); err != nil {
        log.Fatalf("error converting document: %s", err)
    }
}

Two details in that snippet are easy to miss.

Both packages are named license, so one import needs an alias. Without it the file does not compile.

ConvertToPdf returns a UniPDF *creator.Creator rather than bytes or an error. Nothing is written until you call WriteToFile, which means you can add metadata, append pages or merge in another document first. It also means the object you are holding belongs to UniPDF, which is why UniPDF needs its own license loaded. If the conversion fails on a particular element, it is logged at debug level and that element is skipped rather than returned as an error.

To control the conversion, ConvertToPdfWithOptions takes a convert.Options. Note that passing any non-nil options turns font subsetting off unless you set EnableFontSubsetting: true explicitly, despite what its documentation says.

Before you rely on it

Legacy formats are not supported. document.Open expects an Open XML package, which is a ZIP archive, and fails with parsing zip: ... on the pre-2007 binary .doc. Convert it to .docx first.

Register any font the document uses that is not Helvetica, Courier or Times New Roman, or the text is silently drawn in Helvetica with different metrics.

A table of contents converts blank unless Word has already computed it, because the converter does not evaluate TOC fields.

Those and the rest of the limits are in Does UniOffice support DOCX to PDF conversion?, and the guides cover custom fonts and conversion options in full.

Last updated on