DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Go Flags: Beyond the Basics
  • Revolutionize Your MuleSoft Deployments With GitOps
  • How To Convert Common Documents to PNG Image Arrays in Java
  • 5 Simple Steps To Get Your Test Suite Running in Heroku CI

Trending

  • SaaS in an Enterprise - An Implementation Roadmap
  • Go 1.24+ Native FIPS Support for Easier Compliance
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 2
  • Implementing API Design First in .NET for Efficient Development, Testing, and CI/CD
  1. DZone
  2. Coding
  3. Tools
  4. How To Create a Go CLI Tool That Converts Markdowns to PDF Files

How To Create a Go CLI Tool That Converts Markdowns to PDF Files

Explore a Golang CLI tool to convert Markdown files to PDFs. The application uses the Cobra and md2pdf packages underneath.

By 
Samuel Komfi user avatar
Samuel Komfi
·
Apr. 10, 24 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
5.8K Views

Join the DZone community and get the full member experience.

Join For Free

For this tutorial, we are going to be creating a Go CLI application using the popular Cobra framework. In this demo, I used Go version 1.19 on a Linux Mint 21 desktop. This tutorial aims to show you how you can convert a Go library into an application that can be called from the command line. Our application will convert a Markdown file into a PDF file using the mdtopdf library. We will also use the popular Viper package to handle the application configurations. This will be used to set the PDF’s default width for example and other document settings.

Installation

To begin, we will create a directory under any project folder we wish and change into that directory. On my desktop, for instance, my project will based under $HOME/projects.

 
$ mkdir md2pdf-cli 

$ cd md2pdf-cli


Initialize a Git repository with the following command and add the origin remote URL:

 
$ git init


Remember to create an empty repository on GitHub named md2pdf-cli.

 
$ git remote add origin https://github.com/USERNAME/md2pdf-cli.git


After taking care of the Git stuff, you can now create a Go module. The module can be any name you wish for the project. The command will create go.mod file in the directory.

 
go mod init github.com/USERNAME/md2pdf-cli


Add and commit to the repo:

 
$ git add .

$ git commit -m “First Commit”


Upload the package to GitHub:

 
$ git branch -M main

$ git push -u origin main


Tag the CLI app with the git tag:

 
$ git tag v0.0.1

$ git push origin v0.0.1


Install the required dependencies. Start with installing the Cobra CLI, which will be used to create the necessary folder structure for you out of the box:

 
go get -u github.com/spf13/cobra@latest

go install github.com/spf13/cobra-cli@latest


The Cobra Package

Create a document structure by invoking the Cobra CLI init function from the command line. This will create a default directory structure for your application.

 
$ cobra-cli init


You should have more or less the following files and folders:

Cobra default directory

The main.go file will look like this:

/*
Copyright © 2023 NAME HERE <EMAIL ADDRESS>
*/

package main

import "github.com/samaras/md2pdf-cli/cmd"

func main() {
    cmd.Execute()
}


As you can see, it only has a few lines of code. The most important line will be app.Execute(). The function called is defined in the root file of the /cmd directory, which calls the topmost command of the CLI. All other commands are sub-commands of this command. They can be added using the following code:

 
$ cobra-cli add <sub command>


In our case, the only function that makes sense will be convert. So we will add a sub-command named convert, which will create a corresponding file under our cmd folder.

 
$ cobra-cli add convert


It will have more or less the same code as the root.go file:

/*
Copyright © 2023 Samuel Komfi <skomfi@gmail.com>

*/
package cmd

import (
    "os"

    "github.com/spf13/cobra"
)



// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
    Use:   "md2pdf-cli",
    Short: "A go cli app that converts Markdown files to PDFs",
    Long: `The application uses the mdtopdf library to convert a Markdown file to a PDF file. For example:


This application is a tool to generate the needed pdf files
from a provided markdown file.`,
    // Uncomment the following line if your bare application
    // has an action associated with it:
    // Run: func(cmd *cobra.Command, args []string) { },
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
    err := rootCmd.Execute()
    if err != nil {
        os.Exit(1)
    }
}

func init() {
    // Here you will define your flags and configuration settings.
    // Cobra supports persistent flags, which, if defined here,
    // will be global for your application.

    // rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.md2pdf-cli.yaml)")

    // Cobra also supports local flags, which will only run
    // when this action is called directly.
}


The Command struct has five main important properties:

  1. Use → The name of the command; e.g., convert
  2. Version → The version number of your application
  3. Short → A property giving a short description of the command
  4. Long → A property giving the user a long description for the command
  5. Run → A function argument that will be run when the command is invoked; In our case, it will collect the filename and arguments (as flags) if any pass them on to our convert function. You can find the rest of the properties here.

Our convert.go file will be edited to call the convert function from the mdtopdf library. The file will have the following code:

/*
Copyright © 2023 Samuel Komfi <skomfi@gmail.com>

*/
package cmd

import (
    "fmt"
    "os"

    "github.com/spf13/cobra"
    "github.com/spf13/viper"
    "github.com/samaras/md2pdf-cli/util"
)

