DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Revolutionizing Algorithmic Trading: The Power of Reinforcement Learning
  • SRE vs. DevOps
  • 5 Key Concepts for MQTT Broker in Sparkplug Specification
  • How To Approach Java, Databases, and SQL [Video]

Trending

  • Revolutionizing Algorithmic Trading: The Power of Reinforcement Learning
  • SRE vs. DevOps
  • 5 Key Concepts for MQTT Broker in Sparkplug Specification
  • How To Approach Java, Databases, and SQL [Video]
  1. DZone
  2. Coding
  3. Languages
  4. Converting Markdown to PDF with PHP

Converting Markdown to PDF with PHP

Matt Farina user avatar by
Matt Farina
·
Mar. 28, 14 · Interview
Like (0)
Save
Tweet
Share
9.02K Views

Join the DZone community and get the full member experience.

Join For Free

Recently, I had to take some content in markdown, specifically markdown extra, and convert it to a series of PDFs styled with a specific branding. While some will argue that PDFs are dead and “long live the web”, many of us still need to produce PDFs for one reason or another.

In this case I had to take markdown extra, with some html sprinkled in, clean it up, and convert it to a styled PDF. What follows is how I did that using QueryPath for the cleanup and DOMPDF to make the conversion.

The Setup

At the root of this little app was a PHP script with the dependencies managed through composer. The composer.json file looked like:

{
    "name": "foo/bar",
    "description": "Convert markdown to PDF.",
    "type": "application",
    "require": {
        "php": ">=5.3.0",
        "michelf/php-markdown": "1.4.*",
        "dompdf/dompdf" : "0.6.*",
        "querypath/querypath": "3.*",
        "masterminds/html5": "1.*"
    }
}

Turning the Markdown into HTML

Within the script I started with a file we’ll call $file. Form here it was easy using the official markdown extra conversion utility.

$markdown = file_get_contents($file);
$markdownParser = new \Michelf\MarkdownExtra();
$html = $markdownParser->transform($markdown);

This produces the html needed to go inside the body of an html page. From here I wrapped it in a document because I could easily link to a CSS file for styling purposes. DOMPDF supports quite a bit of CSS 2.1.

$html = '<html>
    <head>
        <link rel="stylesheet" type="text/css" href="pdf.css">
    </head>
    <body>' . $html . '</body>
    </html>’;

pdf.css is where you can style the PDF. If you know how to style web pages using CSS you can manage to style a PDF document.

Cleaning Up The Content

There were a number of places html had been injected into the markdown that was either broken, unwanted in a PDF, or an edge case that DOMPDF didn’t support. To make these changes I used QueryPath. For example, I needed to take relative links, normally used in generation of a website, and add a domain name to them:

$dom = \HTML5::loadHTML($html);
$links = htmlqp($dom, 'a');
foreach ($links as $link) {
    $href = $link->attr('href');
    if (substr($href, 0, 1) == '/' && substr($href, 1, 1) != '/') {
        $link->attr('href', $domain_name . $href);
    }
}
$html = \HTML5::saveHTML($dom);

Note, I used the HTML5 parser and writer rather than the built-in one designed for xhtml and HTML 4. This is because DOMPDF attempts to work with HTML5 and I wanted to keep that consistent from the beginning.

Converting to PDF

There is a little setup before using DOMPDF. It has a built in autoloader which should be disabled and needs a config file. In my case I used the default config file and handled this with:

define('DOMPDF_ENABLE_AUTOLOAD', false);
require_once __DIR__ . '/vendor/dompdf/dompdf/dompdf_config.inc.php';

The conversion was fairly straight forward. I used a snippet like:

$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();  
$output = $dompdf->output();
file_put_contents(‘path/to/file.pdf', $output);

DOMPDF has a lot of options and some quirks. It wasn’t exactly designed for composer. For example, if you want to work with custom fonts you need to get the project from git and install submodules.

Despite the quirks, needing to cleanup some of the html, and brand the documents, I was able to write a conversion script that handled dozens of documents quickly. Almost all of my time was on html cleanup and css styling.


PDF PHP

Published at DZone with permission of Matt Farina, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Revolutionizing Algorithmic Trading: The Power of Reinforcement Learning
  • SRE vs. DevOps
  • 5 Key Concepts for MQTT Broker in Sparkplug Specification
  • How To Approach Java, Databases, and SQL [Video]

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: