js实现markdown转html转pdf

话不多说直接上代码

将下面的代码复制,保存为html文件在游览器中打开即可使用
按 ctrl+p 也可转pdf js实现的pdf实际为截图后保存为pdf

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>md2html</title>
    <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/marked/0.3.4/marked.min.js"></script>
    <script src="https://linwalker.github.io/render-html-to-pdf/js/html2canvas.js"></script>
    <script src="https://linwalker.github.io/render-html-to-pdf/js/jsPdf.debug.js"></script>
    <script src="http://cdn.bootcss.com/highlight.js/8.0/highlight.min.js"></script>
        <style>
        .hljs-comment,.hljs-quote {
 color:#989498
}
.hljs-variable,.hljs-template-variable,.hljs-attribute,.hljs-tag,.hljs-name,.hljs-selector-id,.hljs-selector-class,.hljs-regexp,.hljs-link,.hljs-deletion {
 color:#dd464c
}
.hljs-number,.hljs-built_in,.hljs-builtin-name,.hljs-literal,.hljs-type,.hljs-params {
 color:#fd8b19
}
.hljs-class .hljs-title {
 color:#fdcc59
}
.hljs-string,.hljs-symbol,.hljs-bullet,.hljs-addition {
 color:#8fc13e
}
.hljs-meta {
 color:#149b93
}
.hljs-function,.hljs-section,.hljs-title {
 color:#1290bf
}
.hljs-keyword,.hljs-selector-tag {
 color:#c85e7c
}
.hljs {
 display:block;
 background:#322931;
 color:#b9b5b8;
 padding:0.5em
}
.hljs-emphasis {
 font-style:italic
}
.hljs-strong {
 font-weight:bold
}

    #edit {display: flex; justify-content: space-between;}
    #content {width: 49%;float: left;height: auto;}
    .button {
        color: #fff;
        background-color: #009a61;
        border-color: #008151;
        padding: 0 13px;
        font-size: 14px;
        border-radius: 4px;
        margin: 10px;
    }
    #show{width: 50%; border:  1px solid  #ddd; padding: 50px; box-sizing: border-box;float: left;height: auto;}
    @charset "utf-8";



#showHtml {
    border: 0 none;
    margin: 0 auto;
    max-width: 850px;
    overflow-x: hidden;
    padding-bottom: 50px;
    position: relative;
}

html {
  color: #333;
  background: #fff;
  -webkit-text-size-adjust: 100%;
  -ms-text-size-adjust: 100%;
  text-rendering: optimizelegibility;
}


html.borderbox *, html.borderbox *:before, html.borderbox *:after {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}


body, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, code, form, fieldset, legend, input, textarea, p, blockquote, th, td, hr, button, article, aside, details, figcaption, figure, footer, header, menu, nav, section {
  margin: 0;
  padding: 0;
}

article, aside, details, figcaption, figure, footer, header, menu, nav, section {
  display: block;
}


audio, canvas, video {
  display: inline-block;
}


body, button, input, select, textarea {
  font: 300 1em/1.8 PingFang SC, Lantinghei SC, Microsoft Yahei, Hiragino Sans GB, Microsoft Sans Serif, WenQuanYi Micro Hei, sans-serif;
}

button::-moz-focus-inner,
input::-moz-focus-inner {
  padding: 0;
  border: 0;
}


table {
  border-collapse: collapse;
  border-spacing: 0;
}

fieldset, img {
  border: 0;
}

blockquote {
  position: relative;
  color: #999;
  font-weight: 400;
  border-left: 1px solid #1abc9c;
  padding-left: 1em;
  margin: 1em 3em 1em 2em;
}

@media only screen and ( max-width: 640px ) {
  blockquote {
    margin: 1em 0;
  }
}


acronym, abbr {
  border-bottom: 1px dotted;
  font-variant: normal;
}


abbr {
  cursor: help;
}

/* 一致的 del 样式 */
del {
  text-decoration: line-through;
}

address, caption, cite, code, dfn, em, th, var {
  font-style: normal;
  font-family: "Comic Sans MS", Monaco, Courier, "Courier New", monospace;
  font-size: 15px;
}

ul, ol {
  list-style: none;
}


caption, th {
  text-align: left;
}

