-2

I have got a csv file with names, degrees and other data about several persons and a template svg file that shows me how the output should look. Now I should write a bash script that creates a new svg file with the data from the csv file that can be converted into a pdf and be printed to cut out the nameplates later. I have no idea how to do this and would be very happy about some proposals how to write my bash script and some hints what to mind doing this.

Rollaway
  • 11
  • 1

2 Answers2

1

Solution using awk:

# begin by reading the whole first template file at once
BEGIN { RS = "^$" }
FILENAME==ARGV[1] { # NR=1 is the entire template file
  template = $0
  # very conveniently we can now setup RS FPAT etc to apply to the next line for the next file.
  RS = "\r\n"
  # quoted CSV fields pattern
  FPAT = "([^,]*)|(\"[^\"]+\")"
}

FILENAME==ARGV[2] && NR==2 { # NR=2 is the first CSV line: column headers
  for (i = 1; i <= NF; i++) {
    headers[i] = $i
  }
}

FILENAME==ARGV[2] && NR>2 { # NR>2 is the rest of the CSV file records.
  # Strip quotes from quoted CSV values.
  for (i = 1; i <= NF; i++) {
    if (substr($i, 1, 1) == "\"") {
      $i = substr($i, 2, length($i) - 2)
    }
  }

  # Template Replacements
  result = template
  for (i = 1; i <= length(headers); i++) {
    gsub(headers[i], $i, result);
  }

  print result > "svg/" $1 ".svg"
}

Use like this: awk -f build.awk template.svg employees.csv

Where template.svg is a template SVG file that contains the field names you want replaced. For example:

<svg width="200" height="200" xmlns="http://www.w3.org/2000/svg">
 <g>
  <title>Layer 1</title>
  <rect width="100%" height="100%" fill="blue"/>
  <text id="svg_1" y="100" x="76" fill="#FFF">NAME</text>
 </g>
</svg>

This template would expect a CSV file that has a column header "NAME", but you can add as many fields in the template as you have in the CSV. The files would be output in a "svg/" directory, one file per line.

kapace
  • 457
  • 7
  • 12
0

Try Inkscape + the Generator extension:

Replace text and data to automatically generate files (as PDF, PNG, EPS, PS, JPG, SVG), based on an SVG template and a CSV file. Also available via apt in Debian and Ubuntu repositories.

http://wiki.colivre.net/Aurium/InkscapeGenerator

Example file set for testing and learning how to use:

https://inkscape.org/en/~Moini/%E2%98%85example-files-for-generator-extension

Moini
  • 1,239
  • 9
  • 10
  • Updated version as of 2021: https://gitlab.com/Moini/nextgenerator (works with current Inkscape versions) – Moini Aug 17 '21 at 19:15