HTMLファイル (index.html) 例
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>PDF Highlighter</title>
<style>
.highlight {
background-color: yellow; /* ハイライト用の背景色 */
}
#keyword-list {
margin-top: 20px;
font-size: 1.2em;
color: blue;
}
</style>
</head>
<body>
<h1>PDFドキュメントのハイライト表示</h1>
<canvas id="pdf-canvas"></canvas>
<div id="keyword-list">
<h2>ハイライトされたキーワード</h2>
<ul id="keywords"></ul>
</div>
<!-- PDF.js ライブラリの読み込み -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.min.js"></script>
<!-- jQueryの読み込み(任意) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
JavaScriptファイル (script.js) 例
// PDF.js 設定
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.worker.min.js';
// ハイライト対象のキーワード
const keywords = ["example", "sample", "highlight"];
// PDFのURL(業務で使うファイルのパスに変更してください)
const pdfUrl = 'your-pdf-url.pdf';
// PDFをHTML上に描画し、キーワードをハイライト
function renderAndHighlightPDF() {
const loadingTask = pdfjsLib.getDocument(pdfUrl);
loadingTask.promise.then(pdf => {
// 各ページを順に処理
for (let pageNumber = 1; pageNumber <= pdf.numPages; pageNumber++) {
pdf.getPage(pageNumber).then(page => {
const scale = 1.5;
const viewport = page.getViewport({ scale });
// canvasを用意してページをレンダリング
const canvas = document.getElementById('pdf-canvas');
const context = canvas.getContext('2d');
canvas.width = viewport.width;
canvas.height = viewport.height;
const renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext).promise.then(() => {
// ページのテキストを抽出
page.getTextContent().then(textContent => {
const textItems = textContent.items;
let highlightedText = "";
textItems.forEach(item => {
let text = item.str;
// キーワードが含まれているかチェック
keywords.forEach(keyword => {
if (text.includes(keyword)) {
// ハイライト用のHTMLに変換
text = text.replace(keyword, `<span class="highlight">${keyword}</span>`);
addKeywordToList(keyword); // キーワードをリストに追加
}
});
highlightedText += text + " ";
});
// 抽出したテキストをHTMLに挿入(ここでハイライト済み)
const div = document.createElement('div');
div.innerHTML = highlightedText;
document.body.appendChild(div);
});
});
});
}
});
}
// ハイライトされたキーワードをリストに表示
function addKeywordToList(keyword) {
const keywordList = document.getElementById("keywords");
if (!Array.from(keywordList.children).some(li => li.textContent === keyword)) {
const li = document.createElement("li");
li.textContent = keyword;
keywordList.appendChild(li);
}
}
// PDFのレンダリングとハイライトの実行
renderAndHighlightPDF();