javascript PDFファイルを開く

javascript PDFファイルを開く

javascriptで、PDFファイルを開くサンプルコードを記述してます。「document.location.href」に「PDF」があるパスを指定すれば開くことが可能です。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 107.0.5304.88

PDFファイルを開く

PDFファイルを開くには、リンク先にPDFファイルのパスを指定します。

document.location.href = "PDFファイル"

「js」ファイルと同じ階層に「sample.pdf」を用意して、実行してみます。

<script>

document.location.href = 'sample.pdf'

</script>

実行すると指定したPDFファイルが開いていることが確認できます。

サンプルコード

以下は、
「実行」ボタンをクリックした際に、PDFファイルを別タブで開くだけのサンプルコードとなります。ここでは「window.open」で「PDF」ファイルを開いてます。

※cssには「tailwind」を使用して、アロー関数で関数は定義してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
</head>

<script>

  window.onload = () => {

    btn.onclick = () => {

      window.open('sample.pdf', '_blank')

    }

  }

</script>

<body>
  <div class="container mx-auto my-56 w-64 px-4">

    <div id="sample" class="flex flex-col justify-center">

      <button id="btn"
        class="mb-2 md:mb-0 bg-transparent hover:bg-pink-500 text-pink-700 font-semibold hover:text-white py-2 px-4 border border-pink-500 hover:border-transparent rounded">
        実行
      </button>

    </div>

  </div>
</body>

</html>

実行結果を確認すると、PDFが表示されていることが確認できます。

また、javascript部はwindowオブジェクトを省略して記述することも可能です。

onload = () => {

  btn.onclick = () => {

    open('sample.pdf', '_blank')
  }

}