0
0

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 1 year has passed since last update.

Google Chromeを使って自炊

Last updated at Posted at 2022-05-29

Chromeで自炊

Google Chromeを使ってwebページのPDF化を行います。

自炊とは

一般的に自炊とは、物理的な書籍を電子書籍化する際ことを指します。
この場では、WebページをPDF化することを自炊と呼んでいます。

Chromeの起動オプション

Google Chromeはコマンドラインから起動することができます。
こちらの記事で以前紹介しました。

macOS

$ /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome

linux

$ google-chrome

--print-to-pdfオプション

--print-to-pdfオプションと対象のURLを先程のChrome起動コマンドの引数に指定することで、URLのWebページがPDFとして保存されます。
以下実行例。出力PDF名をsample.pdfとしています。URLは機能私が投稿した記事にしました。

$ /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \
  --headless --disable-gpu --print-to-pdf=sample.pdf 'https://qiita.com/shuyaeer/items/ae0fbb75a77b46a6c071'

出力されたPDFを確認してみます。

出力PDF.png

いい感じです。

スクリプト化

シェルスクリプトと同じ改装にurls.txtを作成し、PDF化したいURLの一覧を作成しておけば、下記のスクリプトで一括でPDF化ができます。

#!/bin/bash
set -eu
i=1
while read line
do
    /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \
        --headless --disable-gpu --print-to-pdf="sample_${i}.pdf" $line
    let ++i
done < urls.txt

余談

余談1

普段私はMacをしており

$ alias google-chrome="/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome"

このようなエイリアスを貼ることで、linuxと同じ用にgoogle-chromeコマンドを使用していますが
シェルスクリプト内でエイリアスを参照することはできないので、注意が必要です。

余談2

google-chromeをターミナルから実行する場合、既存のchromeのプロセスは停止している必要があります。
毎度Chromeを終了するのは面倒なので、代わりにchromiumを使用することを勧めます。

$ chromium --headless --disable-gpu \
   --print-to-pdf=sample.pdf 'https://qiita.com/shuyaeer/items/ae0fbb75a77b46a6c071'

chromeと同じように使うことができます。

応用

Qiitaのストックした記事一覧をPDF化しようと思います。
今すぐ別タブでhttps://qiita.com/stockにアクセスし、デベロッパーツールを開きます。
そして、consoleに下記javascriptをコピペ->実行。

let articles = document.querySelectorAll("article > a");
for (let i=0;i<articles.length;i=i+1){
    var ele = articles[i].href
    console.log(ele)
}

出力を先程のurls.txtにペースト後、スクリプトを実行します。
ストックした記事PDFがそれぞれ生成されたでしょうか?
タブレットとかで閲覧したら素敵なドキュメントになる気がします。

今回は簡易的な実装のため、ページの遷移は行っていません。
ページをまたいでURLを収集した場合は以前紹介したpychromeを使うのが良いでしょう。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?