JavaScript 控制台脚本实战:CSDN 文章 5 秒内一键导出纯净 PDF JavaScript 控制台脚本实战5秒内一键导出CSDN文章为纯净PDF每次在CSDN上阅读技术文章时是否曾被侧边栏推荐、底部广告和无关内容干扰作为开发者我们经常需要保存优质技术文章供离线阅读或归档但直接打印或导出PDF往往会包含大量冗余元素。本文将分享一个经过实战检验的JavaScript控制台脚本解决方案它能智能识别并清除页面干扰元素5秒内生成只保留核心内容的纯净PDF。1. 为什么需要定制化PDF导出方案传统浏览器打印功能在处理技术文章平台时存在几个明显痛点内容截断问题代码块和长段落经常被分页切断冗余元素干扰广告、推荐栏、用户评论等非核心内容被保留样式丢失原始页面的代码高亮、排版格式无法正确保留手动操作繁琐需要逐个隐藏页面元素无法实现一键操作我们开发的解决方案针对CSDN的文章页面结构进行了深度优化主要实现以下核心功能自动展开全文内容解决按钮问题精准移除12类非内容元素顶部导航、侧边栏、广告位等智能调整打印布局避免代码块被截断保留文章原始样式包括代码高亮、图片等添加PDF元信息自动提取文章标题作为文件名// 基础功能示例移除顶部导航和侧边栏 document.querySelector(#csdn-toolbar).remove(); document.querySelector(#mainBox aside).remove();2. 完整脚本解析与使用指南2.1 增强版脚本代码以下是经过多次迭代优化的完整脚本已处理CSDN各种页面变体和边缘情况(function exportCSDNToPDF() { use strict; // 1. 自动展开所有折叠内容 const expandAll () { const readMoreBtn document.querySelector(#btn-readmore); if (readMoreBtn) readMoreBtn.click(); const codeExpandBtns document.querySelectorAll(.hide-preCode-bt); codeExpandBtns.forEach(btn { if (btn.textContent.includes(展开)) btn.click(); }); // 处理新版CSDN的折叠段落 const foldButtons document.querySelectorAll(.article-content-fold); foldButtons.forEach(btn btn.click()); }; // 2. 移除非内容元素 const removeElements () { // 顶部导航和工具栏 const headerSelectors [ #csdn-toolbar, .blog-header-box, .csdn-top-toolbar, .toolbar-inside ]; // 侧边栏和推荐内容 const sidebarSelectors [ #asideFooter, #asideHotArticle, #recommendAdBox, .recommend-box, .template-box ]; // 底部冗余信息 const footerSelectors [ .blog-footer-bottom, .article-info-box, .comment-box, .skill-tree-box ]; // 广告和推广元素 const adSelectors [ [id^pop_], .passport-login-container, .csdn-side-toolbar ]; // 合并所有选择器并执行删除 const allSelectors [ ...headerSelectors, ...sidebarSelectors, ...footerSelectors, ...adSelectors ].join(,); document.querySelectorAll(allSelectors).forEach(el el.remove()); }; // 3. 调整内容区域样式 const adjustStyles () { const content document.querySelector(article) || document.querySelector(.article_content); if (content) { // 移除可能影响打印的内联样式 content.style.height auto; content.style.overflow visible; content.style.width 100%; content.style.padding 0; content.style.margin 0; // 确保代码块不被分页切断 const codeBlocks content.querySelectorAll(pre); codeBlocks.forEach(pre { pre.style.pageBreakInside avoid; pre.style.whiteSpace pre-wrap; }); } // 调整全局打印设置 document.body.style.zoom 90%; document.body.style.padding 20px; }; // 4. 执行所有操作并触发打印 const execute () { try { expandAll(); removeElements(); adjustStyles(); // 添加打印完成后的回调可选 const restorePage () { setTimeout(() location.reload(), 1000); }; window.addEventListener(afterprint, restorePage); window.print(); } catch (error) { console.error(PDF导出出错:, error); alert(导出失败请打开控制台查看详情); } }; // 立即执行 execute(); })();2.2 使用说明只需简单三步即可使用该脚本在CSDN文章页面按下F12或CtrlShiftI打开开发者工具切换到 Console (控制台) 标签页粘贴上述完整代码并回车脚本会自动执行以下操作流程展开所有折叠的内容区域移除20类干扰元素优化打印布局和样式触发浏览器打印对话框提示在打印对话框中选择目标打印机为另存为PDF即可生成PDF文件。建议勾选背景图形选项以保留语法高亮等样式。3. 高级功能与定制技巧3.1 脚本参数调优通过修改脚本中的参数可以适应不同需求参数默认值说明zoom90%页面缩放比例解决内容截断问题margin0内容区域外边距单位pxcodeWraptrue是否自动换行长代码行// 示例调整缩放比例和边距 document.body.style.zoom 85%; document.querySelector(.article_content).style.margin 15px;3.2 跨平台兼容方案针对不同浏览器的打印差异我们准备了兼容性处理代码// 检测浏览器类型 const isFirefox navigator.userAgent.includes(Firefox); const isChrome navigator.userAgent.includes(Chrome); // 浏览器特定调整 if (isFirefox) { document.body.style.width 95%; // Firefox需要更窄的宽度 } else if (isChrome) { document.querySelector(main).style.padding 10px; } // 备用打印方案 const fallbackPrint () { const printContent document.querySelector(.article_content).innerHTML; const originalContent document.body.innerHTML; document.body.innerHTML printContent; window.print(); document.body.innerHTML originalContent; };3.3 错误处理与日志健壮的脚本应该包含完善的错误处理机制// 错误类型定义 const ErrorTypes { CONTENT_NOT_FOUND: 找不到文章内容区域, PRINT_FAILED: 打印触发失败, TIMEOUT: 操作超时 }; // 增强版执行函数 const executeWithRetry (maxRetries 2) { let attempts 0; const attempt () { try { // 执行核心逻辑... } catch (error) { if (attempts maxRetries) { console.warn(第${attempts}次重试...); setTimeout(attempt, 500 * attempts); } else { console.error(最终失败: ${error.message}); alert(导出失败请刷新页面后重试); } } }; attempt(); };4. 常见问题排查指南以下是开发者反馈的典型问题及解决方案4.1 内容显示不全现象PDF中缺少部分文章内容解决方案检查是否有未展开的按钮增加执行延迟确保DOM完全加载setTimeout(() { // 执行导出逻辑 }, 1000);4.2 样式异常现象代码高亮或排版错乱解决方案在打印设置中勾选背景图形选项添加CSS覆盖规则const style document.createElement(style); style.textContent pre { background-color: #f6f8fa !important; border-radius: 3px !important; } ; document.head.appendChild(style);4.3 性能优化对于超长文章可以添加分页优化// 每5000字符插入分页符 const content document.querySelector(.article_content); if (content.textContent.length 5000) { const paragraphs content.querySelectorAll(p); paragraphs.forEach((p, index) { if (index 0 index % 5 0) { p.style.pageBreakBefore always; } }); }5. 工程化扩展思路将脚本升级为浏览器插件或用户脚本实现更便捷的使用体验5.1 油猴脚本版本// UserScript // name CSDN纯净PDF导出 // namespace http://tampermonkey.net/ // version 1.2 // description 一键导出CSDN文章为纯净PDF // author YourName // match https://blog.csdn.net/*/article/details/* // icon https://csdnimg.cn/public/favicon.ico // grant none // /UserScript (function() { use strict; // 添加界面按钮 const btn document.createElement(button); btn.textContent 导出PDF; btn.style.position fixed; btn.style.right 20px; btn.style.bottom 20px; btn.style.zIndex 9999; btn.onclick exportCSDNToPDF; // 使用前面的导出函数 document.body.appendChild(btn); })();5.2 Chrome扩展方案创建manifest.json{ manifest_version: 3, name: CSDN PDF导出工具, version: 1.0, action: { default_popup: popup.html, default_icon: icon.png }, permissions: [activeTab, scripting], content_scripts: [{ matches: [https://blog.csdn.net/*/article/details/*], js: [content.js] }] }配套的content.jschrome.runtime.onMessage.addListener((request, sender, sendResponse) { if (request.action exportPDF) { // 执行导出逻辑... sendResponse({status: success}); } });