Skip to content

Exporters API Reference

This page documents the exporter modules of Medium Converter.

Base Exporter

medium_converter.exporters.base.BaseExporter

Base class for all exporters.

export(article, output=None) abstractmethod

Export an article to the target format.

PARAMETER DESCRIPTION
article

The article to export

TYPE: Article

output

Optional output file path or file-like object

TYPE: str | TextIO | BinaryIO | None DEFAULT: None

RETURNS DESCRIPTION
str | bytes

The exported content as string or bytes

Source code in medium_converter/exporters/base.py
@abstractmethod
def export(
    self, article: Article, output: str | TextIO | BinaryIO | None = None
) -> str | bytes:
    """Export an article to the target format.

    Args:
        article: The article to export
        output: Optional output file path or file-like object

    Returns:
        The exported content as string or bytes
    """
    pass

Markdown Exporter

medium_converter.exporters.markdown.MarkdownExporter

Export Medium articles to Markdown format.

export(article, output=None)

Export an article to Markdown.

PARAMETER DESCRIPTION
article

The article to export

TYPE: Article

output

Optional output file path or file-like object

TYPE: str | TextIO | BinaryIO | None DEFAULT: None

RETURNS DESCRIPTION
str

The exported content as string

Source code in medium_converter/exporters/markdown.py
def export(
    self, article: Article, output: str | TextIO | BinaryIO | None = None
) -> str:
    """Export an article to Markdown.

    Args:
        article: The article to export
        output: Optional output file path or file-like object

    Returns:
        The exported content as string
    """
    md_content = f"# {article.title}\n\n"
    md_content += f"By {article.author} | {article.date}\n\n"

    if article.tags:
        tags = ", ".join([f"#{tag.replace(' ', '')}" for tag in article.tags])
        md_content += f"{tags}\n\n"

    if article.estimated_reading_time:
        md_content += f"*{article.estimated_reading_time} min read*\n\n"

    # Process content
    for item in article.content:
        if isinstance(item, Section):
            if item.title:
                md_content += f"## {item.title}\n\n"

            for block in item.blocks:
                md_content += self._format_block(block)
        elif isinstance(item, ContentBlock):
            md_content += self._format_block(item)

    # Write to file if specified
    if output:
        if isinstance(output, str):
            with open(output, "w", encoding="utf-8") as f:
                f.write(md_content)
        else:
            # We need to check the type to avoid mypy errors
            if hasattr(output, "write") and callable(output.write):
                if isinstance(output, BinaryIO):
                    output.write(md_content.encode("utf-8"))
                else:
                    # Assume TextIO
                    output.write(md_content)

    return md_content

PDF Exporter

medium_converter.exporters.pdf.PDFExporter

Export Medium articles to PDF format.

export(article, output=None)

Export an article to PDF.

PARAMETER DESCRIPTION
article

The article to export

TYPE: Article

output

Optional output file path or file-like object

TYPE: str | TextIO | BinaryIO | None DEFAULT: None

RETURNS DESCRIPTION
bytes

The exported content as bytes

Source code in medium_converter/exporters/pdf.py
def export(
    self, article: Article, output: str | TextIO | BinaryIO | None = None
) -> bytes:
    """Export an article to PDF.

    Args:
        article: The article to export
        output: Optional output file path or file-like object

    Returns:
        The exported content as bytes
    """
    try:
        from io import BytesIO

        # reportlab imports
        from reportlab.lib import colors
        from reportlab.lib.pagesizes import A4
        from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
        from reportlab.lib.units import inch
        from reportlab.platypus import (
            Paragraph,
            SimpleDocTemplate,
            Spacer,
        )
    except ImportError as err:
        raise ImportError(
            "PDF export requires reportlab."
            "Install with 'pip install medium-converter[pdf]'"
        ) from err

    # Create a buffer for the PDF
    buffer = BytesIO()

    # Create the PDF document
    doc = SimpleDocTemplate(
        buffer if output is None else output if isinstance(output, str) else buffer,
        pagesize=A4,
        title=article.title,
        author=article.author,
    )

    # Get styles
    styles = getSampleStyleSheet()
    title_style = styles["Title"]
    styles["Heading1"]
    styles["Heading2"]
    normal_style = styles["Normal"]

    # Create PDF elements
    elements = []

    # Add title
    elements.append(Paragraph(article.title, title_style))
    elements.append(Spacer(1, 0.2 * inch))

    # Add author and date
    elements.append(
        Paragraph(f"By {article.author} | {article.date}", normal_style)
    )
    elements.append(Spacer(1, 0.2 * inch))

    # Add reading time if available
    if article.estimated_reading_time:
        elements.append(
            Paragraph(
                f"{article.estimated_reading_time} min read",
                ParagraphStyle(
                    "Italic", parent=normal_style, textColor=colors.gray
                ),
            )
        )
        elements.append(Spacer(1, 0.2 * inch))

    # Example code to process content (placeholder)
    elements.append(
        Paragraph(
            "Content will be rendered here in the actual implementation",
            normal_style,
        )
    )

    # Build the PDF
    doc.build(elements)

    # Get the PDF content
    pdf_content = buffer.getvalue()
    buffer.close()

    # Write to file if specified and not already written
    if output and isinstance(output, str):
        with open(output, "wb") as f:
            f.write(pdf_content)

    return pdf_content