Plan sharing: "Print / Save as PDF" on the mobile app

The printable one-page plan layout (lib/plan-share.js planPrintHTML) was
web-only: printPlan() renders it into a hidden iframe and calls
window.print(), which Android's WebView does not implement.

On mobile the same HTML is handed to the OS print flow via a small
first-party `Print` Capacitor plugin (one method, printHtml), which is
where the user picks "Save as PDF" / "Save to Files" or a real printer.
Web is unchanged.

- Android (PrintPlugin.java): load the HTML into an off-screen WebView and,
  once loaded, drive it through the system PrintManager. A strong ref keeps
  the WebView alive until the job spools. Registered in MainActivity next
  to InstallPlugin.
- iOS (PrintPlugin.swift + .m): UIPrintInteractionController with a
  UIMarkupTextPrintFormatter. Files added to App.xcodeproj.
- lib/mobile.js: printHtml() wrapper (registerPlugin('Print')).
- sheets.jsx: the MOBILE branch of "Print / Save as PDF" calls printHtml;
  the web branch still calls printPlan.

No new dependency — the OS renders the PDF. Native code is not exercised by
the pipeline; run the manual APK job and check on device.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DBkhHLqWtSYrPdsNE11PiP
This commit is contained in:
HenryandClaude Sonnet 5 committed 2026-09-08 11:19:25 +01:00
1 parent acff80348f
commit 8e18e77437
7 files changed
+155 -7

No files matched your search

