Skip to content

Instantly share code, notes, and snippets.

@abdnh
Last active April 8, 2022 22:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abdnh/f0b1ecbaf1e88449908e8c5b491da1f8 to your computer and use it in GitHub Desktop.
Save abdnh/f0b1ecbaf1e88449908e8c5b491da1f8 to your computer and use it in GitHub Desktop.
Adds an option to Anki's Basic Printing Support add-on to sort cards column-wise
# -*- coding: utf-8 -*-
# Copyright: Ankitects Pty Ltd and contributors
# License: GNU GPL, version 3 or later; http://www.gnu.org/copyleft/gpl.html
#
# Exports the cards in the current deck to a HTML file, so they can be
# printed. Card styling is not included. Cards are printed in sort field
# order.
import re
import math
from anki.utils import ids2str
from aqt import mw
from aqt.qt import *
from aqt.utils import mungeQA, openLink
config = mw.addonManager.getConfig(__name__)
def sortFieldOrderCids(did):
dids = [did]
for name, id in mw.col.decks.children(did):
dids.append(id)
return mw.col.db.list(
"""
select c.id from cards c, notes n where did in %s
and c.nid = n.id order by n.sfld"""
% ids2str(dids)
)
def onPrint():
path = os.path.join(
QStandardPaths.writableLocation(QStandardPaths.DesktopLocation), "print.html"
)
ids = sortFieldOrderCids(mw.col.decks.selected())
def esc(s):
# strip off the repeated question in answer if exists
# s = re.sub("(?si)^.*<hr id=answer>\n*", "", s)
# remove type answer
s = re.sub(r"\[\[type:[^]]+\]\]", "", s)
return s
buf = open(path, "w", encoding="utf8")
buf.write(
"<html><head>" + '<meta charset="utf-8">' + mw.baseHTML() + "</head><body>"
)
buf.write(
"""<style>
img { max-width: 100%; }
tr { page-break-inside:avoid; page-break-after:auto }
td { page-break-after:auto; }
td { border: 1px solid #ccc; padding: 1em; }
.playImage { display: none; }
</style><table cellspacing=10 width=100%>"""
)
def write_card(cid):
c = mw.col.getCard(cid)
qatxt = c.render_output(True, False).answer_text
qatxt = mw.prepare_card_text_for_display(qatxt)
cont = '<td width="{1}%"><center>{0}</center></td>'.format(
esc(qatxt), 100 / config["cardsPerRow"]
)
buf.write(cont)
first = True
mw.progress.start(immediate=True)
if config["columnWise"]:
cardsPerColumn = int(math.ceil(len(ids) / config["cardsPerRow"]))
count = 0
j = 0
while j < cardsPerColumn:
buf.write("<tr>")
for i in range(config["cardsPerRow"]):
if j + i * cardsPerColumn >= len(ids):
break
write_card(ids[j + i * cardsPerColumn])
count += 1
if count % 50 == 0:
mw.progress.update("Cards exported: %d" % (j + 1 + 1))
buf.write("</tr>")
j += 1
else:
for j, cid in enumerate(ids):
if j % config["cardsPerRow"] == 0:
if not first:
buf.write("</tr>")
else:
first = False
buf.write("<tr>")
write_card(cid)
if j % 50 == 0:
mw.progress.update("Cards exported: %d" % (j + 1))
buf.write("</tr>")
buf.write("</table></body></html>")
mw.progress.finish()
buf.close()
openLink(QUrl.fromLocalFile(path))
q = QAction(mw)
q.setText("Print")
q.setShortcut(QKeySequence("Shift+P"))
mw.form.menuTools.addAction(q)
q.triggered.connect(onPrint) # type: ignore
{"cardsPerRow": 3, "columnWise": true}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment