<commit_before># -*- coding: utf-8 -*-
from reportlab.lib.enums import TA_LEFT
from reportlab.lib.fonts import addMapping
from reportlab.lib.pagesizes import landscape, A4
from reportlab.lib.styles import ParagraphStyle
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus.frames import Frame, ShowBoundaryValue
from reportlab.platypus.paraparser import ParaFrag, ps2tt, tt2ps
from xhtml2pdf.util import getSize, getCoords, getFile, pisaFileObject, \
    getFrameDimensions, getColor
from xhtml2pdf.w3c import css
from xhtml2pdf.xhtml2pdf_reportlab import PmlPageTemplate, PmlTableOfContents, \
    PmlParagraph, PmlParagraphAndImage, PmlPageCount
import copy
import logging
import os
import re
import reportlab
import types
import urlparse
import xhtml2pdf.default
import xhtml2pdf.parser

# Copyright 2010 <NAME>, <EMAIL>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

reportlab.rl_config.warnOnMissingFontGlyphs = 0

log = logging.getLogger("xhtml2pdf")

sizeDelta = 2       # amount to reduce font size by for super and sub script
subFraction = 0.4   # fraction of font size that a sub script should be lowered
superFraction = 0.4

NBSP = u"\u00a0"


def clone(self, **kwargs):
    n = ParaFrag(**self.__dict__)
    if kwargs:
        d = n.__dict__
        d.update(kwargs)
        # This else could cause trouble in Paragraphs with images etc.
        if "cbDefn" in d:
            del d["cbDefn"]
    n.bulletText = None
    return n


ParaFrag.clone = clone


def getParaFrag(style):
    frag = ParaFrag()
    frag.sub = 0
    frag.super = 0
    frag.rise = 0
    frag.underline = 0  # XXX Need to be able to set color to fit CSS tests
    frag.strike = 0
    frag.greek = 0
    frag.link = None
    frag.text = ""
    frag.fontName = "Times-Roman"
    frag.fontName, frag.bold, frag.italic = ps2tt(style.fontName)
    frag.fontSize = style.fontSize
    frag.textColor = style.textColor

    # Extras
    frag.leading = 0
    frag.letterSpacing = "normal"
    frag.leadingSource = "150%"
    frag.leadingSpace = 0
    frag.backColor = None
    frag.spaceBefore = 0
    frag.spaceAfter = 0
    frag.leftIndent = 0
    frag.rightIndent = 0
    frag.firstLineIndent = 0
    frag.keepWithNext = False
    frag.alignment = TA_LEFT
    frag.vAlign = None

    frag.borderWidth = 1
    frag.borderStyle = None
    frag.borderPadding = 0
    frag.borderColor = None

    frag.borderLeftWidth = frag.borderWidth
    frag.borderLeftColor = frag.borderColor
    frag.borderLeftStyle = frag.borderStyle
    frag.borderRightWidth = frag.borderWidth
    frag.borderRightColor = frag.borderColor
    frag.borderRightStyle = frag.borderStyle
    frag.borderTopWidth = frag.borderWidth
    frag.borderTopColor = frag.borderColor
    frag.borderTopStyle = frag.borderStyle
    frag.borderBottomWidth = frag.borderWidth
    frag.borderBottomColor = frag.borderColor
    frag.borderBottomStyle = frag.borderStyle

    frag.paddingLeft = 0
    frag.paddingRight = 0
    frag.paddingTop = 0
    frag.paddingBottom = 0

    frag.listStyleType = None
    frag.listStyleImage = None
    frag.whiteSpace = "normal"

    frag.wordWrap = None

    frag.pageNumber = False
    frag.pageCount = False
    frag.height = None
    frag.width = None

    frag.bulletIndent = 0
    frag.bulletText = None
    frag.bulletFontName = "Helvetica"

    frag.zoom = 1.0

    frag.outline = False
    frag.outlineLevel = 0
    frag.outlineOpen = False

    frag.insideStaticFrame = 0

    return frag


