Make html2pdf fool proof

Change-Id: Idf92b21a25a219945a35deddc8844e6a99a2dff9
diff --git a/ci/html2pdf b/ci/html2pdf
index 5f9bce9..90a6610 100755
--- a/ci/html2pdf
+++ b/ci/html2pdf
@@ -1,4 +1,37 @@
 #!/bin/sh -eu
-in=$1 out=$2 page0=${3:-} page1=${4:-$page0}
-google-chrome --no-sandbox --headless=new --no-pdf-header-footer --disable-gpu --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-default-apps --disable-dev-shm-usage --disable-extensions --disable-features=TranslateUI,BlinkGenPropertyTrees,ImprovedCookieControls,SameSiteByDefaultCookies,LazyFrameLoading --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --disable-sync --force-color-profile=srgb --metrics-recording-only --no-first-run --enable-automation --password-store=basic --use-mock-keychain --headless=new --hide-scrollbars --mute-audio --no-pdf-header-footer  --virtual-time-budget=42000 --print-to-pdf="$out".tmp "$in"
-pdfseparate -f 1 -l 1 "$out".tmp $out
+in=$1
+
+# Get absolute path to preserve relative links
+abs_in=$(realpath "$in")
+work_dir=$(dirname "$abs_in")
+
+# Use Chrome with no shrinking, working from correct directory
+cd "$work_dir"
+R -e "pagedown::chrome_print('$(basename "$abs_in")',
+  options=list(
+    pageRanges='1',
+    paperWidth=33.11,
+    paperHeight=46.81,
+    marginTop=0,
+    marginBottom=0,
+    marginLeft=0,
+    marginRight=0,
+    printBackground=TRUE,
+    scale=0.98,  # Compensate for ~2% print scaling
+    displayHeaderFooter=FALSE,
+    preferCSSPageSize=TRUE
+  ),
+  extra_args = c(
+    '--disable-gpu',
+    '--no-sandbox',
+    '--disable-dev-shm-usage',
+    '--force-device-scale-factor=1',
+    '--disable-print-preview',
+    '--disable-background-timer-throttling',
+    '--allow-file-access-from-files',
+    '--force-color-profile=srgb',
+    '--disable-lcd-text',
+    '--disable-font-subpixel-positioning',
+    '--run-all-compositor-stages-before-draw'
+  )
+)"