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

示例

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

参考链接

Hugo Docs - Page Resources

GitHub - hugo-embed-pdf-shortcode

Show a pdf file in a static site based on Hugo

内容声明与版权协议

  • 版权协议:本文采用 CC BY-NC-SA 4.0(署名-非商业性使用-相同方式共享) 协议进行许可。转载、演绎请务必保留作者署名及原文链接,且不得用于商业目的。
  • AI 辅助说明:本博客部分内容(如排版设计、个别局部、特定对话片段等)可能由 AI(LLM大语言模型)辅助生成。作者在此明确声明:本人对文章的核心框架、思想立论与最终呈现拥有绝对主导权与最终解释权。
  • 观点免责:文中明示的由 AI 生成的特定文本、对话输出,仅作为理性探讨以及观点展示,不代表本人真实立场、价值观或事实背书。对于因 AI 幻觉造成的客观事实偏差,请读者审慎甄别。
  • 认知时效性:文章仅代表作者在撰写当下的认知状态与情绪切片。随着个人心智迭代与客观事物发展,作者观点可能发生演变。欢迎基于理性的交流与批评。