@@ -7,6 +7,7 @@ public class MainActivity extends BridgeActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
registerPlugin(InstallPlugin.class);
registerPlugin(PrintPlugin.class);
super.onCreate(savedInstanceState);
}
}
@@ -0,0 +1,67 @@
package ch.duartesantos.opengym;
import android.content.Context;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
/**
* Minimal local Capacitor plugin that hands a self-contained HTML document to the Android
* system print flow (Save as PDF, Save to Drive, a real printer). Android WebView has no
* window.print(), so the printable plan page (lib/plan-share.js planPrintHTML) can only reach
* a PDF this way. No PDF library is bundled — the OS renders it.
*
* Usage from JS:
* import { registerPlugin } from '@capacitor/core';
* const Print = registerPlugin('Print');
* await Print.printHtml({ html: '<!doctype html>…', name: 'Weekly Training Plan' });
*/
@CapacitorPlugin(name = "Print")
public class PrintPlugin extends Plugin {
// The print framework drives an off-screen WebView asynchronously; without a strong
// reference it can be collected mid-spool and the job dies silently. Held until the next
// print replaces it — one at a time is all the UI can start.
private WebView printView;
@PluginMethod
public void printHtml(PluginCall call) {
String html = call.getString("html");
if (html == null || html.isEmpty()) {
call.reject("html is required");
return;
}
final String jobName = call.getString("name", "openGym");
getActivity().runOnUiThread(() -> {
WebView webView = new WebView(getContext());
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
PrintManager printManager =
(PrintManager) getContext().getSystemService(Context.PRINT_SERVICE);
if (printManager == null) {
printView = null;
call.reject("printing is not available on this device");
return;
}
PrintDocumentAdapter adapter = view.createPrintDocumentAdapter(jobName);
printManager.print(jobName, adapter,
new PrintAttributes.Builder()
.setMediaSize(PrintAttributes.MediaSize.ISO_A4)
.build());
call.resolve();
}
});
// baseURL null: the document is fully self-contained (inline <style>, no assets).
webView.loadDataWithBaseURL(null, html, "text/html", "UTF-8", null);
printView = webView;
});
}
}
@@ -15,6 +15,8 @@
504EC3121FED79650016851F /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 504EC3101FED79650016851F /* LaunchScreen.storyboard */; };
50B271D11FEDC1A000F3C39B /* public in Resources */ = {isa = PBXBuildFile; fileRef = 50B271D01FEDC1A000F3C39B /* public */; };
A084ECDBA7D38E1E42DFC39D /* Pods_App.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AF277DCFFFF123FFC6DF26C7 /* Pods_App.framework */; };
AA0100000000000000000002 /* PrintPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0100000000000000000001 /* PrintPlugin.swift */; };
AA0100000000000000000004 /* PrintPlugin.m in Sources */ = {isa = PBXBuildFile; fileRef = AA0100000000000000000003 /* PrintPlugin.m */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
@@ -22,6 +24,8 @@
50379B222058CBB4000EE86E /* capacitor.config.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = capacitor.config.json; sourceTree = "<group>"; };
504EC3041FED79650016851F /* App.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = App.app; sourceTree = BUILT_PRODUCTS_DIR; };
504EC3071FED79650016851F /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
AA0100000000000000000001 /* PrintPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrintPlugin.swift; sourceTree = "<group>"; };
AA0100000000000000000003 /* PrintPlugin.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = PrintPlugin.m; sourceTree = "<group>"; };
504EC30C1FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
504EC30E1FED79650016851F /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
504EC3111FED79650016851F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
@@ -75,6 +79,8 @@
children = (
50379B222058CBB4000EE86E /* capacitor.config.json */,
504EC3071FED79650016851F /* AppDelegate.swift */,
AA0100000000000000000001 /* PrintPlugin.swift */,
AA0100000000000000000003 /* PrintPlugin.m */,
504EC30B1FED79650016851F /* Main.storyboard */,
504EC30E1FED79650016851F /* Assets.xcassets */,
504EC3101FED79650016851F /* LaunchScreen.storyboard */,
@@ -210,6 +216,8 @@
buildActionMask = 2147483647;
files = (
504EC3081FED79650016851F /* AppDelegate.swift in Sources */,
AA0100000000000000000002 /* PrintPlugin.swift in Sources */,
AA0100000000000000000004 /* PrintPlugin.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
+7
View File
@@ -0,0 +1,7 @@
#import <Foundation/Foundation.h>
#import <Capacitor/Capacitor.h>
// Bridges the Swift PrintPlugin into Capacitor's Objective-C plugin registry.
CAP_PLUGIN(PrintPlugin, "Print",
CAP_PLUGIN_METHOD(printHtml, CAPPluginReturnPromise);
)
+49
View File
@@ -0,0 +1,49 @@
import Foundation
import Capacitor
import UIKit
/**
* Minimal local Capacitor plugin that hands a self-contained HTML document to the iOS system
* print sheet (Save to Files as PDF, share, a real printer). The printable plan page
* (lib/plan-share.js planPrintHTML) reaches a PDF this way without bundling a PDF library —
* UIKit renders it.
*
* Usage from JS:
* import { registerPlugin } from '@capacitor/core';
* const Print = registerPlugin('Print');
* await Print.printHtml({ html: '<!doctype html>…', name: 'Weekly Training Plan' });
*/
@objc(PrintPlugin)
public class PrintPlugin: CAPPlugin {
@objc func printHtml(_ call: CAPPluginCall) {
guard let html = call.getString("html"), !html.isEmpty else {
call.reject("html is required")
return
}
let jobName = call.getString("name") ?? "openGym"
DispatchQueue.main.async {
let controller = UIPrintInteractionController.shared
let info = UIPrintInfo(dictionary: nil)
info.outputType = .general
info.jobName = jobName
controller.printInfo = info
// The document carries its own @page margins; keep the formatter's own insets at 0
// so they don't stack on top.
let formatter = UIMarkupTextPrintFormatter(markupText: html)
formatter.perPageContentInsets = .zero
controller.printFormatter = formatter
controller.present(animated: true) { (_, completed, error) in
if let error = error {
call.reject(error.localizedDescription)
} else {
call.resolve(["completed": completed])
}
}
}
}
}
+12
View File
@@ -172,6 +172,18 @@ export async function shareExport(json, filename) {
await Share.share({ title: filename, url: w.uri })
}
// Hand a self-contained HTML document (lib/plan-share.js planPrintHTML) to the OS print flow.
// Android routes it through the system PrintManager — "Save as PDF", "Save to Drive", a real
// printer; iOS through the print sheet — "Save to Files" (as PDF), share, print. Either way the
// platform renders the PDF, so no PDF library rides in the bundle. The local `Print` plugin is
// registered natively (android MainActivity, ios PrintPlugin.m); on the web build this file's
// callers gate on MOBILE and never reach here.
export async function printHtml(html, name) {
const { registerPlugin } = await import('@capacitor/core')
const Print = registerPlugin('Print')
await Print.printHtml({ html, name })
}
// "Auto-backup on changes" (Settings): a dated snapshot dropped into the Documents folder —
// visible in Files (iOS) / a file manager (Android), unlike the private mirror nativeSave keeps
// — so whatever the user points at that folder (a sync app, a manual copy) always has something
+11 -7
View File
@@ -22,12 +22,12 @@ import MuscleExplorer from './components/MuscleExplorer.jsx'
import { exerciseMuscleSnapshot, loadOfWorkouts, MUSCLES, MUSCLE_NAME, normalizeMuscleGroups, hasExplicitMuscleMetadata } from './lib/muscles.js'
import { parseImport, mergeImport } from './lib/import-csv.js'
import { importHevyData, HevyApiError, HEVY_DEV_SETTINGS, mergeHevyRoutines } from './lib/import-hevy.js'
import { buildPlanBundle, parsePlan, mergePlan, printPlan } from './lib/plan-share.js'
import { buildPlanBundle, parsePlan, mergePlan, printPlan, planPrintHTML } from './lib/plan-share.js'
import { estimate1RM, best1RM, is1RMRecord, REP_CAP } from './lib/onerm.js'
import { exerciseHistory } from './lib/exercise-history.js'
import { nextPrescription, applyPrescription, policyFor, defaultIncrement, POLICIES_FOR, POLICY_NAME, POLICY_DESC, MAX_BW_SETS, weightIncrement } from './lib/progression.js'
import { normalizeRepRange } from './lib/rep-range.js'
import { MOBILE, shareExport } from './lib/mobile.js'
import { MOBILE, shareExport, printHtml } from './lib/mobile.js'
import { buildCompletedWorkout } from './lib/finish-workout.js'
import { isWarmupRow } from './lib/workout-model.js'
import { nextUnfinishedUnit } from './lib/supersetFlow.js'
@@ -1470,11 +1470,15 @@ function PlanTools({ close }) {
<div className="muted small" style={{ marginBottom: 16 }}>{t('Send your routines to a friend, or put your week on paper.')}</div>
<Button variant="primary" icon="upload" onClick={exportFile} disabled={!hasRoutines}>{t('Export plan file')}</Button>
<div className="dim small" style={{ margin: '7px 2px 0', lineHeight: 1.4 }}>{t('A small file a friend imports into their own openGym — routines only, none of your workouts or weigh-ins.')}</div>
{!MOBILE && <>
<div style={{ height: 12 }} />
<Button variant="tinted" icon="download" onClick={() => { close(); printPlan(st, user?.name || '') }} disabled={!hasRoutines}>{t('Print / Save as PDF')}</Button>
<div className="dim small" style={{ margin: '7px 2px 0', lineHeight: 1.4 }}>{t('A clean one-page-per-plan printout — no exercise ever splits across a page.')}</div>
</>}
<div style={{ height: 12 }} />
<Button variant="tinted" icon="download" onClick={() => {
close()
// Web: the browser's print dialog (→ Save as PDF). Mobile: the OS print flow via the
// native Print plugin — Android WebView has no window.print(). Same printable HTML both ways.
if (MOBILE) printHtml(planPrintHTML(st, user?.name || ''), t('Weekly Training Plan')).catch(() => { /* dismissed */ })
else printPlan(st, user?.name || '')
}} disabled={!hasRoutines}>{t('Print / Save as PDF')}</Button>
<div className="dim small" style={{ margin: '7px 2px 0', lineHeight: 1.4 }}>{t('A clean one-page-per-plan printout — no exercise ever splits across a page.')}</div>
{!hasRoutines && <div className="dim small" style={{ margin: '12px 2px 0' }}>{t('Add an exercise to a routine first — an empty plan has nothing to share.')}</div>}
<h4 className="sec">{t('Got a plan from a friend?')}</h4>
<Button variant="ghost" icon="folder" onClick={() => fileRef.current?.click()}>{t('Import a plan file')}</Button>