Example of Making Documentation in Markdown with PDF Output

Posted: 2018-01-05 17:43:43

Many of the sites I make have a need for a Support page for staff to know how to do things like add content, manage users etc. This article will cover how I go about writing my help docs in Markdown and then displaying it on the website with an option to print as PDF.

Writing MarkDown

To begin with, I made the help doc in mine. I made a sample one here

I save this to the root of the application docs/help.md

Output the Help Page Markdown to HTML

So there are two things I want out of this, a TOC and the Markdown.

First I will install the needed libraries.

composer require cebe/markdown:~1.1.1 laravelista/sherlock

Then I make a controller php artisan make:controller HelpController and add a method show:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use cebe\markdown\GithubMarkdown;
use Laravelista\Sherlock\Sherlock;

class HelpController extends Controller
{


    public function show(GithubMarkdown $markdown_writer, Sherlock $sherlock)
    {
        $path = base_path("docs/help.md");
        $help = \File::get($path);
        $toc = $sherlock->deduct($help)->getToc();

        $help = $markdown_writer->parse($help);

        $help = $toc . '<hr>' . $help;

        return view('help', compact("help"));
    }
}
Route::get("help", "HelpController@show")->name("help");

adding to my web.php file: And a simple blade template to show the content:

@extends('layouts.app')
<!-- -->
@section('content')

<div class="panel panel-default">
    @section('title', 'Example Help')
    <div class="panel-heading">Example Help Output</div>
    <div class="panel-body">
                {!! $help !!}
    </div>
</div>

@endsection

You can see the output here

The author of the Sherlock library suggests a different way to inject the info but I opted for this. It will make more sense when I do the PDF output.

On the top of that page is a PDF link here is how I can provide that as well.

Output to PDF

Install the needed library.

composer require barryvdh/laravel-dompdf

note I did have to install php7.1-gd and php7.1-dom php7.1-opcache

adding to my web.php file:

Route::get("pdf", "HelpController@pdf")->name("pdf");

And update the controller to have a pdf method:

    public function pdf(GithubMarkdown $markdown_writer, Sherlock $sherlock)
    {
        $path = base_path("docs/help.md");
        $help = \File::get($path);
        $toc = $sherlock->deduct($help)->getToc();

        $help = $markdown_writer->parse($help);

        $help = $toc . '<hr>' . $help;

        return \PDF::loadHTML($help)->stream();
    }

Note: this is a good time to move the injected Classes into a __costructor since they are using in two methods in the same class

Alright, now when you click the link o the help page it will output an inline PDF.