// ==UserScript==
// @name Luogu Problem2PDF
// @namespace http://tampermonkey.net/
// @version 1.0
// @description 将洛谷题目页面快速打印为 PDF,去除冗余元素,支持自定义字体、行号和标题。
// @author Murasame & Gemini
// @match *://www.luogu.com.cn/problem/*
// @match *://www.luogu.com/problem/*
// @require https://fastly.jsdelivr.net/npm/sweetalert2@11
// @license MIT
// ==/UserScript==
(function() {
'use strict';
if (typeof window.Swal === 'undefined') {
const swalScript = document.createElement('script');
swalScript.src = 'https://fastly.jsdelivr.net/npm/sweetalert2@11';
document.head.appendChild(swalScript);
}
const DEFAULT_CONFIG = {
mainFont: 'Lato, "Noto Sans CJK SC", "PingFang SC", "Microsoft YaHei", sans-serif',
codeFont: '"Fira Code", Consolas, Monaco, monospace',
showCodeBlockBorder: true,
showLineNumbers: true,
printTitle: true
};
function getConfig() {
try {
const saved = localStorage.getItem('gemini_pdf_config_problem');
return saved ? { ...DEFAULT_CONFIG, ...JSON.parse(saved) } : DEFAULT_CONFIG;
} catch (e) {
return DEFAULT_CONFIG;
}
}
function saveConfig(cfg) {
localStorage.setItem('gemini_pdf_config_problem', JSON.stringify(cfg));
}
function createSettingsModal() {
if (document.getElementById('gemini-pdf-modal')) return;
const overlay = document.createElement('div');
overlay.id = 'gemini-pdf-modal';
overlay.style.position = 'fixed';
overlay.style.top = '0';
overlay.style.left = '0';
overlay.style.width = '100vw';
overlay.style.height = '100vh';
overlay.style.backgroundColor = 'rgba(0,0,0,0.5)';
overlay.style.zIndex = '999999';
overlay.style.display = 'none';
overlay.style.justifyContent = 'center';
overlay.style.alignItems = 'center';
const modal = document.createElement('div');
modal.style.backgroundColor = '#fff';
modal.style.padding = '24px 32px';
modal.style.borderRadius = '8px';
modal.style.width = '400px';
modal.style.boxShadow = '0 10px 25px rgba(0,0,0,0.2)';
modal.style.fontFamily = 'sans-serif';
modal.innerHTML = `
<h3 style="margin-top:0; margin-bottom: 20px; font-size: 18px; color: #333; border-bottom: 1px solid #eee; padding-bottom: 10px;">PDF 打印高级设置</h3>
<div style="margin-bottom: 15px;">
<label style="display:block; font-size: 14px; margin-bottom: 5px; color: #555;">正文字体(留空使用默认):</label>
<input id="cfg-mainFont" type="text" style="width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box;" />
</div>
<div style="margin-bottom: 15px;">
<label style="display:block; font-size: 14px; margin-bottom: 5px; color: #555;">代码块字体:</label>
<input id="cfg-codeFont" type="text" style="width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box;" />
</div>
<div style="margin-bottom: 15px; display: flex; align-items: center;">
<input id="cfg-title" type="checkbox" style="margin-right: 8px; width: 16px; height: 16px;" />
<label for="cfg-title" style="font-size: 14px; color: #333; cursor: pointer;">打印时在顶部添加题目名称</label>
</div>
<div style="margin-bottom: 15px; display: flex; align-items: center;">
<input id="cfg-border" type="checkbox" style="margin-right: 8px; width: 16px; height: 16px;" />
<label for="cfg-border" style="font-size: 14px; color: #333; cursor: pointer;">为代码块添加边框</label>
</div>
<div style="margin-bottom: 25px; display: flex; align-items: center;">
<input id="cfg-linenum" type="checkbox" style="margin-right: 8px; width: 16px; height: 16px;" />
<label for="cfg-linenum" style="font-size: 14px; color: #333; cursor: pointer;">显示代码块行号</label>
</div>
<div style="display: flex; justify-content: flex-end; gap: 10px;">
<button id="cfg-cancel" style="padding: 8px 16px; border: none; background: #e0e0e0; color: #333; border-radius: 4px; cursor: pointer;">取消</button>
<button id="cfg-save" style="padding: 8px 16px; border: none; background: #3498db; color: #fff; border-radius: 4px; cursor: pointer;">保存</button>
</div>
`;
overlay.appendChild(modal);
document.body.appendChild(overlay);
document.getElementById('cfg-cancel').onclick = () => overlay.style.display = 'none';
document.getElementById('cfg-save').onclick = () => {
const newCfg = {
mainFont: document.getElementById('cfg-mainFont').value,
codeFont: document.getElementById('cfg-codeFont').value,
printTitle: document.getElementById('cfg-title').checked,
showCodeBlockBorder: document.getElementById('cfg-border').checked,
showLineNumbers: document.getElementById('cfg-linenum').checked
};
saveConfig(newCfg);
overlay.style.display = 'none';
if (window.Swal) {
Swal.fire({
icon: 'success',
title: '保存成功',
text: '设置已保存!下次点击“打印为 PDF”时生效。',
confirmButtonColor: '#3498db',
timer: 2000
});
}
};
}
function openSettingsModal() {
createSettingsModal();
const cfg = getConfig();
document.getElementById('cfg-mainFont').value = cfg.mainFont;
document.getElementById('cfg-codeFont').value = cfg.codeFont;
document.getElementById('cfg-title').checked = cfg.printTitle;
document.getElementById('cfg-border').checked = cfg.showCodeBlockBorder;
document.getElementById('cfg-linenum').checked = cfg.showLineNumbers;
document.getElementById('gemini-pdf-modal').style.display = 'flex';
}
function handlePrint() {
const actionsRow = document.querySelector('.problem-block-actions');
let content = null;
if (actionsRow && actionsRow.parentElement) {
content = actionsRow.parentElement;
} else {
const markedElems = document.querySelectorAll('.lfe-marked');
if (markedElems.length > 0) {
content = markedElems[0].parentElement;
}
}
if (!content) {
if (window.Swal) {
Swal.fire({
icon: 'error',
title: '未检测到内容',
text: '未能定位到题目内容块,请确保页面已完全加载!',
confirmButtonColor: '#3498db'
});
}
return;
}
const CONFIG = getConfig();
const hiddenElements = [];
const detailsStates = [];
const preStates = [];
let injectedTitle = null;
if (CONFIG.printTitle) {
injectedTitle = document.createElement('h1');
let pureTitle = document.title.replace(/ - 洛谷.*$/, '').trim();
if (!pureTitle) {
const titleEl = document.querySelector('h1.lfe-h1');
pureTitle = titleEl ? titleEl.innerText : '未知题目';
}
injectedTitle.innerText = pureTitle;
injectedTitle.style.textAlign = 'center';
injectedTitle.style.color = '#000';
injectedTitle.style.fontSize = '2em';
injectedTitle.style.fontWeight = 'bold';
injectedTitle.style.marginTop = '0';
injectedTitle.style.marginBottom = '24px';
injectedTitle.style.borderBottom = '2px solid #eaecef';
injectedTitle.style.paddingBottom = '10px';
injectedTitle.className = 'gemini-injected-title';
content.insertBefore(injectedTitle, content.firstChild);
}
content.querySelectorAll('details').forEach(details => {
detailsStates.push({ el: details, isOpen: details.hasAttribute('open') });
details.setAttribute('open', '');
});
content.querySelectorAll('pre').forEach(pre => {
const code = pre.querySelector('code');
if (!code) return;
preStates.push({
el: pre,
cssText: pre.style.cssText,
originalHTML: code.innerHTML,
classList: Array.from(pre.classList)
});
if (CONFIG.showCodeBlockBorder) {
pre.classList.add('gemini-print-pre-border');
}
if (CONFIG.showLineNumbers) {
const codeStyle = window.getComputedStyle(code);
const fontFamily = CONFIG.codeFont || codeStyle.fontFamily;
let htmlContent = code.innerHTML.replace(/\n$/, '');
let lines = htmlContent.split('\n');
while (lines.length > 0) {
let lastLineText = lines[lines.length - 1].replace(/<[^>]*>/g, '').trim();
if (lastLineText === '') {
lines.pop();
} else {
break;
}
}
let newHTML = lines.map((line, index) => {
let num = index + 1;
let fontSizeStyle = codeStyle.fontSize;
return `<div class="gemini-code-line"><span class="gemini-line-num" style="font-size: ${fontSizeStyle}; font-family: ${fontFamily};">${num}</span><span class="gemini-line-content">${line}</span></div>`;
}).join('');
code.innerHTML = newHTML;
}
});
let curr = content;
while (curr && curr !== document.body) {
const siblings = curr.parentNode ? curr.parentNode.children : [];
for (let i = 0; i < siblings.length; i++) {
const sibling = siblings[i];
if (sibling !== curr && sibling.tagName !== 'SCRIPT' && sibling.tagName !== 'STYLE' && sibling.id !== 'gemini-pdf-modal') {
hiddenElements.push({ el: sibling, display: sibling.style.display });
sibling.style.display = 'none';
}
}
hiddenElements.push({
el: curr, margin: curr.style.margin, padding: curr.style.padding,
width: curr.style.width, maxWidth: curr.style.maxWidth, isAncestor: true
});
curr.style.margin = '0';
curr.style.padding = '0';
curr.style.width = '100%';
curr.style.maxWidth = '100%';
curr = curr.parentNode;
}
const printStyle = document.createElement('style');
printStyle.innerHTML = `
@media print {
*, *::before, *::after {
-webkit-print-color-adjust: exact !important;
print-color-adjust: exact !important;
box-shadow: none !important;
text-shadow: none !important;
}
@page { margin: 1.5cm; }
body, html, #app, .columba-layout, .lfe-body {
background: white !important;
border: none !important;
}
footer, [class*="footer"], .footer, hr.lfe-hr {
display: none !important;
}
pre, blockquote, tr, img { page-break-inside: avoid; }
.lfe-marked { width: 100% !important; max-width: none !important; }
details[open] { display: block !important; }
button,
.lform-size-small,
.lform-size-middle,
.problem-block-actions,
.columba-content-wrap.header-layout button,
#pa-problem-panel,
.stat.stacked {
display: none !important;
}
${CONFIG.mainFont ? `.lfe-marked, .gemini-injected-title { font-family: ${CONFIG.mainFont} !important; }` : ''}
${CONFIG.codeFont ? `.lfe-marked pre, .lfe-marked code { font-family: ${CONFIG.codeFont} !important; }` : ''}
.gemini-print-pre-border {
border: 1px solid #d1d5db !important;
border-radius: 6px !important;
}
.lfe-marked pre {
padding: 0 !important;
background: #ffffff !important;
}
.gemini-line-num {
flex-shrink: 0 !important;
width: 3.5em !important;
text-align: right !important;
padding-right: 0.8em !important;
box-sizing: border-box !important;
color: #9ca3af !important;
user-select: none !important;
background-color: #f8f9fa !important;
border-right: 1px solid #d1d5db !important;
}
.gemini-code-line:first-child .gemini-line-num,
.gemini-code-line:first-child .gemini-line-content {
padding-top: 1em !important;
}
.gemini-code-line:last-child .gemini-line-num,
.gemini-code-line:last-child .gemini-line-content {
padding-bottom: 1em !important;
}
.gemini-code-line {
display: flex !important;
align-items: stretch !important;
width: 100% !important;
page-break-inside: avoid !important;
}
.gemini-line-content {
flex-grow: 1 !important;
padding-left: 0.8em !important;
white-space: pre-wrap !important;
word-wrap: break-word !important;
overflow-wrap: anywhere !important;
min-height: 1.5em;
}
}
`;
document.head.appendChild(printStyle);
setTimeout(() => {
window.print();
hiddenElements.forEach(item => {
if (item.isAncestor) {
item.el.style.margin = item.margin; item.el.style.padding = item.padding;
item.el.style.width = item.width; item.el.style.maxWidth = item.maxWidth;
} else {
item.el.style.display = item.display;
}
});
detailsStates.forEach(item => {
if (item.isOpen) item.el.setAttribute('open', '');
else item.el.removeAttribute('open');
});
preStates.forEach(item => {
item.el.style.cssText = item.cssText;
item.el.className = item.classList.join(' ');
if (item.originalHTML !== undefined) {
const code = item.el.querySelector('code');
if (code) code.innerHTML = item.originalHTML;
}
});
if (injectedTitle && injectedTitle.parentNode) {
injectedTitle.parentNode.removeChild(injectedTitle);
}
document.head.removeChild(printStyle);
}, 500);
}
function injectPrintButton() {
if (document.getElementById('gemini-pdf-btn-group')) return;
const actionsRow = document.querySelector('.problem-block-actions');
if (actionsRow) {
const btnGroup = document.createElement('span');
btnGroup.id = 'gemini-pdf-btn-group';
btnGroup.style.display = 'inline-block';
btnGroup.style.marginLeft = '15px';
const printBtn = document.createElement('a');
printBtn.href = 'javascript:void(0)';
printBtn.style.color = '#3498db';
printBtn.style.marginRight = '10px';
printBtn.innerText = '打印为 PDF';
const settingsBtn = document.createElement('a');
settingsBtn.href = 'javascript:void(0)';
settingsBtn.style.color = '#7f8c8d';
settingsBtn.innerText = '打印设置';
btnGroup.appendChild(printBtn);
btnGroup.appendChild(settingsBtn);
actionsRow.appendChild(btnGroup);
printBtn.addEventListener('click', handlePrint);
settingsBtn.addEventListener('click', openSettingsModal);
}
}
const observer = new MutationObserver(() => injectPrintButton());
observer.observe(document.body, { childList: true, subtree: true });
setTimeout(injectPrintButton, 1000);
})();剪贴板
剪贴板 v3qi67ku
剪贴板信息
剪贴板信息
- 收录
- 更新