5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pdf.jsでリンクを押せるようにする

Last updated at Posted at 2017-11-28

はじめに

pdf.jsで、PDF上のリンクを押せるようにするためのメモ
*)pdf.jsはv1.9.426を利用

方法

ざっくりと言うと、

  1. PDFを描画しているcanvas要素上に、透明なdiv要素を配置
  2. リンクにしたい場所に、透明なaタグ要素をdiv要素上から重ねて配置

ソース(ポイント箇所のみ抜粋)

HTML

<div id="pdfContainer" class="pdf-content">
    <canvas id="pdfCanvas"></canvas>
    <div class="annotationLayer"></div>
</div>

CSS

.linkAnnotation {
    position: absolute;
}
.annotationLayer .linkAnnotation > a {
    position: absolute;
    font-size: 1em;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

js

PDFJS.workerSrc = 'pdf.worker.js';

$(function () {
    var pdfData = "sample.pdf";
    PDFJS.getDocument(pdfData).then(function (pdf) {
        return pdf.getPage(1);
    }).then(function (page) {
        var scale = 1;
        var viewport = page.getViewport(scale);
        var $canvas = $('#pdfCanvas');
        var canvas = $canvas.get(0);
        var context = canvas.getContext("2d");
        canvas.height = viewport.height;
        canvas.width = viewport.width;
        var renderContext = {
                canvasContext: context,
                viewport: viewport
        };
        page.render(renderContext);
        setupAnnotations(page, viewport, canvas, $('.annotationLayer'));
    });

  function setupAnnotations(page, viewport, canvas, $annotationLayerDiv) {
    var promise = page.getAnnotations().then(function (annotationsData) {
    viewport = viewport.clone({
        dontFlip: true
    });
    // 全てのリンクは新規ウィンドウで開く
    for(var i = 0; i < annotationsData.length; i++) {
        annotationsData[i].newWindow = true;
    }
    var param = {
        div: $annotationLayerDiv.get(0),
        page: page,
        viewport: viewport,
        annotations: annotationsData,
      };
      PDFJS.AnnotationLayer.render(param);
    });
    return promise;
  }
});
5
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?