// convertCmd represents the convert command
var convertCmd = &cobra.Command{
    Use:   "convert",
    Short: "The commands generates the PDF from a given Markdown file",
    Long: `The command accepts a Markdown file and a corresponding PDF file name. It converts the file to PDF.
    For example:

The cli will use the md2pdf library to convert your given Markdown and convert it to a PDF with
your given arguments.`,
    Run: func(cmd *cobra.Command, args []string) {
        mdFile := viper.GetString("mdfile")
        pdfFile := viper.GetString("pdffile")

        // Call util function to convert the files
        err := util.ConvertFile(mdFile, pdfFile)
        if err != nil {
            fmt.Println("Error converting file:", err)
            os.Exit(1)
        }

        fmt.Println("Converted %s to %s ... \n", mdFile, pdfFile)
    },
}

func init() {
    // Define flags for convert command
    convertCmd.Flags().StringP("mdfile", "m", "", "Markdown file name")
    convertCmd.Flags().StringP("pdffile", "p", "", "PDF file name")

    convertCmd.Flags().StringP("fontsize", "f", "12", "The font size of the PDF")
    convertCmd.Flags().StringP("fontstyle", "s", "B", "The font style of the PDF")
    convertCmd.Flags().StringP("textcolorR", "r", "200", "The text color of the PDF")
    convertCmd.Flags().StringP("textcolorG", "g", "200", "The text color of the PDF")
    convertCmd.Flags().StringP("textcolorB", "b", "200", "The text color of the PDF")

    // Bind flags to viper configuration
    viper.BindPFlag("mdfile", convertCmd.Flags().Lookup("mdfile"))
    viper.BindPFlag("pdffile", convertCmd.Flags().Lookup("pdffile"))

    viper.BindPFlag("fontsize", convertCmd.Flags().Lookup("fontsize"))
    viper.BindPFlag("fontstyle", convertCmd.Flags().Lookup("fontstyle"))
    viper.BindPFlag("textcolorR", convertCmd.Flags().Lookup("textcolorR"))
    viper.BindPFlag("textcolorG", convertCmd.Flags().Lookup("textcolorG"))
    viper.BindPFlag("textcolorB", convertCmd.Flags().Lookup("textcolorB"))

    // Add convert command as a subcommand
    rootCmd.AddCommand(convertCmd)
}


Add the mdtopdf Library

Install the mdtopdf package:

 
go get github.com/raykov/mdtopdf


The file is the main interface between the CLI app and the mdtopdf package. It calls the Convert() method of the library to process the Markdown files. The function in convert.go will be the one called in the Convert command of our CLI. The utility file that handles the conversion between the md2pdf and CLI is called util.go. Create the file in the util/ directory and add the following code:

package util 

import (
    "fmt"
    "os"

    "github.com/spf13/viper"
    "github.com/raykov/mdtopdf"
    "github.com/raykov/gofpdf"
)

func ConvertFile(mdFile, pdfFile string) error {

    md, err := os.Open(mdFile)
    if err != nil{
        fmt.Println(err)
        return err
    }

    defer md.Close()

    pdf, err := os.Create(pdfFile)
    if err != nil {
        fmt.Println(err)
        return err
    }

    defer pdf.Close()

    // Get PDF settings 
    fontSize := viper.GetFloat64("fontsize")
    fontStyle := viper.GetString("fontstyle")

    textColorR := viper.GetInt("textcolorR")
    textColorG := viper.GetInt("textcolorG")
    textColorB := viper.GetInt("textcolorB")


    pageNumExtension := func(pdf *gofpdf.Fpdf) {
        pdf.SetFooterFunc(func() {
            left, _, right, bottom := pdf.GetMargins()
            width, height := pdf.GetPageSize()
            pNum := fmt.Sprint(pdf.PageNo())
            pdf.SetXY(width-left/2-pdf.GetStringWidth(pNum), height-bottom/2)
            pdf.SetFontSize(fontSize)
            pdf.SetTextColor(textColorR, textColorG, textColorB)
            pdf.SetFontStyle(fontStyle)
            pdf.SetRightMargin(0)
            pdf.Write(fontSize, pNum)
            pdf.SetRightMargin(right)
        })
    }

    err = mdtopdf.Convert(md, pdf, pageNumExtension)
    if err != nil {
        fmt.Println(err)
        return err
    }

    return nil
}


Testing the Application

Let's test the application to see how it works.

Build the application:

 
go build


A new folder named –/bin– will pop up. Upon entering the folder, you will find a generated binary of our application. Run the binary, giving the file name of the Markdown as an argument after:

 
md2pdf convert -m flutter.md -o flutter.pdf


I got the following results:

Code results


Conclusion

We have now finished creating our CLI app using the Cobra framework. The application converts Markdown files given as arguments to PDFs. The program also accepts flags used to set how the PDF will look. It also uses the Viper package for easier default settings. All three packages were used to create the application. You can find the complete code on this GitHub repository.

Command-line interface Git PDF Convert (command) Go (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Go Flags: Beyond the Basics
  • Revolutionize Your MuleSoft Deployments With GitOps
  • How To Convert Common Documents to PNG Image Arrays in Java
  • 5 Simple Steps To Get Your Test Suite Running in Heroku CI

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!