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

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
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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Google Cloud Document AI Basics
  • How to Convert Between PDF and TIFF in Java
  • Thumbnail Generator Microservice for PDF in Spring Boot
  • Inheritance in PHP: A Simple Guide With Examples

Trending

  • Integrating Security as Code: A Necessity for DevSecOps
  • Unlocking the Potential of Apache Iceberg: A Comprehensive Analysis
  • Beyond ChatGPT, AI Reasoning 2.0: Engineering AI Models With Human-Like Reasoning
  • Measuring the Impact of AI on Software Engineering Productivity
  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
9.7K 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.

Related

  • Google Cloud Document AI Basics
  • How to Convert Between PDF and TIFF in Java
  • Thumbnail Generator Microservice for PDF in Spring Boot
  • Inheritance in PHP: A Simple Guide With Examples

Partner Resources

×

Comments

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: