Giter Site home page Giter Site logo

go-yadt's Introduction

Yet Another Docx Templater

This Go package can generate .docx files from your template and json data.

Warning This package requires an page merger CLI tool. For now the only option is to build it from source. I hope I could publish an .deb package and homebrew tap soon.

Install

To install package go to your go project directory and run:

go get github.com/tymbaca/go-yadt

Then you can import it by adding github.com/tymbaca/go-yadt.

Usage

Use package via yadt shortcut.

Input docx template

Package needs a template - docx file with placeholder fields. You need to specify that fields in curly braces in following format:

// template.docx

// docx text

Hello, {firstName} {lastName}! How do you do?

// more docx text

In this example we have two fields:

  • firstName
  • lastName

Warning Your template placeholders cannot have leading or tailing whitespaces. { firstName}, {firstName } or { firstName } placeholder will lead to validation error.

You will need to specify values for that field in json data.

Input json data

For now this package only eats raw json data in bytes. You can set up parsing raw json from file or by your favorite web framework.

For example in gin you can get raw json data by calling c.GetRawData() (where c is a *gin.Context)

Now let's set up our json into the file and name it data.json:

[
    {
        "filename":"First file",
        "pages": [
            {
                "firstName": "Alex",
                "lastName": "Brown"
            },
            {
                "firstName": "John",
                "lastName": "White"
            }
        ]
    },
    {
        "filename":"Second file",
        "pages": [
            {
                "firstName": "Karina",
                "lastName": "Stone"
            },
            {
                "firstName": "Simon",
                "lastName": "Rock"
            }
        ]
    }
]

This structure is almost fully mandatory. Only items in pages can be deferent.

The input rules are simple:

  • Whole json body is array
  • Every item of that array is an object with two fields:
    • filename which contains result file name (without extension)
    • pages array. Its items are objects whose keys are identical to keys in your template.

Notice that 'page' isn't necessarily means that size of your template needs to be 1 page. It can be more. Or less.

Using in Go

// main.go

import (
    "github.com/tymbaca/go-yadt"
)


// Create instance of FileGenerator
fileGenerator, err := yadt.NewFromFiles("template.docx", "data.json")
if err != nil {
    panic(err)
}

// Generate .docx files and pack to .zip
err = yadt.GenerateZip("output.zip")
if err != nil {
    panic(err)
}

On output you will get a output.zip archive which contains all files specified in data.json.

Don't be shy, clone repository and run some tests (./tests/ and ./utils/tests).

Roadmap

  • Core functionality
  • Generate without packing to zip
  • Changeable keys separator in .docx template
  • Do something with page merging CLI dependency...
  • More detailed error messages

Questions

  • What if some placeholder appear in docx template more than once?
    • I think this question more related to github.com/lukasjarosch/go-docx...

go-yadt's People

Contributors

tymbaca avatar

Stargazers

 avatar

Watchers

 avatar

go-yadt's Issues

Doesn't work on Ubuntu

Doen't pass generator tests. Exiting with message

--- FAIL: TestGenerateZip (0.34s)
    generator_test.go:81: Starting generation for 2 files, 45 pages total...
    generator_test.go:82: 
    generator_test.go:87: Compression error: open /tmp/1443131279/2. Вторник.docx: no such file or directory
FAIL
exit status 1
FAIL    github.com/tymbaca/go-yadt      0.340s

It says that this is a compression error. But looks like generator simply didn't create an docx file.

Add check if pagemerger CLI tool exists or not

func checkIfPageMergerExists() error {
    _, err := exec.LookPath(PageMergerProgram)
    if err != nil {
        return errors.New("pagemerger is not in PATH. " + err.Error())
    }
}

Just include this function in constructor method.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.