Skip to content

Commit

Permalink
Merge pull request #4 from eeintech/main
Browse files Browse the repository at this point in the history
Support for LaTex tables
  • Loading branch information
donhauser authored May 23, 2021
2 parents 20b0460 + a2a750a commit 66781c3
Show file tree
Hide file tree
Showing 6 changed files with 112 additions and 7 deletions.
5 changes: 5 additions & 0 deletions demo/demo/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import sys

PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_DIR = os.path.dirname(PROJECT_DIR)
Expand All @@ -25,6 +26,9 @@
except ImportError:
django_tex = None

# Allow local import of wagtail_pdf_view for development
sys.path.append(os.path.dirname(BASE_DIR))

# Application definition

INSTALLED_APPS = [
Expand All @@ -48,6 +52,7 @@

'wagtail.contrib.modeladmin',
'wagtail.contrib.routable_page',
'wagtail.contrib.table_block',

'modelcluster',
'taggit',
Expand Down
22 changes: 22 additions & 0 deletions demo/home/migrations/0003_alter_htmlandpdfpage_content.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Generated by Django 3.2.3 on 2021-05-19 13:41

from django.db import migrations
import wagtail.contrib.table_block.blocks
import wagtail.core.blocks
import wagtail.core.fields
import wagtail.images.blocks


class Migration(migrations.Migration):

dependencies = [
('home', '0002_htmlandpdfpage_body'),
]

operations = [
migrations.AlterField(
model_name='htmlandpdfpage',
name='content',
field=wagtail.core.fields.StreamField([('heading', wagtail.core.blocks.CharBlock(form_classname='full title')), ('text', wagtail.core.blocks.RichTextBlock()), ('image', wagtail.images.blocks.ImageChooserBlock()), ('table', wagtail.contrib.table_block.blocks.TableBlock())], blank=True),
),
]
6 changes: 4 additions & 2 deletions demo/home/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from wagtail.core.models import Page
from wagtail.core.fields import RichTextField, StreamField
from wagtail.core import blocks
from wagtail.contrib.table_block.blocks import TableBlock

from wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel#, InlinePanel, MultiFieldPanel, FieldRowPanel

Expand Down Expand Up @@ -91,8 +92,8 @@ class HtmlAndPdfPage(PdfViewPageMixin, Page):

# HTML first
ROUTE_CONFIG = [
("pdf", r'^pdf/$'),
("html", r'^$'),
("pdf", r'^pdf/$'),
]

## You can rename the default preview modes
Expand All @@ -110,7 +111,8 @@ class HtmlAndPdfPage(PdfViewPageMixin, Page):
content = StreamField([
("heading", blocks.CharBlock(form_classname="full title")),
("text", blocks.RichTextBlock()),
("image", ImageChooserBlock())
("image", ImageChooserBlock()),
("table", TableBlock()),

], blank=True)

Expand Down
3 changes: 2 additions & 1 deletion demo/home/templates/home/html_and_pdf_page.html
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ <h3>Company Name</h3>
{% block document_content %}

<h1>{{page.title}}</h1>

<hr>
{% for block in page.content %}
{% if block.block_type == 'heading' %}
<h2>{{ block.value }}</h2>
Expand All @@ -46,5 +46,6 @@ <h2>{{ block.value }}</h2>
{% endblock %}

{% block document_footer %}
<hr>
You can place your <b>Footer here</b>!
{% endblock %}
81 changes: 77 additions & 4 deletions wagtail_pdf_view/environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@


from wagtail.core import blocks
from wagtail.contrib.table_block.blocks import TableBlock

import re
from html.parser import HTMLParser
Expand All @@ -23,8 +24,8 @@ def _include_block(self, value, context=None):
"""
Automatically translate richtext blocks into latex
"""
if isinstance(value.block, blocks.RichTextBlock):

if isinstance(value.block, blocks.RichTextBlock) or isinstance(value.block, TableBlock):

if hasattr(value, 'render_as_block'):
if context:
Expand Down Expand Up @@ -62,6 +63,11 @@ def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.latex = []
self.tex_inline = ''
# table support
self.table_caption = ''
self.column_format_key = '__column_format__'
self.table_column_counter = 0
self.table_column_counter_max = 0

# Some simple HTML Tags, which have a similar representation in latex
mapping = {
Expand Down Expand Up @@ -96,20 +102,87 @@ def handle_starttag(self, tag, attrs):
if tag == "img":
self.latex.append("\\wagtailimage{"+a.get("src", '')+"}{"+a.get("class", '')+"}")

# add support for tables
if tag == "table":
self.latex.append("\\begin{table}[H]\n\\centering\n\\begin{tabular}{ " + self.column_format_key + " }\n\\hline\n")
elif tag == "caption":
self.tex_inline = "\\caption{"
elif tag == "thead":
pass
elif tag == "tbody":
pass
elif tag == "tr":
pass
elif tag == "th":
if not self.table_column_counter:
self.latex.append("\\textbf{")
else:
self.latex.append("& \\textbf{")

# Update column counter
self.table_column_counter += 1
# Update maximum value
if self.table_column_counter_max < self.table_column_counter:
self.table_column_counter_max = self.table_column_counter
elif tag == "td":
if not self.table_column_counter:
pass
else:
self.latex.append("& ")

# Update column counter
self.table_column_counter += 1
# Update maximum value
if self.table_column_counter_max < self.table_column_counter:
self.table_column_counter_max = self.table_column_counter

def handle_endtag(self, tag):

# End inline mode, add line to latex statements
if self.tex_inline:
if tag == "a":
self.latex.append(self.tex_inline+"}\n")

self.tex_inline = ''
# reset inline buffer
self.tex_inline = ''
else:
# simple mapping e.g. </b> --> }
if tag in self.mapping:
self.latex.append(self.mapping[tag][1])

# add support for tables
if tag == "table":
self.latex.append("\\end{tabular}\n" + self.table_caption + "\\end{table}")

# build column format based on number of columns
column_format = '|'
for col in range(self.table_column_counter_max):
column_format += 'c|'

# replace column format key
for idx, line in enumerate(self.latex):
if self.column_format_key in line:
line = line.replace(self.column_format_key, column_format)
break
self.latex[idx] = line

elif tag == "caption":
self.tex_inline += "}\n"
self.table_caption = self.tex_inline
# reset inline buffer
self.tex_inline = ''
elif tag == "thead":
pass
elif tag == "tbody":
pass
elif tag == "tr":
self.latex.append(" \\\\ \\hline\n")
# reset column counter
self.table_column_counter = 0
elif tag == "th":
self.latex.append("} ")
elif tag == "td":
self.latex.append(" ")

def handle_data(self, data):

# preprocess the data
Expand Down
2 changes: 2 additions & 0 deletions wagtail_pdf_view/templates/wagtail_preamble.tex
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
\usepackage{wrapfig}
\usepackage{xstring}
\usepackage{float}
% Prevent table re-positioning
\restylefloat{table}

{% raw %}

Expand Down

0 comments on commit 66781c3

Please sign in to comment.