q:before, q:after {
  content: '';
}

/* 统一上标和下标 */
sub, sup {
  font-size: 75%;
  line-height: 0;
  position: relative;
}

:root sub, :root sup {
  vertical-align: baseline; /* for ie9 and other modern browsers */
}

sup {
  top: -0.5em;
}

sub {
  bottom: -0.25em;
}


a {
  color: #1abc9c;
}

a:hover {
  text-decoration: underline;
}

.typo a {
  border-bottom: 1px solid #1abc9c;
}

.typo a:hover {
  border-bottom-color: #555;
  color: #555;
  text-decoration: none;
}


ins, a {
  text-decoration: none;
}

u, .typo-u {
  text-decoration: underline;
}


mark {
  background: #fffdd1;
  border-bottom: 1px solid #ffedce;
  padding: 2px;
  margin: 0 5px;
}

pre, code, pre tt {
  font-family: "Comic Sans MS", Monaco, Courier, "Courier New", monospace;
}

pre {
  background: #f3f5f0;
  border: 1px solid #ddd;
  padding: 1em 1.5em;
  display: block;
  -webkit-overflow-scrolling: touch;
}


hr {
  border: none;
  border-bottom: 1px solid #cfcfcf;
  margin-bottom: 0.8em;
  height: 10px;
}

small, .typo-small,
figcaption {
  font-size: 0.9em;
  color: #888;
}

strong, b {
  font-weight: bold;
  color: #000;
}


[draggable] {
  cursor: move;
}

.clearfix:before, .clearfix:after {
  content: "";
  display: table;
}

.clearfix:after {
  clear: both;
}

.clearfix {
  zoom: 1;
}

.textwrap, .textwrap td, .textwrap th {
  word-wrap: break-word;
  word-break: break-all;
}

.textwrap-table {
  table-layout: fixed;
}


.serif {
  font-family: Palatino, Optima, Georgia, serif;
}


.typo p, .typo pre, .typo ul, .typo ol, .typo dl, .typo form, .typo hr, .typo table,
.typo-p, .typo-pre, .typo-ul, .typo-ol, .typo-dl, .typo-form, .typo-hr, .typo-table, blockquote {
  margin-bottom: 1.2em;
}
.typo p {  
  text-indent: 2em;
}
.typo code {
 color: #c7254e;
 font-size: .92857em;
 background-color: #f3f3f3;
}
.typo pre code{
  color: #333;
}
h1, h2, h3, h4, h5, h6 {
  font-family: PingFang SC, Verdana, Helvetica Neue, Microsoft Yahei, Hiragino Sans GB, Microsoft Sans Serif, WenQuanYi Micro Hei, sans-serif;
  font-weight: 100;
  color: #000;
  line-height: 1.35;
}

.typo h1, .typo h2, .typo h3, .typo h4, .typo h5, .typo h6,
.typo-h1, .typo-h2, .typo-h3, .typo-h4, .typo-h5, .typo-h6 {
  margin-top: 1.2em;
  margin-bottom: 0.6em;
  line-height: 1.35;
}

.typo h1, .typo-h1 {
  font-size: 2em;
}

.typo h2, .typo-h2 {
  font-size: 1.8em;
}

.typo h3, .typo-h3 {
  font-size: 1.6em;
}

.typo h4, .typo-h4 {
  font-size: 1.4em;
}

.typo h5, .typo h6, .typo-h5, .typo-h6 {
  font-size: 1.2em;
}


.typo ul, .typo-ul {
  margin-left: 1.3em;
  list-style: disc;
}

.typo ol, .typo-ol {
  list-style: decimal;
  margin-left: 1.9em;
}

.typo li ul, .typo li ol, .typo-ul ul, .typo-ul ol, .typo-ol ul, .typo-ol ol {
  margin-bottom: 0.8em;
  margin-left: 2em;
}

.typo li ul, .typo-ul ul, .typo-ol ul {
  list-style: circle;
}

.typo table th, .typo table td, .typo-table th, .typo-table td, .typo table caption {
  border: 1px solid #ddd;
  padding: 0.5em 1em;
  color: #666;
}

.typo table th, .typo-table th {
  background: #fbfbfb;
}

.typo table thead th, .typo-table thead th {
  background: #f1f1f1;
}

