Hugo 页面嵌入 pdf 预览

计划在 Hugo 中启用 pdf 预览功能,这可以用 anvithks 制作的模板库 实现。在此基础上对模板样式做了调整。

安装

按照其 GitHub 主页的指示将相应内容加入我的 noteworthy 模板。

  1. 添加 shortcodes

[theme]/layouts/shortcodes目录下添加 embed-pdf.html ,内容可以复制模板库下相同位置的文件。

cp [hugo-embed-pdf-shortcode-master]/layouts/shortcodes/embed-pdf.html [theme]/layouts/shortcodes/embed-pdf.html
  1. 添加 pdf.js 库到模板的静态文件库 [theme]/static/js/ 中。
cp -R [hugo-embed-pdf-shortcode-master]/static/js/pdf-js [theme]/static/js/

使用

博客源文件按下图组织:

./content/posts
  |_ myblogwithpdfembed
     |_ sample.pdf
     |_ index.md
  |_otherpost.md

首先 index.md 的文件名不要更改,然后在 index.md 中通过如下方式引用:

{{ < embed-pdf url="./sample.pdf"  > }}
{{ < embed-pdf url="./sample.pdf" hidePaginator="true" > }}
{{ < embed-pdf url="./path/to/your/file.pdf" hideLoader="true"  > }}

优化

  1. 导航样式修正

受主题的影响,导航按钮不居中,发现 Paginatorcss block,其中的元素默认左对齐。因此修改 embed-pdf.html,在其中给 Paginator 加入对齐属性。

  //PDF NAVIGATION
  .pdf-paginator {
    text-align:center;
  1. 隐藏下载按钮

修改 embed-pdf.html,在其中将下载按钮隐藏。

//hide download button
#overlayText {
display: none;
}
  1. 增加对 pdf 源链接的显示控制

script标签里加入对 pdf-source 的控制,依次加入如下代码

var showSource = "{{ .Get "showSource" }}" === "true";
//...
var pageSource=document.getElementById("pdf-source-{{ substr (.Get "url" | md5) 0 8 }}");
//...
showSourcef();
//...
/**
 * If we haven't disabled the souce, show source link
 */
function showSourcef() {
  if(showSource) {return
    pageSource.style.display = 'inline';
  } else {
    pageSource.style.display = 'none';
  }
} 

这样,可以通过下面的方式选择是否显示源链接。

{{ < embed-pdf url="./path/to/your/file.pdf" showSource="true"  > }}

示例

下面是隐藏源链接的示例。

    / [pdf]

参考链接

Hugo Docs - Page Resources

GitHub - hugo-embed-pdf-shortcode

Show a pdf file in a static site based on Hugo