def getDirName(path):
    parts = urlparse.urlparse(path)
    if parts.scheme:
        return path
    else:
        return os.path.dirname(os.path.abspath(path))


class pisaCSSBuilder(css.CSSBuilder):
    def atFontFace(self, declarations):
        """
        Embed fonts
        """
        result = self.ruleset([self.selector('*')], declarations)
        data = result[0].values()[0]
        if "src" not in data:
            # invalid - source is required, ignore this specification
            return {}, {}
        names = data["font-family"]

        # Font weight
        fweight = str(data.get("font-weight", "normal")).lower()
        bold = fweight in ("bold", "bolder", "500", "600", "700", "800", "900")
        if not bold and fweight <> "normal":
            log.warn(self.c.warning("@fontface, unknown value font-weight '%s'", fweight))

        # Font style
        italic = str(data.get("font-style", "")).lower() in ("italic", "oblique")

        src = self.c.getFile(data["src"], relative=self.c.cssParser.rootPath)
        self.c.loadFont(
            names,
            src,
            bold=bold,
            italic=italic)
        return {}, {}

    def _pisaAddFrame(self, name, data, first=False, border=None, size=(0, 0)):
        c = self.c
        if not name:
            name = "-pdf-frame-%d" % c.UID()
        x, y, w, h = getFrameDimensions(data, size[0], size[1])
        # print name, x, y, w, h
        #if not (w and h):
        #    return None
        if first:
            return name, None, data.get("-pdf-frame-border", border), x, y, w, h, data

        return (name, data.get("-pdf-frame-content", None),
                data.get("-pdf-frame-border", border), x, y, w, h, data)
<commit_msg>Fix headers/footers in landscape mode.<commit_after># -*- coding: utf-8 -*-
from reportlab.lib.enums import TA_LEFT
from reportlab.lib.fonts import addMapping
from reportlab.lib.pagesizes import landscape, A4
from reportlab.lib.styles import ParagraphStyle
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus.frames import Frame, ShowBoundaryValue
from reportlab.platypus.paraparser import ParaFrag, ps2tt, tt2ps
from xhtml2pdf.util import getSize, getCoords, getFile, pisaFileObject, \
    getFrameDimensions, getColor
from xhtml2pdf.w3c import css
from xhtml2pdf.xhtml2pdf_reportlab import PmlPageTemplate, PmlTableOfContents, \
    PmlParagraph, PmlParagraphAndImage, PmlPageCount
import copy
import logging
import os
import re
import reportlab
import types
import urlparse
import xhtml2pdf.default
import xhtml2pdf.parser

# Copyright 2010 <NAME>, holtw<EMAIL>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

reportlab.rl_config.warnOnMissingFontGlyphs = 0

log = logging.getLogger("xhtml2pdf")

sizeDelta = 2       # amount to reduce font size by for super and sub script
subFraction = 0.4   # fraction of font size that a sub script should be lowered
superFraction = 0.4

NBSP = u"\u00a0"


def clone(self, **kwargs):
    n = ParaFrag(**self.__dict__)
    if kwargs:
        d = n.__dict__
        d.update(kwargs)
        # This else could cause trouble in Paragraphs with images etc.
        if "cbDefn" in d:
            del d["cbDefn"]
    n.bulletText = None
    return n


ParaFrag.clone = clone


