1
1

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 3 years have passed since last update.

WEBページをサーバ側でPDF化して保存

Posted at

こんなことやりたいなって思ったら、だいたいすでに誰かやってるから助かるね。

やりたいこと

  • 外部のWEBからもページにアクセスして、そのHTML内容をPDFとして手元のサーバに保存したい。
  • Ubuntu18でやりたい
  • PHPでやりたい

すでにやってる人

これらの方とやってることはほぼ一緒です。ありがとうございます。

元はたぶんここ → ヘッドレス Chrome ことはじめ

やってることは同じなので、わざわざ記事にするほどでもなかったカナ・・。

環境


$ cat /etc/os-release
NAME="Ubuntu"
VERSION="18.04.5 LTS (Bionic Beaver)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 18.04.5 LTS"
VERSION_ID="18.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=bionic
UBUNTU_CODENAME=bionic

chromeのインストール

chromeのheadlessモードを使うので、Ubuntu18にchromeをインストールします。

こちらをそのまま実行しました。

curl https://dl.google.com/linux/linux_signing_key.pub | sudo apt-key add -
echo 'deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main' | sudo tee /etc/apt/sources.list.d/google-chrome.list
sudo apt update
sudo apt install google-chrome-stable

実行

$ google-chrome  --headless --no-sandbox --disable-gpu --print-to-pdf 'https://google.co.jp/'

カレントディレクトリに、output.pdf というPDFが出力されます。出力したてのファイルは、パーみたいが

-rw-------  1 XXXX XXXX 149734 Sep 18 16:49 output.pdf

だったので、そのままではブラウザからアクセスできないので、適当に変えてください。

結果

日本語が化ける。(キャプチャするの忘れた)

日本語フォントのインストール


apt-get install -y unzip
cd /usr/local/share/fonts/
sudo curl 'https://ipafont.ipa.go.jp/IPAfont/IPAfont00303.zip' -o IPAfont00303.zip
sudo unzip IPAfont00303.zip
sudo fc-cache -fv
fc-list

image.png
……できた。

できてないこと

  • ヘッダー・フッターを消せない
  • 拡大率(Zoom)を変更できない

--no-marginsや、--print-to-pdf-no-headerとか、効いてない気がする。ソース追う気力なし。
DevTools Protcolを使えば、もっと細かく制御できそうだけど・・また今度で。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?