Skip to content

Commit

Permalink
Fixes fossasia#374: Add custom font for badges (fossasia#384)
Browse files Browse the repository at this point in the history
  • Loading branch information
yashLadha authored and vaibhavsingh97 committed Dec 17, 2017
1 parent ef5a699 commit 65a5450
Show file tree
Hide file tree
Showing 7 changed files with 84 additions and 12 deletions.
30 changes: 25 additions & 5 deletions app/generate-badges.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,19 @@
paper_sizes['A3'] = ['297mm', '420mm']
paper_sizes['A4'] = ['210mm', '297mm']

input_files = [file for file in os.listdir(UPLOAD_FOLDER) if file.lower().endswith(".csv")]
input_files = [file for file in os.listdir(
UPLOAD_FOLDER) if file.lower().endswith(".csv")]

with open(APP_ROOT + "/../badges/8BadgesOnA3.svg", encoding="UTF-8") as f:
CONTENT = f.read()


font_choice = None
if os.path.isfile(os.path.join(UPLOAD_FOLDER, 'fonts.json')):
DATA = json.load(open(os.path.join(UPLOAD_FOLDER, "fonts.json")))
font_choice = DATA['font']


def configure_badge_page(badge_page, options):
"""
Configure the badge page according to the page
Expand Down Expand Up @@ -57,6 +64,15 @@ def generate_badges(aggregate, folder, index, picture, paper_size):
target = os.path.join(folder, "badges_{}.svg".format(index))
print("Generating {}".format(target))
content = CONTENT
if font_choice:
content = content.replace("font-family:sans-serif",
"font-family:" + font_choice)
content = content.replace("inkscape-font-specification:sans-serif",
"inkscape-font-specification:" + font_choice)
content = content.replace("font-family:ubuntu",
"font-family:" + font_choice)
content = content.replace("inkscape-font-specification:ubuntu",
"inkscape-font-specification:" + font_choice)
for i, row in enumerate(aggregate):
row = [entry for entry in row if not entry.isspace()]
if len(row) == 0:
Expand All @@ -67,7 +83,8 @@ def generate_badges(aggregate, folder, index, picture, paper_size):
row = [""] * (4 - len(row)) + row
for j, text in enumerate(row):
text = html.escape(text)
content = content.replace("person_{}_line_{}".format(i + 1, j + 1), text)
content = content.replace(
"person_{}_line_{}".format(i + 1, j + 1), text)
content = content.replace("badge_{}.png".format(i + 1), picture)
with open(target, "w", encoding="UTF-8") as f:
f.write(content)
Expand All @@ -79,7 +96,8 @@ def generate_badges(aggregate, folder, index, picture, paper_size):

# check if custom config.json is present for the file
config_json_uploaded = os.path.splitext(input_file)[0] + '.json'
config_json_uploaded_path = os.path.join(UPLOAD_FOLDER, config_json_uploaded)
config_json_uploaded_path = os.path.join(
UPLOAD_FOLDER, config_json_uploaded)
if os.path.isfile(config_json_uploaded_path):
config_json = config_json_uploaded
config = json.loads(open(UPLOAD_FOLDER + '/' + config_json).read())
Expand Down Expand Up @@ -109,8 +127,10 @@ def generate_badges(aggregate, folder, index, picture, paper_size):
if options['badge_wrap']:
aggregate.append(row)
if len(aggregate) >= NUMBER_OF_BADGES_PER_PAGE:
generate_badges(aggregate, folder, i, badges_background, options)
generate_badges(aggregate, folder, i,
badges_background, options)
aggregate = []
i += 1
if aggregate:
generate_badges(aggregate, folder, i, badges_background, options)
generate_badges(aggregate, folder, i,
badges_background, options)
19 changes: 18 additions & 1 deletion app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from flask_compress import Compress
from werkzeug.utils import secure_filename
import os
import json
import shutil
import traceback
from svg_to_png import do_svg2png
Expand All @@ -25,6 +26,8 @@
# help="Start the server in development mode with debug=True",
# action="store_true")
# args = parser.parse_args()
CUSTOM_FONTS = ['monospace', 'sans-serif', 'sans', 'Courier 10 Pitch', 'Source Code Pro']


@app.route('/')
def index():
Expand All @@ -35,7 +38,7 @@ def index():
for file in os.listdir(UPLOAD_FOLDER):
if file.rsplit('.', 1)[1] == 'png' and file != 'user_defined.png':
default_background.append(file)
return render_template('index.html', default_background=default_background)
return render_template('index.html', default_background=default_background, custom_fonts=CUSTOM_FONTS)


def generate_badges(_pdf=True):
Expand Down Expand Up @@ -72,6 +75,7 @@ def upload():
empty_directory()
csv = request.form['csv'].strip()
img = request.form['img-default']
custom_font = request.form['custfont']
text_on_image = request.form['text_on_image']
file = request.files['file']

Expand All @@ -83,6 +87,15 @@ def upload():
do_svg2png(img, 1, bg_color, text_on_image)
filename = img + '.csv'

# Custom font is selected for the text
if custom_font != '':
json_str = json.dumps({
'font': custom_font
})
f = open(os.path.join(app.config['UPLOAD_FOLDER'], 'fonts.json'), "w+")
f.write(json_str)
f.close()

# If the textbox is filled
if img == '':
img = request.files['image'].filename
Expand Down Expand Up @@ -145,6 +158,8 @@ def upload():

# Remove the uploaded files after job in done
os.unlink(os.path.join(app.config['UPLOAD_FOLDER'], filename))
if os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'], 'fonts.json')):
os.unlink(os.path.join(app.config['UPLOAD_FOLDER'], 'fonts.json'))
try:
if 'imgname' in locals():
os.unlink(os.path.join(app.config['UPLOAD_FOLDER'], imgname))
Expand All @@ -153,6 +168,8 @@ def upload():

if True:
flash(filename.replace('.', '-'), 'success-pdf')
os.rename(os.path.join(BADGES_FOLDER + "/" + filename + ".badges.pdf"),
os.path.join(BADGES_FOLDER + "/" + filename.replace('.', '-') + "-badges.pdf"))

return redirect(url_for('index'))

Expand Down
2 changes: 0 additions & 2 deletions app/merge_badges.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@

if subprocess.call(['which', 'python3']) != 0:
raise PackageNotFoundError("Package python3 not found")
if subprocess.call(['which', 'pdftk']) != 0:
raise PackageNotFoundError("Package pdftk not found")

APP_ROOT = os.path.dirname(os.path.abspath(__file__))
BADGES_FOLDER = os.path.join(APP_ROOT, 'static/badges')
Expand Down
5 changes: 5 additions & 0 deletions app/static/css/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,11 @@
border-bottom: 1px solid darkgray;
}

.font-options {
border-bottom: 1px solid darkgray;
padding: 9px;
}

.dropdown-menu>li:hover {
background: #f1f9fd;
cursor: pointer;
Expand Down
6 changes: 6 additions & 0 deletions app/static/js/form.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ $(document).ready(
$("#cutext-input").css("display", "none");
$("#config-input").css("display", "block");
});
$("#custfont").click(function(){
$("#custom-font").css("display", "block");
});
$("#deffont").click(function(){
$("#custom-font").css("display", "none");
});

$("input[type=file], input[type=hidden], input[type=text], textarea").on("keyup change", function () {
var csv = $("textarea[name='csv']").val();
Expand Down
6 changes: 6 additions & 0 deletions app/static/js/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ $(document).on("ready", function () {
$('input[name="img-default"]').val(i).trigger('change');
});

$(".font-options").click(function () {
var i = $(this).data("item");
$(".placeholder2").text(i);
$("input[name='custfont']").val(i);
});


$("#picker").minicolors({
control: 'hue',
Expand Down
28 changes: 24 additions & 4 deletions app/templates/index.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
{% extends "layout.html" %}
{% block body %}
{% extends "layout.html" %} {% block body %}
<div class="container board">
<div class="row">
<form action="{{ url_for('upload') }}" method="post" enctype="multipart/form-data" onsubmit="return validate()">
Expand Down Expand Up @@ -73,7 +72,28 @@
</section>
</li>
</ul>
<div id="error" class="no-image-error"> Please select a default background or upload an image!</div>
<div id="error" class="no-image-error"> Please select a default background or upload an image!</div>
<label>Choose your font</label>
<ul style="list-style-type:none">
<li>
<input type="radio" name="fontsource" id="custfont"> Use Custom font
</li>
<section id="custom-font" style="display: none;">
<label for="inputFile">Select from following fonts</label>
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="placeholder2">Select a font</span>
<span class="glyphicon glyphicon-chevron-down"></span>
</button>
<ul class="dropdown-menu">
{% for i in custom_fonts %}
<li class="font-options" style="font-family:'{{i}}'" data-item="{{i}}">{{i}}</li>
{% endfor %}
</ul>
</div>
</section>
<input type="hidden" name="custfont" value="">
</ul>
<label> Customise Badges (Optional)</label>
<ul style="list-style-type:none">
<li>
Expand Down Expand Up @@ -105,7 +125,7 @@
{% if cat == 'success-pdf' %}
<div class="flash-success">Your badges have been created successfully.</div>
<div class="text-center">
<a href="static/badges/{{msg}}-badges.pdf" class="btn btn-success" download="{{msg}}.badges.pdf">Download as PDF</a>
<a href="static/badges/{{msg}}-badges.pdf" class="btn btn-success" download="{{msg}}-badges.pdf">Download as PDF</a>
</div>
{% else %}
<div class="flash-{{cat}}">{{msg}}</div>
Expand Down

0 comments on commit 65a5450

Please sign in to comment.