def getParaFrag(style):
    frag = ParaFrag()
    frag.sub = 0
    frag.super = 0
    frag.rise = 0
    frag.underline = 0  # XXX Need to be able to set color to fit CSS tests
    frag.strike = 0
    frag.greek = 0
    frag.link = None
    frag.text = ""
    frag.fontName = "Times-Roman"
    frag.fontName, frag.bold, frag.italic = ps2tt(style.fontName)
    frag.fontSize = style.fontSize
    frag.textColor = style.textColor

    # Extras
    frag.leading = 0
    frag.letterSpacing = "normal"
    frag.leadingSource = "150%"
    frag.leadingSpace = 0
    frag.backColor = None
    frag.spaceBefore = 0
    frag.spaceAfter = 0
    frag.leftIndent = 0
    frag.rightIndent = 0
    frag.firstLineIndent = 0
    frag.keepWithNext = False
    frag.alignment = TA_LEFT
    frag.vAlign = None

    frag.borderWidth = 1
    frag.borderStyle = None
    frag.borderPadding = 0
    frag.borderColor = None

    frag.borderLeftWidth = frag.borderWidth
    frag.borderLeftColor = frag.borderColor
    frag.borderLeftStyle = frag.borderStyle
    frag.borderRightWidth = frag.borderWidth
    frag.borderRightColor = frag.borderColor
    frag.borderRightStyle = frag.borderStyle
    frag.borderTopWidth = frag.borderWidth
    frag.borderTopColor = frag.borderColor
    frag.borderTopStyle = frag.borderStyle
    frag.borderBottomWidth = frag.borderWidth
    frag.borderBottomColor = frag.borderColor
    frag.borderBottomStyle = frag.borderStyle

    frag.paddingLeft = 0
    frag.paddingRight = 0
    frag.paddingTop = 0
    frag.paddingBottom = 0

    frag.listStyleType = None
    frag.listStyleImage = None
    frag.whiteSpace = "normal"

    frag.wordWrap = None

    frag.pageNumber = False
    frag.pageCount = False
    frag.height = None
    frag.width = None

    frag.bulletIndent = 0
    frag.bulletText = None
    frag.bulletFontName = "Helvetica"

    frag.zoom = 1.0

    frag.outline = False
    frag.outlineLevel = 0
    frag.outlineOpen = False

    frag.insideStaticFrame = 0

    return frag


def getDirName(path):
    parts = urlparse.urlparse(path)
    if parts.scheme:
        return path
    else:
        return os.path.dirname(os.path.abspath(path))


class pisaCSSBuilder(css.CSSBuilder):
    def atFontFace(self, declarations):
        """
        Embed fonts
        """
        result = self.ruleset([self.selector('*')], declarations)
        data = result[0].values()[0]
        if "src" not in data:
            # invalid - source is required, ignore this specification
            return {}, {}
        names = data["font-family"]

        # Font weight
        fweight = str(data.get("font-weight", "normal")).lower()
        bold = fweight in ("bold", "bolder", "500", "600", "700", "800", "900")
        if not bold and fweight <> "normal":
            log.warn(self.c.warning("@fontface, unknown value font-weight '%s'", fweight))

        # Font style
        italic = str(data.get("font-style", "")).lower() in ("italic", "oblique")

        src = self.c.getFile(data["src"], relative=self.c.cssParser.rootPath)
        self.c.loadFont(
            names,
            src,
            bold=bold,
            italic=italic)
        return {}, {}

    def _pisaAddFrame(self, name, data, first=False, border=None, size=(0, 0)):
        c = self.c
        if not name:
            name = "-pdf-frame-%d" % c.UID()
        if data.get('is_landscape', False):
            size = (size[1], size[0])
        x, y, w, h = getFrameDimensions(data, size[0], size[1])
        # print name, x, y, w, h
        #if not (w and h):
        #    return None
        if first:
            return name, None, data.get("-pdf-frame-border", border), x, y, w, h, data

        return (name, data.get("-pdf-frame-content", None),
                data.get("-pdf-frame-border", border), x, y, w, h, data)

{'fraction_non_alphanumeric': 0.10128865979381443, 'fraction_numerical': 0.013573883161512028, 'mean_word_length': 2.761227786752827, 'pattern_counts': {'":': 2, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4400198', 'n_tokens_mistral': 3717, 'n_tokens_neox': 3544, 'n_words': 1028}