使用方法:

  1. 打开要保存的技术文章页面

  2. 在浏览器控制台(F12)中粘贴此代码执行

  3. 浏览器打印对话框会自动弹出

  4. 页面会在打印后自动恢复

(function() {
    'use strict';
    const originalHTML = document.body.innerHTML;
    const originalStyle = document.body.style.cssText;

    try {
        // 1. 先展开所有折叠的代码块
        document.querySelectorAll('.expand-btn, .fold-btn, .code-expand, .toggle-btn').forEach(btn => {
            btn.click();
        });
        // 兼容CSDN的代码块展开
        document.querySelectorAll('.hljs-button').forEach(btn => {
            if (btn.textContent.includes('展开')) btn.click();
        });

        // 2. 去水印(修复版)
        let removedCount = 0;
        document.querySelectorAll('*').forEach(el => {
            const className = el.className || '';
            const id = el.id || '';
            if (
                (typeof className === 'string' && className.includes('watermark')) ||
                (typeof id === 'string' && id.includes('watermark')) ||
                el.style.pointerEvents === 'none' ||
                (el.style.position === 'fixed' && parseInt(el.style.zIndex || 0) > 999)
            ) {
                el.remove();
                removedCount++;
            }
            const computedStyle = getComputedStyle(el);
            if (computedStyle && typeof computedStyle.backgroundImage === 'string' && computedStyle.backgroundImage.includes('watermark')) {
                el.style.backgroundImage = 'none';
                removedCount++;
            }
        });

        // 3. 优化打印样式,让代码块完整显示
        const printStyle = document.createElement('style');
        printStyle.textContent = `
            @media print {
                body { zoom: 0.8; }
                pre, code { white-space: pre-wrap !important; word-wrap: break-word !important; }
                .article_content { width: 100% !important; }
                header, footer, .sidebar, .comment, .advertisement { display: none !important; }
            }
        `;
        document.head.appendChild(printStyle);

        // 4. 弹出打印窗口
        window.print();

        // 5. 清理临时样式
        document.head.removeChild(printStyle);
    } finally {
        // 恢复页面
        document.body.innerHTML = originalHTML;
        document.body.style.cssText = originalStyle;
    }
})();

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