def transform_img_to_latex(image: Image):

    url = image.url
    label = image.identifier
    caption = image.content

    log("Transforming image '{0}' to latex ...", fName, url)

    # Set `/fig.png` to `./fig.png`
    if os.path.isabs(url):
        url = "." + os.path.splitdrive(url)[1]

    baseCommand = None
    blockBuilder = None
    graphicsOpts = {}

    if "includepdf" in image.classes:
        baseCommand = r"includePDF"
        blockBuilder = include_pdf
    else:
        baseCommand = r"imageWithCaption"
        if os.path.splitext(url)[1] == ".svg":
            baseCommand = r"svgWithCaption"
        blockBuilder = include_image

    # Parse witdh/height
    def to_scaling(size: Union[str, None], proportionalTo: str):
        if size and "%" in size:
            s = float(size.strip().replace("%", "")) / 100.0
            return "{0}{1}".format(s, proportionalTo)
        else:
            return size

    width = to_scaling(
        image.attributes.get("width", None),
        proportionalTo=r"\textwidth",
    )
    height = to_scaling(
        image.attributes.get("height", None),
        proportionalTo=r"\textwidth",
    )

    log(" - height: {0}, width: {1}", fName, height, width)

    if width:
        graphicsOpts["width"] = "{0}".format(width)
    if height:
        graphicsOpts["height"] = "{0}".format(height)

    return blockBuilder(
        image.attributes,
        baseCommand,
        url,
        caption,
        graphicsOpts,
        label,
    )
def include_pdf(
    attributes,
    baseCommand,
    url,
    caption,
    graphicsOpts,
    label=None,
):

    pages = attributes.get("pages", None)  # Insert all pages
    pageStart = 1

    try:
        if not pages:
            pageEnd = get_pdf_pages(url)
        else:
            if "-" in pages:
                p = pages.split("-")
                if p[0]:
                    pageStart = int(p[0])

                if p[1]:
                    pageEnd = int(p[1])
                else:
                    pageEnd = get_pdf_pages(url)
            else:
                pageEnd = int(p)
    except ValueError:
        raise ValueError("Wrong pages attribute '{0}' for '{1}'".format(
            pages,
            url,
        ))

    if not pageEnd:
        log(
            "You need to specify the pages atrribute as 'pages=[<start-page>-]<end-page>",
            fName,
        )
        raise ValueError("Pages could not be determined")

    if "width" not in graphicsOpts:
        graphicsOpts["width"] = r"\textwidth"

    opts = ["{0}={1}".format(k, v) for k, v in graphicsOpts.items()]

    log(" - page start: {0}, page end {1}", fName, pageStart, pageEnd)
    return [
        latexblock(r"\{0}{{{1}}}[{2}]{{{3}}}[{4}]".format(
            baseCommand,
            url,
            str(pageStart),
            str(pageEnd),
            ",".join(opts),
        )),
    ]
示例#3
0
def tee(clear=False):
    input_stream = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8')

    source = input_stream.read()
    file = None

    if len(sys.argv) >= 3:
        for a in sys.argv[2:]:
            if a == "--clear":
                clear = True
            else:
                file = a

    if clear and os.path.exists(flags.teeOutput):
        log("Clear output '{0}'", fName, flags.teeOutput)
        shutil.rmtree(flags.teeOutput)

    if not file:
        if not os.path.exists(flags.teeOutput):
            os.makedirs(flags.teeOutput)

        file = os.path.join(flags.teeOutput, "tee")

        # Increment counter ...
        i = 1

        def filename(x):
            return file + "-{0}.json".format(x)

        t = filename(i)
        while os.path.exists(t):
            i += 1
            t = filename(i)
        file = t

    if file:
        log("Write pandoc AST to '{0}'", fName, file)
        js = json.loads(source)
        with open(file, "w") as f:
            json.dump(js, f, indent=4)

    # Pass it on
    sys.stdout.write(source)
def get_pdf_pages(url):
    pages = None
    try:
        cmd = None
        if sys.platform == "linux":
            cmd = ["pdfinfo", url]
            info = yaml.safe_load(subprocess.check_output(cmd))
            pages = info.get("Pages", None)
            if not pages:
                pages = info.get("pages", None)
        elif sys.platform == "darwin":
            cmd = ["mdls", "-name", "kMDItemNumberOfPages", "-raw", url]
            pages = int(subprocess.check_output(cmd, encoding="utf-8").strip())

    except Exception as e:
        log("Command '{0}' failed for '{1}':", fName, cmd, url)
        log(str(e), fName)

    return pages if pages else None