19
20

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.

JavaScriptのスクレイピングを使用した印刷機能の実装メモ

Last updated at Posted at 2015-04-07

JavaScriptのスクレイピングを使用した印刷機能の実装メモ

メモ

JavaScriptを使用したスクレイピング、および任意箇所の印刷機能のメモ。HTMLにすでにある特定のタグ間のデータを抽出し、印刷対象に指定します。JavaScriptの実装となり、スクレイピングした範囲をwindowオブジェクトにコピーし、printメソッドを指定。最後に生データを戻すことにより、通常の印刷にも支障のないようにしています。

hoge.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML lang="ja">
<HEAD>
  <TITLE>ほげほげ</TITLE>
  <link href="css/hoge.css" rel="stylesheet" type="text/css">
  <script src="js/hoge.js"></script>
</HEAD>

<BODY>
<a onClick="PrintScript();"><image src="/img/printer.png" alt="印刷"/></a>

<!--PrintStart-->
  <div>
    ほげほげ
  </div>
<!--PrintEnd-->
</BODY>
</HTML>

hoge.js

function PrintScript() {
    //印刷範囲を設定
    htmlcode = window.document.body.innerHTML; 
    sprnstr  = "<!--PrintStart-->"; 
    eprnstr  = "<!--PrintEnd-->"; 
    var prnhtml = htmlcode.substr(htmlcode.indexOf(sprnstr)+sprnstr.length); 
    prnhtml = prnhtml.substring(0,prnhtml.indexOf(eprnstr)); 
    window.document.body.innerHTML = prnhtml; 
    window.print(); 
    window.document.body.innerHTML = htmlcode;
}


19
20
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
19
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?