.typo table caption {
  border-bottom: none;
}


.typo-input, .typo-textarea {
  -webkit-appearance: none;
  border-radius: 0;
}

.typo-em, .typo em, legend, caption {
  color: #000;
  font-weight: inherit;
}


.typo-em {
  position: relative;
}

.typo-em:after {
  position: absolute;
  top: 0.65em;
  left: 0;
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-indent: 0;
  content: "・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・・";
}

/* Responsive images */
.typo img {
  max-width: 100%;
}
    </style>
</head>
<body id="edit">
<div><button id="download" class="button">下载html</button><button class="button" id="downloadPdf">下载PDF</button></div>
<textarea  id="content"></textarea> 
<div id="show" class="typo"></div>
<script>
    marked.setOptions({
        renderer: new marked.Renderer(),
        gfm: true,
        tables: true,
        escaped : true,
        breaks: false,
        pedantic: false,
        sanitize: false,
        smartLists: true,
        smartypants: false,
        highlight: function (code, lang) {
        return hljs.highlightAuto(code).value;
      }
    });

    $("#content").on("input  propertychange", function() {
        var val = $(this).val();
        $("#show").html(marked(val));
    });


    function downloadFile(fileName, content){
      var aLink = document.createElement('a');
      var blob = new Blob([content]);
      var evt = document.createEvent("HTMLEvents");
      aLink.download = fileName;
      aLink.href = URL.createObjectURL(blob);
      aLink.click();
    }



    $("#download").click(e=>{
      var tpl = new Template($('#tpl').html());
      var s = tpl.render({
          title: "markdown",
          style:$("style").html(),
          content:$("#show").html()
      });
      downloadFile("markdown.html",s);
    });


  function Template(tpl) {
      var
          fn,
          match,
          code = ['var r=[];\nvar _html = function (str) { return str; };'],
          re = /\{\s*([a-zA-Z\.\_0-9()]+)(\s*\|\s*safe)?\s*\}/m,
          addLine = function (text) {
              code.push('r.push(\'' + text.replace(/\'/g, '\\\'').replace(/\n/g, '\\n').replace(/\r/g, '\\r') + '\');');
          };
      while (match = re.exec(tpl)) {
          if (match.index > 0) {
              addLine(tpl.slice(0, match.index));
          }
          if (match[2]) {
              code.push('r.push(String(this.' + match[1] + '));');
          }
          else {
              code.push('r.push(_html(String(this.' + match[1] + ')));');
          }
          tpl = tpl.substring(match.index + match[0].length);
      }
      addLine(tpl);
      code.push('return r.join(\'\');');
      fn = new Function(code.join('\n'));
      this.render = function (model) {
          return fn.apply(model);
      };
    }

$("#downloadPdf").click(e=>{
    html2canvas($('#show')[0], {
      onrendered:function(canvas) {

          var contentWidth = canvas.width;
          var contentHeight = canvas.height;

          //一页pdf显示html页面生成的canvas高度;
          var pageHeight = contentWidth / 592.28 * 841.89;
          //未生成pdf的html页面高度
          var leftHeight = contentHeight;
          //页面偏移
          var position = 0;
          //a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
          var imgWidth = 595.28;
          var imgHeight = 592.28/contentWidth * contentHeight;

          var pageData = canvas.toDataURL('image/jpeg', 1.0);

          var pdf = new jsPDF('', 'pt', 'a4');

          //有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
          //当内容未超过pdf一页显示的范围,无需分页
          if (leftHeight < pageHeight) {
          pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight );
          } else {
              while(leftHeight > 0) {
                  pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
                  leftHeight -= pageHeight;
                  position -= 841.89;
                  //避免添加空白页
                  if(leftHeight > 0) {
                    pdf.addPage();
                  }
              }
          }

          pdf.save('content.pdf');
      }
    })
}); 



</script>

<script id="tpl" type="text/plain">
  <html>
    <head>
      <title>{title}</title>
      <style>{style}</style>
    </head>
    <body>
      <div id="showHtml" class="typo">
          {content}
      </div>
    </body>
  </html>
</script>

</body>
</html>

猜你喜欢

转载自blog.csdn.net/isyoungboy/article/details/81286611