mcc-html-to-pdf
v1.0.0
Published
Cordova plugin to convert HTML to PDF natively on Android (WebView → PdfDocument) with JS fallback for other platforms.
Maintainers
Readme
mcc-html-to-pdf
Cordova plugin that converts an HTML string to a PDF file on-device.
- Android: uses the native
WebView→PdfDocumentpipeline (no third-party libs required). - Other platforms: falls back to a pure-JS renderer (SVG
foreignObject→ JPEG → hand-built PDF).
Installation
cordova plugin add mcc-html-to-pdf
cordova plugin add cordova-plugin-fileTo open the generated PDF after saving:
cordova plugin add cordova-plugin-file-opener2Usage
document.addEventListener('deviceready', function () {
var htmlToPdf = cordova.plugins.mcc.htmlToPdf;
htmlToPdf.convert(
{
html: '<h1>Hello PDF</h1><p>This is a test.</p>',
fileName: 'output.pdf',
pdf: {
orientation: 'p', // 'p' (portrait) | 'l' (landscape)
format: 'a4'
}
},
function (result) {
// result.fullPath — absolute path on device
// result.name — file name
// result.type — 'application/pdf'
var path = result.fullPath;
if (path.indexOf('file://') !== 0) path = 'file://' + path;
cordova.plugins.fileOpener2.open(path, 'application/pdf', {
success: function () {},
error: function (e) { console.error('Open error', e); }
});
},
function (err) {
console.error('mcc-html-to-pdf error:', err);
}
);
});API
cordova.plugins.mcc.htmlToPdf.convert(
options: {
html: string; // HTML string to render (required)
fileName?: string; // Output file name. Default: mcc-html-<timestamp>.pdf
pdf?: {
orientation?: 'p' | 'l'; // Portrait or landscape. Default: 'p'
format?: 'a4' | number[]; // Page format or [widthMm, heightMm]. Default: 'a4'
};
// JS-fallback only options (non-Android):
selector?: string; // CSS selector of a DOM element to capture
element?: HTMLElement; // Direct DOM element reference
quality?: number; // JPEG quality 0–1. Default: 1.0
scale?: number; // Render scale factor. Default: 2
},
success: (result: { fullPath: string; name: string; type: string }) => void,
error: (err: string) => void
): void;How It Works
Android (native)
- An off-screen
WebViewloads the HTML string. - After render,
PdfDocumentdraws each page of the WebView onto aCanvas. - The PDF is written to
getExternalFilesDir()and the path is returned.
JS fallback (non-Android)
- The HTML string (or DOM element) is rendered to a
<canvas>via SVGforeignObject. - Each page is sliced from the canvas and encoded as JPEG.
- A valid PDF binary is assembled in memory and saved via
cordova-plugin-file.
Dependencies
| Plugin | Required |
|---|---|
| cordova-plugin-file | Yes (JS fallback file save) |
| cordova-plugin-file-opener2 | No (only to open the PDF) |
License
MIT © MCC
