Export Google Analytics Data to PDF Reports via API
Google Analytics 4 dashboards are great for real-time monitoring, but stakeholders often need a formatted PDF they can read offline, store in a shared drive, or attach to a weekly email digest. GA4 standard reports can be downloaded as PDF from Share this report > Download File, and administrators can schedule PDF or CSV reports by email. Those exports cover one GA4 report screen at a time, though. If you want several metrics in one document with your own layout and logo, or a separate report for each client, building it through the API gives you more control.
This guide shows you how to automate the full pipeline: fetch metrics from the GA4 Data API, render them with Chart.js, and generate a branded PDF using the FUNBREW PDF API — in Node.js and Python.
Architecture Overview
GA4 Data API → Node.js/Python → HTML template → FUNBREW PDF API → Email / S3
- Fetch GA4 metrics via the
@google-analytics/data(Node.js) orgoogle-analytics-data(Python) client - Render metrics and charts into an HTML template
- Convert HTML to PDF using the FUNBREW PDF REST API, then download the PDF from the returned
download_url - Deliver by email or upload to cloud storage
This pattern is covered in more detail in the PDF report generation guide and in the automation use cases.
Step 1 — Set Up GA4 Data API Access
Enable the Google Analytics Data API in Google Cloud Console, create a service account, and download its JSON credentials file. Add the service account's email address as a user in GA4 Property access management with a role that can read reports (for example, Viewer). The client libraries use the JSON file pointed to by the GOOGLE_APPLICATION_CREDENTIALS environment variable.
npm install @google-analytics/data nodemailer
export GOOGLE_APPLICATION_CREDENTIALS="$PWD/ga4-credentials.json"
Step 2 — Fetch GA4 Metrics (Node.js)
const { BetaAnalyticsDataClient } = require('@google-analytics/data');
// Credentials are read from GOOGLE_APPLICATION_CREDENTIALS
const analyticsClient = new BetaAnalyticsDataClient();
const GA4_PROPERTY_ID = 'properties/XXXXXXXX'; // replace with your property ID
async function fetchMonthlyMetrics(startDate, endDate) {
const [response] = await analyticsClient.runReport({
property: GA4_PROPERTY_ID,
dateRanges: [{ startDate, endDate }],
dimensions: [{ name: 'date' }],
metrics: [
{ name: 'sessions' },
{ name: 'activeUsers' },
{ name: 'screenPageViews' },
{ name: 'bounceRate' },
],
orderBys: [{ dimension: { dimensionName: 'date' } }],
});
return (response.rows || []).map((row) => ({
date: row.dimensionValues[0].value, // YYYYMMDD
sessions: parseInt(row.metricValues[0].value, 10),
users: parseInt(row.metricValues[1].value, 10),
pageviews: parseInt(row.metricValues[2].value, 10),
bounceRate: parseFloat(row.metricValues[3].value), // fraction from 0 to 1
}));
}
The date dimension is returned as YYYYMMDD, and bounceRate is a fraction such as 0.2761 (27.61%).
Step 3 — Build the HTML Report Template
The template combines a KPI summary with a Chart.js line chart. Because the chart is drawn by JavaScript, convert it with the quality engine, which renders with Chromium via Gotenberg (Step 4).
function buildReportHTML(metrics, reportPeriod) {
const labels = metrics.map((m) => m.date);
const sessionData = metrics.map((m) => m.sessions);
const userDataArr = metrics.map((m) => m.users);
const totals = metrics.reduce(
(acc, m) => {
acc.sessions += m.sessions;
acc.users += m.users;
acc.pageviews += m.pageviews;
acc.bouncedSessions += m.bounceRate * m.sessions;
return acc;
},
{ sessions: 0, users: 0, pageviews: 0, bouncedSessions: 0 }
);
// Session-weighted average of the daily bounce rate, as a percentage
const avgBounce = totals.sessions
? ((totals.bouncedSessions / totals.sessions) * 100).toFixed(1)
: '0.0';
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://cdn.jsdelivr.net/npm/chart.js@4/dist/chart.umd.min.js"></script>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: -apple-system, 'Segoe UI', sans-serif; font-size: 13px;
color: #1e293b; background: #fff; }
h1 { font-size: 22px; font-weight: 700; color: #0f172a; margin-bottom: 4px; }
.period { font-size: 13px; color: #64748b; margin-bottom: 24px; }
.kpi-grid { display: flex; gap: 16px; margin-bottom: 28px; }
.kpi { flex: 1; background: #f8fafc; border: 1px solid #e2e8f0;
border-radius: 8px; padding: 16px; }
.kpi-label { font-size: 11px; color: #64748b; text-transform: uppercase;
letter-spacing: .5px; margin-bottom: 6px; }
.kpi-value { font-size: 26px; font-weight: 700; color: #0f172a; }
.chart-wrap { margin-bottom: 24px; }
h2 { font-size: 15px; font-weight: 600; margin-bottom: 12px; }
canvas { max-height: 220px; }
</style>
</head>
<body>
<h1>Monthly Analytics Report</h1>
<div class="period">${reportPeriod}</div>
<div class="kpi-grid">
<div class="kpi"><div class="kpi-label">Sessions</div>
<div class="kpi-value">${totals.sessions.toLocaleString()}</div></div>
<div class="kpi"><div class="kpi-label">Users (sum of daily)</div>
<div class="kpi-value">${totals.users.toLocaleString()}</div></div>
<div class="kpi"><div class="kpi-label">Pageviews</div>
<div class="kpi-value">${totals.pageviews.toLocaleString()}</div></div>
<div class="kpi"><div class="kpi-label">Avg Bounce Rate</div>
<div class="kpi-value">${avgBounce}%</div></div>
</div>
<div class="chart-wrap">
<h2>Sessions & Users — Daily Trend</h2>
<canvas id="trendChart"></canvas>
</div>
<script>
new Chart(document.getElementById('trendChart'), {
type: 'line',
data: {
labels: ${JSON.stringify(labels)},
datasets: [
{ label: 'Sessions', data: ${JSON.stringify(sessionData)},
borderColor: '#6366f1', backgroundColor: 'rgba(99,102,241,.1)',
tension: 0.3, fill: true },
{ label: 'Users', data: ${JSON.stringify(userDataArr)},
borderColor: '#10b981', backgroundColor: 'rgba(16,185,129,.1)',
tension: 0.3, fill: true },
],
},
options: {
animation: false,
plugins: { legend: { position: 'bottom' } },
scales: { y: { beginAtZero: true } },
},
});
</script>
</body>
</html>`;
}
Summing daily activeUsers counts a user once for every day they visited. If you need unique users for the whole month, run a separate runReport over the full range without the date dimension.
Step 4 — Convert HTML to PDF with FUNBREW PDF
POST /api/pdf/generate-from-html returns JSON containing data.download_url, not the PDF itself. Fetch that URL with the same API key (this uses fetch, available in Node.js 18 and later).
const API_KEY = process.env.FUNBREW_PDF_API_KEY;
async function htmlToPdf(html, filename) {
const res = await fetch('https://pdf.funbrew.cloud/api/pdf/generate-from-html', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Bearer ${API_KEY}`,
},
body: JSON.stringify({
html,
filename,
options: {
'page-size': 'A4',
engine: 'quality', // Chromium runs the JavaScript (Chart.js)
'margin-top': 15,
'margin-right': 15,
'margin-bottom': 20,
'margin-left': 15,
},
expiration_hours: 1,
}),
});
const json = await res.json();
if (!res.ok || !json.success) {
throw new Error(`PDF API error ${res.status} ${json.message || ''}`);
}
const pdfRes = await fetch(json.data.download_url, {
headers: { Authorization: `Bearer ${API_KEY}` },
});
if (!pdfRes.ok) throw new Error(`Download error ${pdfRes.status}`);
return Buffer.from(await pdfRes.arrayBuffer());
}
Margins are set with the margin-* options (millimetres, 0 to 50). The quality engine is available on paid plans and falls back to fast (wkhtmltopdf) where Gotenberg is not configured. Chart.js 4 may not run on fast, so always check that the chart appears in the output. To add page numbers, call the /api/pdf/page-numbers endpoint on the generated PDF (available on every plan). See the FUNBREW PDF documentation for the other options, including watermarks, expiration, download limits, and email delivery.
Step 5 — Wire It Together and Email the PDF
const nodemailer = require('nodemailer');
const fs = require('fs');
// toISOString() converts to UTC, so format the local date as YYYY-MM-DD
function toYmd(d) {
const mm = String(d.getMonth() + 1).padStart(2, '0');
const dd = String(d.getDate()).padStart(2, '0');
return `${d.getFullYear()}-${mm}-${dd}`;
}
async function generateAndSendReport() {
// Last calendar month
const now = new Date();
const firstOfLastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
const lastOfLastMonth = new Date(now.getFullYear(), now.getMonth(), 0);
const startDate = toYmd(firstOfLastMonth);
const endDate = toYmd(lastOfLastMonth);
const period = `${startDate} – ${endDate}`;
console.log(`Fetching GA4 data: ${period}`);
const metrics = await fetchMonthlyMetrics(startDate, endDate);
console.log('Rendering HTML template…');
const html = buildReportHTML(metrics, period);
console.log('Generating PDF…');
const filename = `analytics-report-${startDate.slice(0, 7)}.pdf`;
const pdfBuffer = await htmlToPdf(html, filename);
fs.writeFileSync(filename, pdfBuffer);
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: 587,
auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS },
});
await transporter.sendMail({
from: process.env.SMTP_USER,
to: process.env.REPORT_RECIPIENTS, // comma-separated
subject: `Analytics Report — ${period}`,
text: 'Please find the monthly analytics report attached.',
attachments: [{ filename, content: pdfBuffer }],
});
console.log(`Report sent: ${filename}`);
}
generateAndSendReport().catch(console.error);
For a single recipient, you can instead add email: { to, subject, body } to the generation request and let FUNBREW PDF send the email (email.to takes one address).
Python Version
import os
import requests
from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
DateRange, Dimension, Metric, RunReportRequest, OrderBy
)
GA4_PROPERTY_ID = "properties/XXXXXXXX"
API_KEY = os.environ["FUNBREW_PDF_API_KEY"]
def fetch_monthly_metrics(start_date: str, end_date: str):
# Credentials are read from GOOGLE_APPLICATION_CREDENTIALS
client = BetaAnalyticsDataClient()
request = RunReportRequest(
property=GA4_PROPERTY_ID,
date_ranges=[DateRange(start_date=start_date, end_date=end_date)],
dimensions=[Dimension(name="date")],
metrics=[
Metric(name="sessions"),
Metric(name="activeUsers"),
Metric(name="screenPageViews"),
Metric(name="bounceRate"),
],
order_bys=[OrderBy(dimension=OrderBy.DimensionOrderBy(dimension_name="date"))],
)
response = client.run_report(request)
return [
{
"date": row.dimension_values[0].value,
"sessions": int(row.metric_values[0].value),
"users": int(row.metric_values[1].value),
"pageviews": int(row.metric_values[2].value),
"bounce_rate": float(row.metric_values[3].value), # fraction from 0 to 1
}
for row in response.rows
]
def html_to_pdf(html: str, filename: str) -> bytes:
headers = {"Authorization": f"Bearer {API_KEY}", "Accept": "application/json"}
resp = requests.post(
"https://pdf.funbrew.cloud/api/pdf/generate-from-html",
headers=headers,
json={
"html": html,
"filename": filename,
"options": {
"page-size": "A4",
"engine": "quality",
"margin-top": 15,
"margin-right": 15,
"margin-bottom": 20,
"margin-left": 15,
},
"expiration_hours": 1,
},
timeout=60,
)
resp.raise_for_status()
download_url = resp.json()["data"]["download_url"]
pdf = requests.get(download_url, headers=headers, timeout=60)
pdf.raise_for_status()
return pdf.content
Build the HTML with the same template as buildReportHTML in the Node.js version, for example with Jinja2.
Schedule the Report (Cron)
Add this to your server's crontab (crontab -e) to run on the 1st of every month at 8 AM:
0 8 1 * * /usr/bin/node /app/generate-ga4-report.js >> /var/log/reports.log 2>&1
Cron usually reads the schedule in the server's time zone. With cronie, adding CRON_TZ=UTC (or another zone) to the crontab makes the table's times use that zone; support differs between cron implementations, so check your cron's manual.
For cloud environments, run the same logic as a Lambda function invoked by AWS EventBridge Scheduler, or behind an HTTP endpoint called by Google Cloud Scheduler. For multi-client agencies generating one report per client, see the bulk PDF generation guide.
Common Issues
| Problem | Cause | Fix |
|---|---|---|
| Chart missing in PDF | Converted mid-animation / script not run by the fast engine / Chart.js could not be loaded from the CDN |
Set animation: false and use engine: 'quality'. If it is still missing, embed the chart as an image or SVG |
403 / PERMISSION_DENIED from GA4 API |
Service account has no access to the property, or the API is not enabled | Add the service account email in GA4 Property access management and enable the Google Analytics Data API in Cloud Console |
| Bounce rate shows as 0.3% | bounceRate is a fraction from 0 to 1 |
Multiply by 100 before showing a percentage |
| PDF is blank or broken | HTML rendering error (JS exception) | Open the HTML in local Chrome and check the DevTools console, then check the conversion in the playground |
| Cron fires at the wrong time | Server time zone differs from what you expect | Check the server time zone; with cronie, set CRON_TZ |
For more rendering issues, see the HTML to PDF troubleshooting guide.
Next Steps
- Try the template in the FUNBREW PDF playground
- Add per-client branding (logo, colors) by parameterizing the HTML template
- Extend with top-page or channel breakdowns using additional GA4
dimensions - Explore batch PDF generation to generate one report per client in bulk (every plan, up to 100 items per request)