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 Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Document Generation API: How to Automate Personalized Document Creation at Scale
  • Beyond Extensions: Architectural Deep-Dives into File Upload Security
  • Extracting Clean Excel Tables From PDFs Using Python + Docling
  • How Laravel Developers Handle Database Migrations Without Downtime

Trending

  • The Latency Tax That’s Hidden in Cloud-Native Systems (and the Hard Lessons I Learned to Minimize It)
  • How to Set MX Records via API: Automate Email Routing Programmatically
  • The Trust Problem in Modern SaaS: Why Your Authentication Succeeded, and You Still Got Breached
  • The Cross-Lingual RAG Problem Nobody Is Talking About
  1. DZone
  2. Coding
  3. Languages
  4. Converting Markdown to PDF with PHP

Converting Markdown to PDF with PHP

By 
Matt Farina user avatar
Matt Farina
·
Mar. 28, 14 · Interview
Likes (0)
Comment
Save
Tweet
Share
10.0K 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. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Document Generation API: How to Automate Personalized Document Creation at Scale
  • Beyond Extensions: Architectural Deep-Dives into File Upload Security
  • Extracting Clean Excel Tables From PDFs Using Python + Docling
  • How Laravel Developers Handle Database Migrations Without Downtime

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook