-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpagify.js
More file actions
812 lines (717 loc) · 33.3 KB
/
pagify.js
File metadata and controls
812 lines (717 loc) · 33.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
/**
* Pagify SDK - Modular Version
* Provides a simple API for rendering HTML content as paginated PDFs using Paged.js
*
* Usage:
* - Render paginated content: pagify.render(options)
*
* @author Pagify SDK
* @version 1.2.0
* @license MIT
*/
import { Previewer } from 'pagedjs';
import html2pdf from 'html2pdf.js';
/**
* Pagify SDK Class
* Handles PDF rendering with pagination using Paged.js and html2pdf.js
*/
const pagifyIframeIdentifier = 'iframe[data-pagify-iframe="true"]';
class PagifySDK {
constructor() {
// Counter for unique iframe instances
this.instanceCounter = 1;
// Storage for callback functions indexed by instance ID
this.callbackStorage = {};
this.pdfCallbackStorage = {};
// Initialize message listener
this.initMessageListener();
}
/**
* Initialize message listener for iframe communication
*/
initMessageListener() {
if (typeof window !== 'undefined') {
window.addEventListener("message", (event) => {
if (event.data?.type === "renderpdf") {
const callback = this.callbackStorage[event.data?.iter];
if (callback) {
callback();
}
// Clean up callback storage
delete this.callbackStorage[event.data?.iter];
} else if (event.data?.type === "PDF_READY") {
// Handle PDF blob ready event
console.log('PDF blob ready:', event.data.blobUrl);
// Check if there's a specific callback for this instance
const instanceId = event.data?.iter;
if (instanceId && this.pdfCallbackStorage[instanceId]?.onPdfReady) {
this.pdfCallbackStorage[instanceId].onPdfReady(event.data.blobUrl);
delete this.pdfCallbackStorage[instanceId];
}
// Also trigger global PDF ready event for backward compatibility
window.dispatchEvent(new CustomEvent('pdfReady', {
detail: { blobUrl: event.data.blobUrl }
}));
} else if (event.data?.type === "PDF_ERROR") {
// Handle PDF generation error
console.error('PDF generation error:', event.data.error);
// Check if there's a specific callback for this instance
const instanceId = event.data?.iter;
if (instanceId && this.pdfCallbackStorage[instanceId]?.onPdfError) {
this.pdfCallbackStorage[instanceId].onPdfError(event.data.error);
delete this.pdfCallbackStorage[instanceId];
}
// Also trigger global PDF error event for backward compatibility
window.dispatchEvent(new CustomEvent('pdfError', {
detail: { error: event.data.error }
}));
}
else if (event.data?.type === "PREVIEW_READY") {
const instanceId = event.data?.iter;
if (instanceId && this.pdfCallbackStorage[instanceId]?.onPreviewReady) {
this.pdfCallbackStorage[instanceId].onPreviewReady({
success: true
});
delete this.pdfCallbackStorage[instanceId];
}
// Also trigger global preview ready event for backward compatibility
window.dispatchEvent(new CustomEvent('previewReady', {
detail: { success: true }
}));
} else if (event.data?.type === "PREVIEW_ERROR") {
console.error('Preview error:', event.data.error);
const instanceId = event.data?.iter;
if (instanceId && this.pdfCallbackStorage[instanceId]?.onPreviewReady) {
this.pdfCallbackStorage[instanceId].onPreviewReady({
success: false,
error: event.data.error
});
delete this.pdfCallbackStorage[instanceId];
}
window.dispatchEvent(new CustomEvent('previewError', {
detail: { success: false, error: event?.data?.error }
}));
}
}, false);
}
}
/**
* Load html2pdf library via script tag as fallback
*/
loadHtml2PdfLibrary() {
return new Promise((resolve, reject) => {
// Check if html2pdf is already available
if (typeof window.html2pdf === 'function') {
resolve(window.html2pdf);
return;
}
// Create script tag to load html2pdf
const script = document.createElement('script');
script.src = 'https://unpkg.com/html2pdf.js@0.10.1/dist/html2pdf.bundle.min.js';
script.onload = () => {
if (typeof window.html2pdf === 'function') {
resolve(window.html2pdf);
} else {
reject(new Error('html2pdf not available after loading script'));
}
};
script.onerror = () => reject(new Error('Failed to load html2pdf script'));
document.head.appendChild(script);
});
}
/**
* Render HTML content as a paginated PDF
* @param {Object} options - Configuration options for PDF rendering
* @param {string} options.body_html - Main HTML content for the PDF body
* @param {string} options.header_html - HTML content for page headers
* @param {string} options.footer_html - HTML content for page footers
* @param {string} options.head_html - Additional HTML for the <head> section
* @param {string} options.page_size - Page size (A4, Letter, etc.)
* @param {string} options.margin_left - Left page margin
* @param {string} options.margin_right - Right page margin
* @param {string} options.header_height - Height reserved for header
* @param {string} options.footer_height - Height reserved for footer
* @param {string} options.page_number_selector - CSS selector for page numbering
* @param {boolean} options.footer_only_on_last_page - Show footer only on last page
* @param {string} options.page_padding_top - Top padding for page content
* @param {function} options.callback - Function called when rendering completes
* @param {function} options.onPdfReady - Callback when PDF blob is ready (receives blobUrl)
* @param {function} options.onPdfError - Callback when PDF generation fails (receives error)
* @param {string} options.containerSelector - CSS selector for container element
* @param {boolean} options.isViewOnlySkipMakingPDF - If true, only render preview without generating PDF
* @param {function} options.onPreviewReady - Callback when in preview only mode, fired on iframe ready in DOM (receives {success: boolean, error?: string})
* @param {boolean} options.beautifyListItems - If true, apply bullet point fixes to list items (default: true)
* @returns {Promise<void>}
*/
async render({
body_html = "",
header_html = "",
footer_html = "",
head_html = "",
page_size = "A4",
margin_left = "0mm",
margin_right = "0mm",
header_height = "0mm",
footer_height = "0mm",
page_number_selector = "",
footer_only_on_last_page = false,
page_padding_top = "16px",
callback = null,
onPdfReady = null,
onPdfError = null,
containerSelector = null,
isViewOnlySkipMakingPDF = false,
onPreviewReady = null,
beautifyListItems = true,
}) {
try {
// Generate unique instance ID
const instanceId = this.instanceCounter++;
// Store callback for later execution
this.callbackStorage[instanceId] = callback;
// Store PDF callbacks for later execution
if (onPdfReady || onPdfError) {
this.pdfCallbackStorage[instanceId] = {
onPdfReady: onPdfReady,
onPdfError: onPdfError
};
}
if (onPreviewReady) {
this.pdfCallbackStorage[instanceId] = {
...this.pdfCallbackStorage[instanceId],
onPreviewReady: onPreviewReady
};
}
// Generate page numbering CSS if selector is provided
const pageNumberCSS = page_number_selector
? `${page_number_selector}::before {
content: "Page " counter(page) " of " counter(pages) " ";
}`
: "";
// Build complete HTML document for the iframe
const iframeHTML = this.buildIframeHTML({
instanceId,
body_html,
header_html,
footer_html,
head_html,
page_size,
margin_left,
margin_right,
header_height,
footer_height,
footer_only_on_last_page,
page_padding_top,
pageNumberCSS,
isViewOnlySkipMakingPDF,
beautifyListItems,
});
// Create and configure iframe
const iframe = this.createIframe(containerSelector);
iframe.srcdoc = iframeHTML;
// Insert iframe into specified container or body
const container = this.getContainer(containerSelector);
container.appendChild(iframe);
} catch (error) {
console.error("Pagify render error:", error);
if (onPdfError) {
onPdfError(error.message);
}
}
}
/**
* Build HTML content for the iframe
*/
buildIframeHTML({
instanceId,
body_html,
header_html,
footer_html,
head_html,
page_size,
margin_left,
margin_right,
header_height,
footer_height,
footer_only_on_last_page,
page_padding_top,
pageNumberCSS,
isViewOnlySkipMakingPDF,
beautifyListItems,
}) {
return `
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
// Configure Paged.js
window.PagedConfig = {
auto: false,
}
<\/script>
<script>
let totalPages;
let isViewOnly = ${isViewOnlySkipMakingPDF};
${!isViewOnlySkipMakingPDF ? `${this.getPdfGenerationScript(instanceId, beautifyListItems, page_size)}` : ''}
function initializePagination() {
${this.getPagedJSInitScript(instanceId, isViewOnlySkipMakingPDF)}
}
<\/script>
<script src="https://unpkg.com/pagedjs@0.4.3/dist/paged.polyfill.js" onload="initializePagination()"><\/script>
<style>
/* Ensure print colors are preserved */
body {
-webkit-print-color-adjust: exact !important;
print-color-adjust: exact !important;
margin: 0;
padding: 0;
}
/* Page numbering styles */
${pageNumberCSS}
/* Header and footer positioning */
.header {
position: running(header);
}
.footer {
position: running(footer);
}
/* Paged.js content styling */
.pagedjs_page_content {
border-bottom-width: 1px;
border-top-width: 1px;
--tw-border-opacity: 1;
border-color: rgba(218, 222, 227, var(--tw-border-opacity));
padding-top: ${page_padding_top};
}
.pagedjs_pages {
align-items: center;
display: flex;
flex: 1;
flex-direction: column;
}
/* Prevent table rows from breaking across pages */
tr {
break-inside: avoid;
}
/* Page layout configuration */
@page {
margin-left: ${margin_left};
margin-right: ${margin_right};
margin-top: ${header_height};
margin-bottom: ${footer_height};
size: ${page_size};
@bottom-center {
content: element(footer);
}
@top-center {
content: element(header);
}
}
/* Base64 image optimization */
img {
max-width: 100%;
height: auto;
}
/* Print-friendly table styles */
table {
border-collapse: collapse;
width: 100%;
}
/* Page break controls */
.page-break-before {
page-break-before: always;
}
.page-break-after {
page-break-after: always;
}
.page-break-inside-avoid {
page-break-inside: avoid;
}
</style>
${head_html}
</head>
<body>
<!-- Header content (appears on every page) -->
<div class="header" style="width: 100%">
${header_html}
</div>
<!-- Footer content (conditional positioning) -->
${footer_only_on_last_page ? "" : `<div class="footer" style="width: 100%">
${footer_html}
</div>`}
<!-- Main body content -->
${body_html}
<!-- Footer on last page only (if specified) -->
${footer_only_on_last_page ? `<div class="footer" style="width: 100%">
${footer_html}
</div>` : ""}
</body>
</html>
`;
}
/**
* Get Paged.js initialization script
*/
getPagedJSInitScript(instanceId, isViewOnlySkipMakingPDF) {
return `
// Wait for fonts to load before starting pagination
document.fonts.ready.then(async () => {
console.log("Fonts are ready");
try {
// Import Paged.js dynamically
const { Previewer, Handler, registerHandlers } = window.Paged;
class RepeatingTableHeaders extends Handler {
constructor(chunker, polisher, caller) {
super(chunker, polisher, caller);
}
beforePageLayout(page) {
// console.log("page", page);
// page.height = 200;
}
afterPageLayout(pageElement, page, breakToken, chunker) {
// Find all split table elements
let tables = pageElement.querySelectorAll("table[data-split-from]");
tables.forEach((table) => {
// There is an edge case where the previous page table
// has zero height (isn't visible).
// To avoid double header we will only add header if there is none.
let tableHeader = table.querySelector("thead");
if (tableHeader) {
return;
}
// Get the reference UUID of the node
let ref = table.dataset.ref;
// Find the node in the original source
let sourceTable = chunker.source.querySelector("[data-ref='" + ref + "']");
// Find if there is a header
let sourceHeader = sourceTable.querySelector("thead");
if (sourceHeader) {
console.log("Table header was cloned, because it is splitted.");
// Clone the header element
let clonedHeader = sourceHeader.cloneNode(true);
// Insert the header at the start of the split table
table.insertBefore(clonedHeader, table.firstChild);
}
});
// Find all tables
tables = pageElement.querySelectorAll("table");
// special case which might not fit for everyone
tables.forEach((table) => {
// if the table has no rows in body, hide it.
// This happens because my render engine creates empty tables.
let sourceBody = table.querySelector("tbody > tr");
if (!sourceBody) {
console.log("Table was hidden, because it has no rows in tbody.");
table.style.visibility = "hidden";
table.style.position = "absolute";
var lineSpacer = table.nextSibling;
if (lineSpacer) {
lineSpacer.style.visibility = "hidden";
lineSpacer.style.position = "absolute";
}
}
});
try {
// setting the page to show overflowing content
let contents = pageElement.querySelectorAll(".pagedjs_page_content");
contents.forEach((content) => {
content.style.height = 'max-content';
});
} catch (e) {
console.warn("Failed to set page content height to max-content", e);
}
}
}
registerHandlers(RepeatingTableHeaders);
console.log('Paged.js imported successfully');
// Initialize pagination
const previewer = new Previewer();
const result = await previewer.preview();
console.log('Paged.js pagination complete:', result);
totalPages = result.total;
// Notify parent window that rendering is complete
window.parent.postMessage({
type: "renderpdf",
iter: ${instanceId}
}, "*");
if (${isViewOnlySkipMakingPDF}) {
window.parent.postMessage({
type: "PREVIEW_READY",
iter: ${instanceId}
}, "*");
} else {
// PDF generation mode
if (typeof generatePdfBlob === "function") {
generatePdfBlob();
}
}
} catch (error) {
console.error('Failed to load or initialize Paged.js:', error);
if (${isViewOnlySkipMakingPDF}) {
window.parent.postMessage({
type: "PREVIEW_ERROR",
error: "Failed to initialize Paged.js: " + error.message,
iter: ${instanceId}
}, "*");
} else {
window.parent.postMessage({
type: "PDF_ERROR",
error: "Failed to initialize Paged.js: " + error.message,
iter: ${instanceId}
}, "*");
}
}
});
`;
}
/**
* Get PDF generation script
*/
getPdfGenerationScript(instanceId, beautifyListItems = true, page_size = "a4") {
return `
function getBulletChar(listStyleType) {
const bulletMap = {
'disc': '•',
'circle': '○',
'square': '▪',
'none': '',
};
return bulletMap[listStyleType] || '•';
}
function beautifyListItemsHandler(originalBody) {
try {
const clonedBody = originalBody?.cloneNode?.(true);
if (!clonedBody) return originalBody;
clonedBody?.querySelectorAll?.('ul, ol')?.forEach?.((list) => {
list?.querySelectorAll?.('li')?.forEach?.((li) => {
const originalLi = originalBody?.querySelector?.(\`[data-ref="\${li?.getAttribute?.('data-ref')}"]\`) || li;
const computedStyle = window?.getComputedStyle?.(originalLi);
if (computedStyle?.listStyleType !== 'none') {
li.style.listStyleType = 'none';
li.style.position = 'relative';
li.style.paddingLeft = '-1.2em';
li.style.paddingTop = '-0.3em';
const bullet = document?.createElement?.('span');
if (bullet) {
bullet.textContent = getBulletChar(computedStyle?.listStyleType);
bullet.style.cssText = \`
position: absolute;
left: -1.4em;
top: -0.28em;
line-height: 1.25rem;
font-size: 1.2em;
font-weight: bold;
color: currentColor;
\`;
li?.insertBefore?.(bullet, li?.firstChild);
}
}
});
});
return clonedBody;
} catch (error) {
console.error('beautifyListItemsHandler failed:', error);
return originalBody;
}
}
// Generate PDF blob function
async function generatePdfBlob() {
try {
console.log('Starting PDF generation...');
let html2pdfLib;
await new Promise((resolve, reject) => {
if (typeof window.html2pdf === 'function') {
resolve();
return;
}
const script = document.createElement('script');
script.src = 'https://unpkg.com/html2pdf.js@0.10.1/dist/html2pdf.bundle.min.js';
script.onload = () => {
if (typeof window.html2pdf === 'function') {
resolve();
} else {
reject(new Error('html2pdf not available after loading script'));
}
};
script.onerror = () => reject(new Error('Failed to load html2pdf script'));
document.head.appendChild(script);
});
html2pdfLib = window.html2pdf;
console.log('html2pdf loaded successfully');
await startPdfGeneration();
} catch (error) {
console.error("PDF generation error:", error);
window.parent.postMessage({
type: "PDF_ERROR",
error: error.message,
iter: ${instanceId}
}, "*");
}
}
async function startPdfGeneration() {
try {
const originalBody = document.body;
let targetElement = originalBody;
if (${beautifyListItems}) {
targetElement = beautifyListItemsHandler(originalBody);
}
console.log('Using body element for PDF generation');
console.log('Element innerHTML length:', targetElement?.innerHTML?.length);
if (!targetElement || targetElement?.innerHTML?.trim()?.length === 0) {
throw new Error('No content found in body element');
}
console.log('Estimated pages:', totalPages);
const opt = {
margin: [0,0,0,0],
filename: "document.pdf",
image: {
type: "jpeg",
quality: 0.98
},
html2canvas: {
scale: 2,
useCORS: true,
allowTaint: false,
backgroundColor: '#ffffff'
},
jsPDF: {
unit: "mm",
format: ${JSON.stringify(page_size.toLowerCase())},
orientation: "portrait",
compress: true
}
};
console.log('Starting html2pdf conversion with body element');
window.html2pdf().set(opt).from(targetElement)
.toPdf()
.get("pdf").then(pdf => {
const pageCount = pdf.internal.getNumberOfPages();
console.log('Generated PDF with', pageCount, 'pages');
// Remove extra pages if necessary
if (pageCount > totalPages && totalPages > 0) {
for (let i = pageCount; i > totalPages; i--) {
pdf.deletePage(i);
}
}
})
.outputPdf("blob").then(function (blob) {
console.log('PDF blob generated:', blob);
const blobUrl = URL.createObjectURL(blob);
console.log("Blob URL:", blobUrl);
window.parent.postMessage({
type: "PDF_READY",
blobUrl: blobUrl,
iter: ${instanceId}
}, "*");
})
.catch(error => {
console.error("PDF generation failed:", error);
window.parent.postMessage({
type: "PDF_ERROR",
error: error.message,
iter: ${instanceId}
}, "*");
});
} catch (error) {
console.error("PDF generation error:", error);
window.parent.postMessage({
type: "PDF_ERROR",
error: error.message,
iter: ${instanceId}
}, "*");
}
}
`;
}
/**
* Create and configure iframe
*/
createIframe(containerSelector) {
const iframe = document.createElement("iframe");
iframe.setAttribute('data-pagify-iframe', 'true');
// Configure iframe styling based on container selector
if (containerSelector) {
// If container is specified, make iframe fill the container
iframe.style.width = "100%";
iframe.style.height = "100%";
iframe.style.border = "none";
} else {
// If no container, hide iframe off-screen
iframe.style.position = "absolute";
iframe.style.top = "-9999px";
iframe.style.left = "-9999px";
iframe.style.border = "none";
}
return iframe;
}
cleanupIframesOnContainerLevel(container) {
const oldPagifyIframes = container?.querySelectorAll(pagifyIframeIdentifier) || [];
oldPagifyIframes?.forEach(iframe => {
iframe?.remove();
});
}
cleanupIframesOnDOMLevel() {
const oldPagifyIframes = document?.querySelectorAll(pagifyIframeIdentifier) || [];
oldPagifyIframes?.forEach(iframe => {
iframe?.remove();
});
}
/**
* Get container element for iframe
*/
getContainer(containerSelector) {
let container;
if (containerSelector) {
container = document.querySelector(containerSelector);
if (!container) {
console.warn(`Container with selector "${containerSelector}" not found. Using document.body instead.`);
container = document.body;
}
this.cleanupIframesOnContainerLevel(container);
} else {
container = document.body;
this.cleanupIframesOnDOMLevel();
}
return container;
}
/**
* Direct PDF generation without iframe (for Node.js environments)
* @param {Object} options - Same options as render method
* @returns {Promise<Blob>} - PDF blob
*/
async generatePDF(options) {
if (typeof window === "undefined") {
throw new Error("Direct PDF generation is only available in browser environments");
}
return new Promise(async (resolve, reject) => {
try {
const modifiedOptions = {
...options,
onPdfReady: (blobUrl) => {
// Convert blob URL back to blob
fetch(blobUrl)
.then(response => response.blob())
.then(blob => resolve(blob))
.catch(error => reject(error));
},
onPdfError: (error) => {
reject(new Error(error));
}
};
await this.render(modifiedOptions);
} catch (error) {
reject(error);
}
});
}
}
// Create singleton instance
const pagify = new PagifySDK();
// Export for ES modules
export default pagify;
export { PagifySDK };
// Also expose on window for browser compatibility
if (typeof window !== "undefined") {
window.pagify = pagify;
}